file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
list
attention_mask
list
labels
list
// SPDX-License-Identifier: AGPL-3.0-only // Copyright (C) 2017, 2018, 2019, 2020 dbrock, rain, mrchico, d-xo pragma solidity ^0.8.13; contract NoRevertToken { // --- ERC20 Data --- string public constant name = "Token"; string public constant symbol = "TKN"; uint8 public decimals = 18; uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; event Approval(address indexed src, address indexed guy, uint256 wad); event Transfer(address indexed src, address indexed dst, uint256 wad); // --- Init --- constructor(uint256 _totalSupply) public { totalSupply = _totalSupply; balanceOf[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } // --- Token --- function transfer(address dst, uint256 wad) external returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom( address src, address dst, uint256 wad ) public virtual returns (bool) { if (balanceOf[src] < wad) return false; // insufficient src bal if (balanceOf[dst] >= (type(uint256).max - wad)) return false; // dst bal too high if (src != msg.sender && allowance[src][msg.sender] != type(uint256).max) { if (allowance[src][msg.sender] < wad) return false; // insufficient allowance allowance[src][msg.sender] = allowance[src][msg.sender] - wad; } balanceOf[src] = balanceOf[src] - wad; balanceOf[dst] = balanceOf[dst] + wad; emit Transfer(src, dst, wad); return true; } function approve(address usr, uint256 wad) external virtual returns (bool) { allowance[msg.sender][usr] = wad; emit Approval(msg.sender, usr, wad); return true; } }
--- ERC20 Data --- --- Init ---
contract NoRevertToken { string public constant name = "Token"; string public constant symbol = "TKN"; uint8 public decimals = 18; uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; event Approval(address indexed src, address indexed guy, uint256 wad); event Transfer(address indexed src, address indexed dst, uint256 wad); constructor(uint256 _totalSupply) public { totalSupply = _totalSupply; balanceOf[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function transfer(address dst, uint256 wad) external returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom( address src, address dst, uint256 wad ) public virtual returns (bool) { if (src != msg.sender && allowance[src][msg.sender] != type(uint256).max) { allowance[src][msg.sender] = allowance[src][msg.sender] - wad; } balanceOf[src] = balanceOf[src] - wad; balanceOf[dst] = balanceOf[dst] + wad; emit Transfer(src, dst, wad); return true; } function transferFrom( address src, address dst, uint256 wad ) public virtual returns (bool) { if (src != msg.sender && allowance[src][msg.sender] != type(uint256).max) { allowance[src][msg.sender] = allowance[src][msg.sender] - wad; } balanceOf[src] = balanceOf[src] - wad; balanceOf[dst] = balanceOf[dst] + wad; emit Transfer(src, dst, wad); return true; } function approve(address usr, uint256 wad) external virtual returns (bool) { allowance[msg.sender][usr] = wad; emit Approval(msg.sender, usr, wad); return true; } }
2,560,387
[ 1, 6062, 4232, 39, 3462, 1910, 9948, 9948, 4378, 9948, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 2631, 426, 1097, 1345, 288, 203, 225, 533, 1071, 5381, 508, 273, 315, 1345, 14432, 203, 225, 533, 1071, 5381, 3273, 273, 315, 56, 47, 50, 14432, 203, 225, 2254, 28, 1071, 15105, 273, 6549, 31, 203, 225, 2254, 5034, 1071, 2078, 3088, 1283, 31, 203, 203, 225, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 11013, 951, 31, 203, 225, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 1071, 1699, 1359, 31, 203, 203, 225, 871, 1716, 685, 1125, 12, 2867, 8808, 1705, 16, 1758, 8808, 3058, 93, 16, 2254, 5034, 341, 361, 1769, 203, 225, 871, 12279, 12, 2867, 8808, 1705, 16, 1758, 8808, 3046, 16, 2254, 5034, 341, 361, 1769, 203, 203, 203, 225, 3885, 12, 11890, 5034, 389, 4963, 3088, 1283, 13, 1071, 288, 203, 565, 2078, 3088, 1283, 273, 389, 4963, 3088, 1283, 31, 203, 565, 11013, 951, 63, 3576, 18, 15330, 65, 273, 389, 4963, 3088, 1283, 31, 203, 565, 3626, 12279, 12, 2867, 12, 20, 3631, 1234, 18, 15330, 16, 389, 4963, 3088, 1283, 1769, 203, 225, 289, 203, 203, 225, 445, 7412, 12, 2867, 3046, 16, 2254, 5034, 341, 361, 13, 3903, 1135, 261, 6430, 13, 288, 203, 565, 327, 7412, 1265, 12, 3576, 18, 15330, 16, 3046, 16, 341, 361, 1769, 203, 225, 289, 203, 203, 225, 445, 7412, 1265, 12, 203, 565, 1758, 1705, 16, 203, 565, 1758, 3046, 16, 203, 565, 2254, 5034, 341, 361, 203, 225, 262, 1071, 5024, 1135, 261, 6430, 13, 288, 203, 203, 565, 309, 2 ]
./partial_match/1/0x1c7f0Dc294397637Dc674992D632Ac2570711dbD/sources/ERC721.sol
* @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"); uint256 size; if(size == _sizeContract) { require(!IChallenge(payable(to)).isFinished(), "ERC20: Challenge was finished"); } _beforeTokenTransfer(from, to, tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); }
4,246,952
[ 1, 1429, 18881, 1375, 2316, 548, 68, 628, 1375, 2080, 68, 358, 1375, 869, 8338, 225, 2970, 1061, 7423, 358, 288, 13866, 1265, 5779, 333, 709, 10522, 1158, 17499, 603, 1234, 18, 15330, 18, 29076, 30, 300, 1375, 869, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 2316, 548, 68, 1147, 1297, 506, 16199, 635, 1375, 2080, 8338, 7377, 1282, 279, 288, 5912, 97, 871, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 565, 262, 2713, 5024, 288, 203, 3639, 2583, 12, 654, 39, 27, 5340, 18, 8443, 951, 12, 2316, 548, 13, 422, 628, 16, 315, 654, 39, 27, 5340, 30, 7412, 628, 11332, 3410, 8863, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 27, 5340, 30, 7412, 358, 326, 3634, 1758, 8863, 203, 203, 3639, 2254, 5034, 963, 31, 203, 3639, 309, 12, 1467, 422, 389, 1467, 8924, 13, 288, 203, 5411, 2583, 12, 5, 45, 18359, 12, 10239, 429, 12, 869, 13, 2934, 291, 10577, 9334, 315, 654, 39, 3462, 30, 1680, 8525, 1703, 6708, 8863, 203, 3639, 289, 7010, 203, 3639, 389, 5771, 1345, 5912, 12, 2080, 16, 358, 16, 1147, 548, 1769, 203, 203, 203, 3639, 389, 70, 26488, 63, 2080, 65, 3947, 404, 31, 203, 3639, 389, 70, 26488, 63, 869, 65, 1011, 404, 31, 203, 3639, 389, 995, 414, 63, 2316, 548, 65, 273, 358, 31, 203, 203, 3639, 3626, 12279, 12, 2080, 16, 358, 16, 1147, 548, 1769, 203, 203, 3639, 389, 5205, 1345, 5912, 12, 2080, 16, 358, 16, 1147, 548, 1769, 203, 565, 289, 203, 21281, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* ProposalCreator.sol */ pragma solidity >=0.4.0 <0.7.0; import "../contracts/UserManager.sol"; import "../contracts/ProposalManager.sol"; /* <Summary> This contract is used by an account to create an account recovery proposal. All functions in this contract are used by the new new account. */ contract ProposalCreator { UserManager UMI; // Connects to the list of users on the network TransactionManager TMI; // Connects to the list of transaction data ProposalManager PMI; // Connects to the list of proposals // Used to originally deploy the contract constructor(address _UM, address _TM, address _PM) public { UMI = UserManager(_UM); TMI = TransactionManager(_TM); PMI = ProposalManager(_PM); } // Used to create a new account recovery proposal function StartProposal(address _oldAccount) external { // Checks if there is already an active proposal for this account PMI.validProposal(_oldAccount, msg.sender); // Price of the account recover proposal: Used to pay voters uint price = UMI.getUser(_oldAccount).balance() / 20; // Creates Proposal and adds it to the active proposal map PMI.AddActiveProposal(_oldAccount, msg.sender, new Proposal(price)); } // Used to view the price of the account recover proposal function ViewPrice(address _oldAccount) external view returns (uint) { return PMI.getProposal(_oldAccount, msg.sender).price(); } // Used to pay for the account recover proposal function Pay(address _oldAccount, bool _pay) external { if (_pay){ // The new account is paying for the proposal // Finds the person in the network Person newAccount = UMI.getUser(msg.sender); // Pays for the proposal PMI.getProposal(_oldAccount, msg.sender).Pay(newAccount); } else{ // The new account will not pay PMI.archiveProposal(_oldAccount, msg.sender); // Deletes proposal } } // Used to add indicated voters to the proposal function AddTradePartners(address _oldAccount, address[] calldata _tradePartners) external { // Gets voters from past account recovery attempts address[] memory archivedVoters = PMI.getArchivedVoter(_oldAccount); // Finds proposal and adds indicated voters PMI.getProposal(_oldAccount, msg.sender).AddTradePartners( msg.sender, _oldAccount, _tradePartners, archivedVoters, TMI, PMI); } // Returns a list of voters for an account recovery proposal function ViewVoters(address _oldAccount) external view returns (address[] memory) { return PMI.getProposal(_oldAccount, msg.sender).getVoters(); } // Randomly selects a trade partner. Also adds the last randomly selected // trade partner to the list of voters function RandomTradingPartner(address _oldAccount, bool _veto) external { PMI.getProposal(_oldAccount, msg.sender).RandomTradingPartner(_veto); } // Returns the current randomly selected voter function ViewRandomTradingPartner(address _oldAccount) external view returns (address) { return PMI.getProposal(_oldAccount, msg.sender).lastOtherPartner(); } // Checks transaction data and adds it to the proposal to be viewed later function MakeTransactionDataSet( address _oldAccount, address _voter, uint _timeStamp, uint _amount, string calldata _description, string calldata _importantNotes, string calldata _location, string calldata _itemsInTrade) external { // Checks if there exists a transaction with this infromation TMI.Equal(_oldAccount, _voter, _timeStamp, _amount); Proposal temp = PMI.getProposal(_oldAccount, msg.sender); // Checks if this address is actually a voter require(temp.ContainsVoter(_voter), "Invalid Voter"); // Adds the tranaction data to the proposal to be viewed by the voter temp.AddTransactionDataSet(_voter, _timeStamp, _amount, _description, _importantNotes, _location, _itemsInTrade); } } /* require(bytes(_description).length > 0 && bytes(_location).length > 0 && bytes(_itemsInTrade).length > 0, "Must provide private infromation"); */ // 6471200 // 6568080 // 6530283 // 6096988 // 5939582 // 5762541 // 5677263 // 5643513 // 5807176
Connects to the list of proposals
ProposalManager PMI;
884,836
[ 1, 21500, 358, 326, 666, 434, 450, 22536, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 14592, 1318, 453, 7492, 31, 1082, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.6.12; pragma experimental ABIEncoderV2; interface ERC20 { function totalSupply() external view returns (uint); function decimals() external view returns (uint); function balanceOf(address tokenOwner) external view returns (uint balance); function allowance(address tokenOwner, address spender) external view returns (uint remaining); function transfer(address to, uint tokens) external returns (bool success); function approve(address spender, uint tokens) external returns (bool success); function transferFrom(address from, address to, uint tokens) external returns (bool success); } interface IFeature { enum OwnerSignature { Anyone, // Anyone Required, // Owner required Optional, // Owner and/or guardians Disallowed // guardians only } /** * @notice Utility method to recover any ERC20 token that was sent to the Feature by mistake. * @param _token The token to recover. */ function recoverToken(address _token) external; /** * @notice Inits a Feature for a wallet by e.g. setting some wallet specific parameters in storage. * @param _wallet The wallet. */ function init(address _wallet) external; /** * @notice Helper method to check if an address is an authorised feature of a target wallet. * @param _wallet The target wallet. * @param _feature The address. */ function isFeatureAuthorisedInVersionManager(address _wallet, address _feature) external view returns (bool); /** * @notice Gets the number of valid signatures that must be provided to execute a * specific relayed transaction. * @param _wallet The target wallet. * @param _data The data of the relayed transaction. * @return The number of required signatures and the wallet owner signature requirement. */ function getRequiredSignatures(address _wallet, bytes calldata _data) external view returns (uint256, OwnerSignature); /** * @notice Gets the list of static call signatures that this feature responds to on behalf of wallets */ function getStaticCallSignatures() external view returns (bytes4[] memory); } interface IGuardianStorage { /** * @notice Lets an authorised module add a guardian to a wallet. * @param _wallet The target wallet. * @param _guardian The guardian to add. */ function addGuardian(address _wallet, address _guardian) external; /** * @notice Lets an authorised module revoke a guardian from a wallet. * @param _wallet The target wallet. * @param _guardian The guardian to revoke. */ function revokeGuardian(address _wallet, address _guardian) external; /** * @notice Checks if an account is a guardian for a wallet. * @param _wallet The target wallet. * @param _guardian The account. * @return true if the account is a guardian for a wallet. */ function isGuardian(address _wallet, address _guardian) external view returns (bool); function isLocked(address _wallet) external view returns (bool); function getLock(address _wallet) external view returns (uint256); function getLocker(address _wallet) external view returns (address); function setLock(address _wallet, uint256 _releaseAfter) external; function getGuardians(address _wallet) external view returns (address[] memory); function guardianCount(address _wallet) external view returns (uint256); } interface ILimitStorage { struct Limit { // the current limit uint128 current; // the pending limit if any uint128 pending; // when the pending limit becomes the current limit uint64 changeAfter; } struct DailySpent { // The amount already spent during the current period uint128 alreadySpent; // The end of the current period uint64 periodEnd; } function setLimit(address _wallet, Limit memory _limit) external; function getLimit(address _wallet) external view returns (Limit memory _limit); function setDailySpent(address _wallet, DailySpent memory _dailySpent) external; function getDailySpent(address _wallet) external view returns (DailySpent memory _dailySpent); function setLimitAndDailySpent(address _wallet, Limit memory _limit, DailySpent memory _dailySpent) external; function getLimitAndDailySpent(address _wallet) external view returns (Limit memory _limit, DailySpent memory _dailySpent); } interface ILockStorage { function isLocked(address _wallet) external view returns (bool); function getLock(address _wallet) external view returns (uint256); function getLocker(address _wallet) external view returns (address); function setLock(address _wallet, address _locker, uint256 _releaseAfter) external; } interface IModule { /** * @notice Inits a module for a wallet by e.g. setting some wallet specific parameters in storage. * @param _wallet The wallet. */ function init(address _wallet) external; /** * @notice Adds a module to a wallet. Cannot execute when wallet is locked (or under recovery) * @param _wallet The target wallet. * @param _module The modules to authorise. */ function addModule(address _wallet, address _module) external; } interface IModuleRegistry { function registerModule(address _module, bytes32 _name) external; function deregisterModule(address _module) external; function registerUpgrader(address _upgrader, bytes32 _name) external; function deregisterUpgrader(address _upgrader) external; function recoverToken(address _token) external; function moduleInfo(address _module) external view returns (bytes32); function upgraderInfo(address _upgrader) external view returns (bytes32); function isRegisteredModule(address _module) external view returns (bool); function isRegisteredModule(address[] calldata _modules) external view returns (bool); function isRegisteredUpgrader(address _upgrader) external view returns (bool); } interface ITransferStorage { function setWhitelist(address _wallet, address _target, uint256 _value) external; function getWhitelist(address _wallet, address _target) external view returns (uint256); } interface IVersionManager { /** * @notice Returns true if the feature is authorised for the wallet * @param _wallet The target wallet. * @param _feature The feature. */ function isFeatureAuthorised(address _wallet, address _feature) external view returns (bool); /** * @notice Lets a feature (caller) invoke a wallet. * @param _wallet The target wallet. * @param _to The target address for the transaction. * @param _value The value of the transaction. * @param _data The data of the transaction. */ function checkAuthorisedFeatureAndInvokeWallet( address _wallet, address _to, uint256 _value, bytes calldata _data ) external returns (bytes memory _res); /* ******* Backward Compatibility with old Storages and BaseWallet *************** */ /** * @notice Sets a new owner for the wallet. * @param _newOwner The new owner. */ function setOwner(address _wallet, address _newOwner) external; /** * @notice Lets a feature write data to a storage contract. * @param _wallet The target wallet. * @param _storage The storage contract. * @param _data The data of the call */ function invokeStorage(address _wallet, address _storage, bytes calldata _data) external; /** * @notice Upgrade a wallet to a new version. * @param _wallet the wallet to upgrade * @param _toVersion the new version */ function upgradeWallet(address _wallet, uint256 _toVersion) external; } interface IWallet { /** * @notice Returns the wallet owner. * @return The wallet owner address. */ function owner() external view returns (address); /** * @notice Returns the number of authorised modules. * @return The number of authorised modules. */ function modules() external view returns (uint); /** * @notice Sets a new owner for the wallet. * @param _newOwner The new owner. */ function setOwner(address _newOwner) external; /** * @notice Checks if a module is authorised on the wallet. * @param _module The module address to check. * @return `true` if the module is authorised, otherwise `false`. */ function authorised(address _module) external view returns (bool); /** * @notice Returns the module responsible for a static call redirection. * @param _sig The signature of the static call. * @return the module doing the redirection */ function enabled(bytes4 _sig) external view returns (address); /** * @notice Enables/Disables a module. * @param _module The target module. * @param _value Set to `true` to authorise the module. */ function authoriseModule(address _module, bool _value) external; /** * @notice Enables a static method by specifying the target module to which the call must be delegated. * @param _module The target module. * @param _method The static method signature. */ function enableStaticCall(address _module, bytes4 _method) external; } contract Owned { // The owner address public owner; event OwnerChanged(address indexed _newOwner); /** * @notice Throws if the sender is not the owner. */ modifier onlyOwner { require(msg.sender == owner, "Must be owner"); _; } constructor() public { owner = msg.sender; } /** * @notice Lets the owner transfer ownership of the contract to a new owner. * @param _newOwner The new owner. */ function changeOwner(address _newOwner) external onlyOwner { require(_newOwner != address(0), "Address must not be null"); owner = _newOwner; emit OwnerChanged(_newOwner); } } 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; } } library Utils { /** * @notice Helper method to recover the signer at a given position from a list of concatenated signatures. * @param _signedHash The signed hash * @param _signatures The concatenated signatures. * @param _index The index of the signature to recover. */ function recoverSigner(bytes32 _signedHash, bytes memory _signatures, uint _index) internal pure returns (address) { uint8 v; bytes32 r; bytes32 s; // we jump 32 (0x20) as the first slot of bytes contains the length // we jump 65 (0x41) per signature // for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(_signatures, add(0x20,mul(0x41,_index)))) s := mload(add(_signatures, add(0x40,mul(0x41,_index)))) v := and(mload(add(_signatures, add(0x41,mul(0x41,_index)))), 0xff) } require(v == 27 || v == 28); address recoveredAddress = ecrecover(_signedHash, v, r, s); require(recoveredAddress != address(0), "Utils: ecrecover returned 0"); return recoveredAddress; } /** * @notice Helper method to parse data and extract the method signature. */ function functionPrefix(bytes memory _data) internal pure returns (bytes4 prefix) { require(_data.length >= 4, "RM: Invalid functionPrefix"); // solhint-disable-next-line no-inline-assembly assembly { prefix := mload(add(_data, 0x20)) } } /** * @notice Returns ceil(a / b). */ function ceil(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; if (a % b == 0) { return c; } else { return c + 1; } } function min(uint256 a, uint256 b) internal pure returns (uint256) { if (a < b) { return a; } return b; } } contract BaseFeature is IFeature { // Empty calldata bytes constant internal EMPTY_BYTES = ""; // Mock token address for ETH address constant internal ETH_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // The address of the Lock storage ILockStorage internal lockStorage; // The address of the Version Manager IVersionManager internal versionManager; event FeatureCreated(bytes32 name); /** * @notice Throws if the wallet is locked. */ modifier onlyWhenUnlocked(address _wallet) { require(!lockStorage.isLocked(_wallet), "BF: wallet locked"); _; } /** * @notice Throws if the sender is not the VersionManager. */ modifier onlyVersionManager() { require(msg.sender == address(versionManager), "BF: caller must be VersionManager"); _; } /** * @notice Throws if the sender is not the owner of the target wallet. */ modifier onlyWalletOwner(address _wallet) { require(isOwner(_wallet, msg.sender), "BF: must be wallet owner"); _; } /** * @notice Throws if the sender is not an authorised feature of the target wallet. */ modifier onlyWalletFeature(address _wallet) { require(versionManager.isFeatureAuthorised(_wallet, msg.sender), "BF: must be a wallet feature"); _; } /** * @notice Throws if the sender is not the owner of the target wallet or the feature itself. */ modifier onlyWalletOwnerOrFeature(address _wallet) { // Wrapping in an internal method reduces deployment cost by avoiding duplication of inlined code verifyOwnerOrAuthorisedFeature(_wallet, msg.sender); _; } constructor( ILockStorage _lockStorage, IVersionManager _versionManager, bytes32 _name ) public { lockStorage = _lockStorage; versionManager = _versionManager; emit FeatureCreated(_name); } /** * @inheritdoc IFeature */ function recoverToken(address _token) external virtual override { uint total = ERC20(_token).balanceOf(address(this)); _token.call(abi.encodeWithSelector(ERC20(_token).transfer.selector, address(versionManager), total)); } /** * @notice Inits the feature for a wallet by doing nothing. * @dev !! Overriding methods need make sure `init()` can only be called by the VersionManager !! * @param _wallet The wallet. */ function init(address _wallet) external virtual override {} /** * @inheritdoc IFeature */ function getRequiredSignatures(address, bytes calldata) external virtual view override returns (uint256, OwnerSignature) { revert("BF: disabled method"); } /** * @inheritdoc IFeature */ function getStaticCallSignatures() external virtual override view returns (bytes4[] memory _sigs) {} /** * @inheritdoc IFeature */ function isFeatureAuthorisedInVersionManager(address _wallet, address _feature) public override view returns (bool) { return versionManager.isFeatureAuthorised(_wallet, _feature); } /** * @notice Checks that the wallet address provided as the first parameter of _data matches _wallet * @return false if the addresses are different. */ function verifyData(address _wallet, bytes calldata _data) internal pure returns (bool) { require(_data.length >= 36, "RM: Invalid dataWallet"); address dataWallet = abi.decode(_data[4:], (address)); return dataWallet == _wallet; } /** * @notice Helper method to check if an address is the owner of a target wallet. * @param _wallet The target wallet. * @param _addr The address. */ function isOwner(address _wallet, address _addr) internal view returns (bool) { return IWallet(_wallet).owner() == _addr; } /** * @notice Verify that the caller is an authorised feature or the wallet owner. * @param _wallet The target wallet. * @param _sender The caller. */ function verifyOwnerOrAuthorisedFeature(address _wallet, address _sender) internal view { require(isFeatureAuthorisedInVersionManager(_wallet, _sender) || isOwner(_wallet, _sender), "BF: must be owner or feature"); } /** * @notice Helper method to invoke a wallet. * @param _wallet The target wallet. * @param _to The target address for the transaction. * @param _value The value of the transaction. * @param _data The data of the transaction. */ function invokeWallet(address _wallet, address _to, uint256 _value, bytes memory _data) internal returns (bytes memory _res) { _res = versionManager.checkAuthorisedFeatureAndInvokeWallet(_wallet, _to, _value, _data); } } contract VersionManager is IVersionManager, IModule, BaseFeature, Owned { bytes32 constant NAME = "VersionManager"; bytes4 constant internal ADD_MODULE_PREFIX = bytes4(keccak256("addModule(address,address)")); bytes4 constant internal UPGRADE_WALLET_PREFIX = bytes4(keccak256("upgradeWallet(address,uint256)")); // Last bundle version uint256 public lastVersion; // Minimum allowed version uint256 public minVersion = 1; // Current bundle version for a wallet mapping(address => uint256) public walletVersions; // [wallet] => [version] // Features per version mapping(address => mapping(uint256 => bool)) public isFeatureInVersion; // [feature][version] => bool // Features requiring initialization for a wallet mapping(uint256 => address[]) public featuresToInit; // [version] => [features] // Supported static call signatures mapping(uint256 => bytes4[]) public staticCallSignatures; // [version] => [sigs] // Features executing static calls mapping(uint256 => mapping(bytes4 => address)) public staticCallExecutors; // [version][sig] => [feature] // Authorised Storages mapping(address => bool) public isStorage; // [storage] => bool event VersionAdded(uint256 _version, address[] _features); event WalletUpgraded(address indexed _wallet, uint256 _version); // The Module Registry IModuleRegistry private registry; /* ***************** Constructor ************************* */ constructor( IModuleRegistry _registry, ILockStorage _lockStorage, IGuardianStorage _guardianStorage, ITransferStorage _transferStorage, ILimitStorage _limitStorage ) BaseFeature(_lockStorage, IVersionManager(address(this)), NAME) public { registry = _registry; // Add initial storages if(address(_lockStorage) != address(0)) { addStorage(address(_lockStorage)); } if(address(_guardianStorage) != address(0)) { addStorage(address(_guardianStorage)); } if(address(_transferStorage) != address(0)) { addStorage(address(_transferStorage)); } if(address(_limitStorage) != address(0)) { addStorage(address(_limitStorage)); } } /* ***************** onlyOwner ************************* */ /** * @inheritdoc IFeature */ function recoverToken(address _token) external override onlyOwner { uint total = ERC20(_token).balanceOf(address(this)); _token.call(abi.encodeWithSelector(ERC20(_token).transfer.selector, msg.sender, total)); } /** * @notice Lets the owner change the minimum allowed version * @param _minVersion the minimum allowed version */ function setMinVersion(uint256 _minVersion) external onlyOwner { require(_minVersion > 0 && _minVersion <= lastVersion, "VM: invalid _minVersion"); minVersion = _minVersion; } /** * @notice Lets the owner add a new version, i.e. a new bundle of features. * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! * WARNING: if a feature was added to a version and later on removed from a subsequent version, * the feature may no longer be used in any future version without first being redeployed. * Otherwise, the feature could be initialized more than once. * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! * @param _features the list of features included in the new version * @param _featuresToInit the subset of features that need to be initialized for a wallet */ function addVersion(address[] calldata _features, address[] calldata _featuresToInit) external onlyOwner { uint256 newVersion = ++lastVersion; for(uint256 i = 0; i < _features.length; i++) { isFeatureInVersion[_features[i]][newVersion] = true; // Store static call information to optimise its use by wallets bytes4[] memory sigs = IFeature(_features[i]).getStaticCallSignatures(); for(uint256 j = 0; j < sigs.length; j++) { staticCallSignatures[newVersion].push(sigs[j]); staticCallExecutors[newVersion][sigs[j]] = _features[i]; } } // Sanity check for(uint256 i = 0; i < _featuresToInit.length; i++) { require(isFeatureInVersion[_featuresToInit[i]][newVersion], "VM: invalid _featuresToInit"); } featuresToInit[newVersion] = _featuresToInit; emit VersionAdded(newVersion, _features); } /** * @notice Lets the owner add a storage contract * @param _storage the storage contract to add */ function addStorage(address _storage) public onlyOwner { require(!isStorage[_storage], "VM: storage already added"); isStorage[_storage] = true; } /* ***************** View Methods ************************* */ /** * @inheritdoc IVersionManager */ function isFeatureAuthorised(address _wallet, address _feature) external view override returns (bool) { // Note that the VersionManager is the only feature that isn't stored in isFeatureInVersion return _isFeatureAuthorisedForWallet(_wallet, _feature) || _feature == address(this); } /** * @inheritdoc IFeature */ function getRequiredSignatures(address /* _wallet */, bytes calldata _data) external view override returns (uint256, OwnerSignature) { bytes4 methodId = Utils.functionPrefix(_data); // This require ensures that the RelayerManager cannot be used to call a featureOnly VersionManager method // that calls a Storage or the BaseWallet for backward-compatibility reason require(methodId == UPGRADE_WALLET_PREFIX || methodId == ADD_MODULE_PREFIX, "VM: unknown method"); return (1, OwnerSignature.Required); } /** * @notice This method delegates the static call to a target feature */ fallback() external { uint256 version = walletVersions[msg.sender]; address feature = staticCallExecutors[version][msg.sig]; require(feature != address(0), "VM: static call not supported for wallet version"); // solhint-disable-next-line no-inline-assembly assembly { calldatacopy(0, 0, calldatasize()) let result := staticcall(gas(), feature, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 {revert(0, returndatasize())} default {return (0, returndatasize())} } } /* ***************** Wallet Upgrade ************************* */ /** * @inheritdoc IFeature */ function init(address _wallet) public override(IModule, BaseFeature) {} /** * @inheritdoc IVersionManager */ function upgradeWallet(address _wallet, uint256 _toVersion) external override onlyWhenUnlocked(_wallet) { require( // Upgrade triggered by the RelayerManager (from version v>=1 to version v'>v) _isFeatureAuthorisedForWallet(_wallet, msg.sender) || // Upgrade triggered by WalletFactory or UpgraderToVersionManager (from version v=0 to version v'>0) IWallet(_wallet).authorised(msg.sender) || // Upgrade triggered directly by the owner (from version v>=1 to version v'>v) isOwner(_wallet, msg.sender), "VM: sender may not upgrade wallet" ); uint256 fromVersion = walletVersions[_wallet]; uint256 minVersion_ = minVersion; uint256 toVersion; if(_toVersion < minVersion_ && fromVersion == 0 && IWallet(_wallet).modules() == 2) { // When the caller is the WalletFactory, we automatically change toVersion to minVersion if needed. // Note that when fromVersion == 0, the caller could be the WalletFactory or the UpgraderToVersionManager. // The WalletFactory will be the only possible caller when the wallet has only 2 authorised modules // (that number would be >= 3 for a call from the UpgraderToVersionManager) toVersion = minVersion_; } else { toVersion = _toVersion; } require(toVersion >= minVersion_ && toVersion <= lastVersion, "VM: invalid _toVersion"); require(fromVersion < toVersion, "VM: already on new version"); walletVersions[_wallet] = toVersion; // Setup static call redirection bytes4[] storage sigs = staticCallSignatures[toVersion]; for(uint256 i = 0; i < sigs.length; i++) { bytes4 sig = sigs[i]; if(IWallet(_wallet).enabled(sig) != address(this)) { IWallet(_wallet).enableStaticCall(address(this), sig); } } // Init features address[] storage featuresToInitInToVersion = featuresToInit[toVersion]; for(uint256 i = 0; i < featuresToInitInToVersion.length; i++) { address feature = featuresToInitInToVersion[i]; // We only initialize a feature that was not already initialized in the previous version if(fromVersion == 0 || !isFeatureInVersion[feature][fromVersion]) { IFeature(feature).init(_wallet); } } emit WalletUpgraded(_wallet, toVersion); } /** * @inheritdoc IModule */ function addModule(address _wallet, address _module) external override onlyWalletOwnerOrFeature(_wallet) onlyWhenUnlocked(_wallet) { require(registry.isRegisteredModule(_module), "VM: module is not registered"); IWallet(_wallet).authoriseModule(_module, true); } /* ******* Backward Compatibility with old Storages and BaseWallet *************** */ /** * @inheritdoc IVersionManager */ function checkAuthorisedFeatureAndInvokeWallet( address _wallet, address _to, uint256 _value, bytes memory _data ) external override returns (bytes memory _res) { require(_isFeatureAuthorisedForWallet(_wallet, msg.sender), "VM: sender may not invoke wallet"); bool success; (success, _res) = _wallet.call(abi.encodeWithSignature("invoke(address,uint256,bytes)", _to, _value, _data)); if (success && _res.length > 0) { //_res is empty if _wallet is an "old" BaseWallet that can't return output values (_res) = abi.decode(_res, (bytes)); } else if (_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"); } } /** * @inheritdoc IVersionManager */ function invokeStorage(address _wallet, address _storage, bytes calldata _data) external override { require(_isFeatureAuthorisedForWallet(_wallet, msg.sender), "VM: sender may not invoke storage"); require(verifyData(_wallet, _data), "VM: target of _data != _wallet"); require(isStorage[_storage], "VM: invalid storage invoked"); (bool success,) = _storage.call(_data); require(success, "VM: _storage failed"); } /** * @inheritdoc IVersionManager */ function setOwner(address _wallet, address _newOwner) external override { require(_isFeatureAuthorisedForWallet(_wallet, msg.sender), "VM: sender should be authorized feature"); IWallet(_wallet).setOwner(_newOwner); } /* ***************** Internal Methods ************************* */ function _isFeatureAuthorisedForWallet(address _wallet, address _feature) private view returns (bool) { return isFeatureInVersion[_feature][walletVersions[_wallet]]; } }
solhint-disable-next-line no-inline-assembly
function checkAuthorisedFeatureAndInvokeWallet( address _wallet, address _to, uint256 _value, bytes memory _data ) external override returns (bytes memory _res) { require(_isFeatureAuthorisedForWallet(_wallet, msg.sender), "VM: sender may not invoke wallet"); bool success; (success, _res) = _wallet.call(abi.encodeWithSignature("invoke(address,uint256,bytes)", _to, _value, _data)); (_res) = abi.decode(_res, (bytes)); assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } revert("VM: wallet invoke reverted"); }
7,419,947
[ 1, 18281, 11317, 17, 8394, 17, 4285, 17, 1369, 1158, 17, 10047, 17, 28050, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 866, 3594, 5918, 4595, 1876, 10969, 16936, 12, 203, 203, 3639, 1758, 389, 19177, 16, 7010, 203, 3639, 1758, 389, 869, 16, 7010, 203, 3639, 2254, 5034, 389, 1132, 16, 7010, 203, 3639, 1731, 3778, 389, 892, 203, 203, 565, 262, 7010, 203, 3639, 3903, 7010, 203, 3639, 3849, 203, 203, 3639, 1135, 261, 3890, 3778, 389, 455, 13, 7010, 203, 565, 288, 203, 203, 3639, 2583, 24899, 291, 4595, 3594, 5918, 1290, 16936, 24899, 19177, 16, 1234, 18, 15330, 3631, 315, 7397, 30, 5793, 2026, 486, 4356, 9230, 8863, 203, 203, 3639, 1426, 2216, 31, 203, 203, 3639, 261, 4768, 16, 389, 455, 13, 273, 389, 19177, 18, 1991, 12, 21457, 18, 3015, 1190, 5374, 2932, 14407, 12, 2867, 16, 11890, 5034, 16, 3890, 2225, 16, 389, 869, 16, 389, 1132, 16, 389, 892, 10019, 203, 203, 203, 5411, 261, 67, 455, 13, 273, 24126, 18, 3922, 24899, 455, 16, 261, 3890, 10019, 203, 203, 203, 203, 5411, 19931, 288, 203, 203, 7734, 327, 892, 3530, 12, 20, 16, 374, 16, 327, 13178, 554, 10756, 203, 203, 7734, 15226, 12, 20, 16, 327, 13178, 554, 10756, 203, 203, 5411, 289, 203, 203, 203, 5411, 15226, 2932, 7397, 30, 9230, 4356, 15226, 329, 8863, 203, 203, 3639, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x3B02E45Bf30D687F0E11d3E5f01e19431E91868F/sources/browser/testconsumer2.sol
* Network: Matic Mainnet Oracle: 0xEb91e4751A3ccc3EC931E8276351FBB63c33713C Job ID: 1916c3ad603c4d039f61510225829be3 LINK address: 0x3D6834Ccf0a5844D3466b23B5077D19fB9D9C067 Fee: 0.01 LINK/
constructor() public { setChainlinkToken(0x70d1F773A9f81C852087B77F6Ae6d3032B02D2AB); oracle = 0xaBA1e27E4bd543EE8e6028573f5d87caE7D9C341; jobId = "5096a3603e804e4fae46a4b5b9c98fbd"; }
5,566,925
[ 1, 3906, 30, 490, 2126, 12740, 2758, 28544, 30, 374, 17432, 70, 12416, 73, 24, 5877, 21, 37, 23, 952, 71, 23, 7228, 29, 6938, 41, 28, 5324, 4449, 10593, 42, 9676, 4449, 71, 3707, 27, 3437, 39, 3956, 1599, 30, 5342, 2313, 71, 23, 361, 26, 4630, 71, 24, 72, 4630, 29, 74, 26, 3600, 20481, 2947, 28, 5540, 2196, 23, 22926, 1758, 30, 374, 92, 23, 40, 9470, 5026, 39, 8522, 20, 69, 25, 5193, 24, 40, 5026, 6028, 70, 4366, 38, 3361, 4700, 40, 3657, 74, 38, 29, 40, 29, 39, 7677, 27, 30174, 30, 374, 18, 1611, 22926, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 1071, 288, 203, 6647, 444, 3893, 1232, 1345, 12, 20, 92, 7301, 72, 21, 42, 4700, 23, 37, 29, 74, 11861, 39, 7140, 3462, 11035, 38, 4700, 42, 26, 37, 73, 26, 72, 5082, 1578, 38, 3103, 40, 22, 2090, 1769, 203, 5411, 20865, 273, 374, 6995, 12536, 21, 73, 5324, 41, 24, 16410, 6564, 23, 9383, 28, 73, 26, 3103, 7140, 9036, 74, 25, 72, 11035, 5353, 41, 27, 40, 29, 39, 5026, 21, 31, 203, 5411, 13845, 273, 315, 5995, 26, 69, 5718, 4630, 73, 28, 3028, 73, 24, 507, 73, 8749, 69, 24, 70, 25, 70, 29, 71, 10689, 74, 16410, 14432, 203, 540, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0x3A902Fe0C6558338B20AfA09b77511eDc5437659/sources/Chance.sol
return address(uint160(receiver)).transfer(address(this).balance);
function sendETHDividends(address userAddress, address _from, uint8 matrix, uint8 level) private { (address receiver, bool isExtraDividends) = findEthReceiver(userAddress, _from, matrix, level); if (!address(uint160(receiver)).send(levelPrice[level])) { Token.transfer(receiver,address(this).balance); } if (isExtraDividends) { emit SentExtraEthDividends(_from, receiver, matrix, level); } }
5,266,962
[ 1, 2463, 1758, 12, 11890, 16874, 12, 24454, 13, 2934, 13866, 12, 2867, 12, 2211, 2934, 12296, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1366, 1584, 44, 7244, 350, 5839, 12, 2867, 729, 1887, 16, 1758, 389, 2080, 16, 2254, 28, 3148, 16, 2254, 28, 1801, 13, 3238, 288, 203, 3639, 261, 2867, 5971, 16, 1426, 353, 7800, 7244, 350, 5839, 13, 273, 1104, 41, 451, 12952, 12, 1355, 1887, 16, 389, 2080, 16, 3148, 16, 1801, 1769, 203, 203, 3639, 309, 16051, 2867, 12, 11890, 16874, 12, 24454, 13, 2934, 4661, 12, 2815, 5147, 63, 2815, 22643, 288, 203, 2398, 3155, 18, 13866, 12, 24454, 16, 2867, 12, 2211, 2934, 12296, 1769, 203, 3639, 289, 203, 540, 203, 3639, 309, 261, 291, 7800, 7244, 350, 5839, 13, 288, 203, 5411, 3626, 16695, 7800, 41, 451, 7244, 350, 5839, 24899, 2080, 16, 5971, 16, 3148, 16, 1801, 1769, 203, 3639, 289, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/5/0x780501A5267e3232EC406A20c7d683BCE9b4468b/sources/ManagerFactory.sol
토큰 생성 만들어진 토큰과 토큰 계약 권한은 이 계약에 있음 @TODO: tokenTemplateKey 넣고 필요 금액을 가져와야 함. 매니저 생성 + 오너 EOA + 각종 설정(min use token, burning token) router에 토큰 approve 이더와 토큰 Uniswap pair 생성 유동성 추가 + LP 토큰 받음
function newManager( string calldata tokenName, string calldata tokenSymbol, uint256 mintingAmount, uint256 requireAmount, uint256 burningAmount ) external payable { uint256 value = msg.value; address token = tokenTemplateKey, "1", tokenName, tokenSymbol, 18, mintingAmount ); address managerAddr = _newManager(token, requireAmount, burningAmount); require( IERC20(token).balanceOf(address(this)) == mintingAmount, "not gen" ); IERC20(token).approve(UniswapV2Router, mintingAmount); token, mintingAmount, mintingAmount, value, managerAddr, block.timestamp ); ownerToManager[msg.sender] = managerAddr; emit DeployedManager(managerAddr); }
16,877,658
[ 1, 174, 233, 259, 174, 228, 113, 225, 173, 230, 256, 173, 231, 114, 225, 172, 105, 239, 172, 246, 102, 173, 249, 117, 173, 105, 231, 225, 174, 233, 259, 174, 228, 113, 171, 116, 125, 225, 174, 233, 259, 174, 228, 113, 225, 171, 116, 231, 173, 248, 126, 225, 171, 119, 239, 174, 248, 255, 173, 256, 227, 225, 173, 256, 117, 225, 171, 116, 231, 173, 248, 126, 173, 250, 243, 225, 173, 257, 235, 173, 256, 239, 632, 6241, 30, 1147, 2283, 653, 225, 172, 231, 101, 171, 116, 259, 225, 174, 248, 231, 173, 253, 247, 225, 171, 121, 235, 173, 248, 99, 173, 256, 231, 225, 171, 113, 227, 173, 259, 121, 173, 252, 227, 173, 248, 125, 225, 174, 248, 106, 18, 225, 172, 105, 102, 172, 238, 235, 173, 259, 227, 225, 173, 230, 256, 173, 231, 114, 397, 225, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 394, 1318, 12, 203, 3639, 533, 745, 892, 1147, 461, 16, 203, 3639, 533, 745, 892, 1147, 5335, 16, 203, 3639, 2254, 5034, 312, 474, 310, 6275, 16, 203, 3639, 2254, 5034, 2583, 6275, 16, 203, 3639, 2254, 5034, 18305, 310, 6275, 203, 565, 262, 3903, 8843, 429, 288, 203, 3639, 2254, 5034, 460, 273, 1234, 18, 1132, 31, 203, 3639, 1758, 1147, 273, 203, 7734, 1147, 2283, 653, 16, 203, 7734, 315, 21, 3113, 203, 7734, 1147, 461, 16, 203, 7734, 1147, 5335, 16, 203, 7734, 6549, 16, 203, 7734, 312, 474, 310, 6275, 203, 5411, 11272, 203, 203, 3639, 1758, 3301, 3178, 273, 389, 2704, 1318, 12, 2316, 16, 2583, 6275, 16, 18305, 310, 6275, 1769, 203, 3639, 2583, 12, 203, 5411, 467, 654, 39, 3462, 12, 2316, 2934, 12296, 951, 12, 2867, 12, 2211, 3719, 422, 312, 474, 310, 6275, 16, 203, 5411, 315, 902, 3157, 6, 203, 3639, 11272, 203, 203, 3639, 467, 654, 39, 3462, 12, 2316, 2934, 12908, 537, 12, 984, 291, 91, 438, 58, 22, 8259, 16, 312, 474, 310, 6275, 1769, 203, 5411, 1147, 16, 203, 5411, 312, 474, 310, 6275, 16, 203, 5411, 312, 474, 310, 6275, 16, 203, 5411, 460, 16, 203, 5411, 3301, 3178, 16, 203, 5411, 1203, 18, 5508, 203, 3639, 11272, 203, 203, 3639, 3410, 774, 1318, 63, 3576, 18, 15330, 65, 273, 3301, 3178, 31, 203, 3639, 3626, 7406, 329, 1318, 12, 4181, 3178, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; import "../interfaces/IManager.sol"; import "../interfaces/ILiquidityPool.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import {IERC20Upgradeable as IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import {SafeERC20Upgradeable as SafeERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import {EnumerableSetUpgradeable as EnumerableSet} from "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol"; import {SafeMathUpgradeable as SafeMath} from "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import {AccessControlUpgradeable as AccessControl} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "../interfaces/events/Destinations.sol"; import "../interfaces/events/CycleRolloverEvent.sol"; import "../interfaces/events/IEventSender.sol"; //solhint-disable not-rely-on-time //solhint-disable var-name-mixedcase contract Manager is IManager, Initializable, AccessControl, IEventSender { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.Bytes32Set; bytes32 public immutable ADMIN_ROLE = keccak256("ADMIN_ROLE"); bytes32 public immutable ROLLOVER_ROLE = keccak256("ROLLOVER_ROLE"); bytes32 public immutable MID_CYCLE_ROLE = keccak256("MID_CYCLE_ROLE"); bytes32 public immutable START_ROLLOVER_ROLE = keccak256("START_ROLLOVER_ROLE"); uint256 public currentCycle; // Start timestamp of current cycle uint256 public currentCycleIndex; // Uint representing current cycle uint256 public cycleDuration; // Cycle duration in seconds bool public rolloverStarted; // Bytes32 controller id => controller address mapping(bytes32 => address) public registeredControllers; // Cycle index => ipfs rewards hash mapping(uint256 => string) public override cycleRewardsHashes; EnumerableSet.AddressSet private pools; EnumerableSet.Bytes32Set private controllerIds; // Reentrancy Guard bool private _entered; bool public _eventSend; Destinations public destinations; uint256 public nextCycleStartTime; bool private isLogicContract; modifier onlyAdmin() { require(hasRole(ADMIN_ROLE, _msgSender()), "NOT_ADMIN_ROLE"); _; } modifier onlyRollover() { require(hasRole(ROLLOVER_ROLE, _msgSender()), "NOT_ROLLOVER_ROLE"); _; } modifier onlyMidCycle() { require(hasRole(MID_CYCLE_ROLE, _msgSender()), "NOT_MID_CYCLE_ROLE"); _; } modifier nonReentrant() { require(!_entered, "ReentrancyGuard: reentrant call"); _entered = true; _; _entered = false; } modifier onEventSend() { if (_eventSend) { _; } } modifier onlyStartRollover() { require(hasRole(START_ROLLOVER_ROLE, _msgSender()), "NOT_START_ROLLOVER_ROLE"); _; } constructor() public { isLogicContract = true; } function initialize(uint256 _cycleDuration, uint256 _nextCycleStartTime) public initializer { __Context_init_unchained(); __AccessControl_init_unchained(); cycleDuration = _cycleDuration; _setupRole(DEFAULT_ADMIN_ROLE, _msgSender()); _setupRole(ADMIN_ROLE, _msgSender()); _setupRole(ROLLOVER_ROLE, _msgSender()); _setupRole(MID_CYCLE_ROLE, _msgSender()); _setupRole(START_ROLLOVER_ROLE, _msgSender()); setNextCycleStartTime(_nextCycleStartTime); } function registerController(bytes32 id, address controller) external override onlyAdmin { registeredControllers[id] = controller; require(controllerIds.add(id), "ADD_FAIL"); emit ControllerRegistered(id, controller); } function unRegisterController(bytes32 id) external override onlyAdmin { emit ControllerUnregistered(id, registeredControllers[id]); delete registeredControllers[id]; require(controllerIds.remove(id), "REMOVE_FAIL"); } function registerPool(address pool) external override onlyAdmin { require(pools.add(pool), "ADD_FAIL"); emit PoolRegistered(pool); } function unRegisterPool(address pool) external override onlyAdmin { require(pools.remove(pool), "REMOVE_FAIL"); emit PoolUnregistered(pool); } function setCycleDuration(uint256 duration) external override onlyAdmin { require(duration > 60, "CYCLE_TOO_SHORT"); cycleDuration = duration; emit CycleDurationSet(duration); } function setNextCycleStartTime(uint256 _nextCycleStartTime) public override onlyAdmin { // We are aware of the possibility of timestamp manipulation. It does not pose any // risk based on the design of our system require(_nextCycleStartTime > block.timestamp, "MUST_BE_FUTURE"); nextCycleStartTime = _nextCycleStartTime; emit NextCycleStartSet(_nextCycleStartTime); } function getPools() external view override returns (address[] memory) { uint256 poolsLength = pools.length(); address[] memory returnData = new address[](poolsLength); for (uint256 i = 0; i < poolsLength; i++) { returnData[i] = pools.at(i); } return returnData; } function getControllers() external view override returns (bytes32[] memory) { uint256 controllerIdsLength = controllerIds.length(); bytes32[] memory returnData = new bytes32[](controllerIdsLength); for (uint256 i = 0; i < controllerIdsLength; i++) { returnData[i] = controllerIds.at(i); } return returnData; } function completeRollover(string calldata rewardsIpfsHash) external override onlyRollover { // Can't be hit via test cases, going to leave in anyways in case we ever change code require(nextCycleStartTime > 0, "SET_BEFORE_ROLLOVER"); // We are aware of the possibility of timestamp manipulation. It does not pose any // risk based on the design of our system require(block.timestamp > nextCycleStartTime, "PREMATURE_EXECUTION"); _completeRollover(rewardsIpfsHash); } /// @notice Used for mid-cycle adjustments function executeMaintenance(MaintenanceExecution calldata params) external override onlyMidCycle nonReentrant { for (uint256 x = 0; x < params.cycleSteps.length; x++) { _executeControllerCommand(params.cycleSteps[x]); } } function executeRollover(RolloverExecution calldata params) external override onlyRollover nonReentrant { // We are aware of the possibility of timestamp manipulation. It does not pose any // risk based on the design of our system require(block.timestamp > nextCycleStartTime, "PREMATURE_EXECUTION"); // Transfer deployable liquidity out of the pools and into the manager for (uint256 i = 0; i < params.poolData.length; i++) { require(pools.contains(params.poolData[i].pool), "INVALID_POOL"); ILiquidityPool pool = ILiquidityPool(params.poolData[i].pool); IERC20 underlyingToken = pool.underlyer(); underlyingToken.safeTransferFrom( address(pool), address(this), params.poolData[i].amount ); emit LiquidityMovedToManager(params.poolData[i].pool, params.poolData[i].amount); } // Deploy or withdraw liquidity for (uint256 x = 0; x < params.cycleSteps.length; x++) { _executeControllerCommand(params.cycleSteps[x]); } // Transfer recovered liquidity back into the pools; leave no funds in the manager for (uint256 y = 0; y < params.poolsForWithdraw.length; y++) { require(pools.contains(params.poolsForWithdraw[y]), "INVALID_POOL"); ILiquidityPool pool = ILiquidityPool(params.poolsForWithdraw[y]); IERC20 underlyingToken = pool.underlyer(); uint256 managerBalance = underlyingToken.balanceOf(address(this)); // transfer funds back to the pool if there are funds if (managerBalance > 0) { underlyingToken.safeTransfer(address(pool), managerBalance); } emit LiquidityMovedToPool(params.poolsForWithdraw[y], managerBalance); } if (params.complete) { _completeRollover(params.rewardsIpfsHash); } } function sweep(address[] calldata poolAddresses) external override onlyRollover { uint256 length = poolAddresses.length; uint256[] memory amounts = new uint256[](length); for (uint256 i = 0; i < length; i++) { address currentPoolAddress = poolAddresses[i]; require(pools.contains(currentPoolAddress), "INVALID_ADDRESS"); IERC20 underlyer = IERC20(ILiquidityPool(currentPoolAddress).underlyer()); uint256 amount = underlyer.balanceOf(address(this)); amounts[i] = amount; if (amount > 0) { underlyer.safeTransfer(currentPoolAddress, amount); } } emit ManagerSwept(poolAddresses, amounts); } function _executeControllerCommand(ControllerTransferData calldata transfer) private { require(!isLogicContract, "FORBIDDEN_CALL"); address controllerAddress = registeredControllers[transfer.controllerId]; require(controllerAddress != address(0), "INVALID_CONTROLLER"); controllerAddress.functionDelegateCall(transfer.data, "CYCLE_STEP_EXECUTE_FAILED"); emit DeploymentStepExecuted(transfer.controllerId, controllerAddress, transfer.data); } function startCycleRollover() external override onlyStartRollover { // We are aware of the possibility of timestamp manipulation. It does not pose any // risk based on the design of our system require(block.timestamp > nextCycleStartTime, "PREMATURE_EXECUTION"); rolloverStarted = true; bytes32 eventSig = "Cycle Rollover Start"; encodeAndSendData(eventSig); emit CycleRolloverStarted(block.timestamp); } function _completeRollover(string calldata rewardsIpfsHash) private { currentCycle = nextCycleStartTime; nextCycleStartTime = nextCycleStartTime.add(cycleDuration); cycleRewardsHashes[currentCycleIndex] = rewardsIpfsHash; currentCycleIndex = currentCycleIndex.add(1); rolloverStarted = false; bytes32 eventSig = "Cycle Complete"; encodeAndSendData(eventSig); emit CycleRolloverComplete(block.timestamp); } function getCurrentCycle() external view override returns (uint256) { return currentCycle; } function getCycleDuration() external view override returns (uint256) { return cycleDuration; } function getCurrentCycleIndex() external view override returns (uint256) { return currentCycleIndex; } function getRolloverStatus() external view override returns (bool) { return rolloverStarted; } function setDestinations(address _fxStateSender, address _destinationOnL2) external override onlyAdmin { require(_fxStateSender != address(0), "INVALID_ADDRESS"); require(_destinationOnL2 != address(0), "INVALID_ADDRESS"); destinations.fxStateSender = IFxStateSender(_fxStateSender); destinations.destinationOnL2 = _destinationOnL2; emit DestinationsSet(_fxStateSender, _destinationOnL2); } function setEventSend(bool _eventSendSet) external override onlyAdmin { require(destinations.destinationOnL2 != address(0), "DESTINATIONS_NOT_SET"); _eventSend = _eventSendSet; emit EventSendSet(_eventSendSet); } function setupRole(bytes32 role) external override onlyAdmin { _setupRole(role, _msgSender()); } function encodeAndSendData(bytes32 _eventSig) private onEventSend { require(address(destinations.fxStateSender) != address(0), "ADDRESS_NOT_SET"); require(destinations.destinationOnL2 != address(0), "ADDRESS_NOT_SET"); bytes memory data = abi.encode(CycleRolloverEvent({ eventSig: _eventSig, cycleIndex: currentCycleIndex, timestamp: currentCycle })); destinations.fxStateSender.sendMessageToChild(destinations.destinationOnL2, data); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; pragma experimental ABIEncoderV2; /** * @title Controls the transition and execution of liquidity deployment cycles. * Accepts instructions that can move assets from the Pools to the Exchanges * and back. Can also move assets to the treasury when appropriate. */ interface IManager { // bytes can take on the form of deploying or recovering liquidity struct ControllerTransferData { bytes32 controllerId; // controller to target bytes data; // data the controller will pass } struct PoolTransferData { address pool; // pool to target uint256 amount; // amount to transfer } struct MaintenanceExecution { ControllerTransferData[] cycleSteps; } struct RolloverExecution { PoolTransferData[] poolData; ControllerTransferData[] cycleSteps; address[] poolsForWithdraw; //Pools to target for manager -> pool transfer bool complete; //Whether to mark the rollover complete string rewardsIpfsHash; } event ControllerRegistered(bytes32 id, address controller); event ControllerUnregistered(bytes32 id, address controller); event PoolRegistered(address pool); event PoolUnregistered(address pool); event CycleDurationSet(uint256 duration); event LiquidityMovedToManager(address pool, uint256 amount); event DeploymentStepExecuted(bytes32 controller, address adapaterAddress, bytes data); event LiquidityMovedToPool(address pool, uint256 amount); event CycleRolloverStarted(uint256 timestamp); event CycleRolloverComplete(uint256 timestamp); event NextCycleStartSet(uint256 nextCycleStartTime); event ManagerSwept(address[] addresses, uint256[] amounts); /// @notice Registers controller /// @param id Bytes32 id of controller /// @param controller Address of controller function registerController(bytes32 id, address controller) external; /// @notice Registers pool /// @param pool Address of pool function registerPool(address pool) external; /// @notice Unregisters controller /// @param id Bytes32 controller id function unRegisterController(bytes32 id) external; /// @notice Unregisters pool /// @param pool Address of pool function unRegisterPool(address pool) external; ///@notice Gets addresses of all pools registered ///@return Memory array of pool addresses function getPools() external view returns (address[] memory); ///@notice Gets ids of all controllers registered ///@return Memory array of Bytes32 controller ids function getControllers() external view returns (bytes32[] memory); ///@notice Allows for owner to set cycle duration ///@param duration Block durtation of cycle function setCycleDuration(uint256 duration) external; ///@notice Starts cycle rollover ///@dev Sets rolloverStarted state boolean to true function startCycleRollover() external; ///@notice Allows for controller commands to be executed midcycle ///@param params Contains data for controllers and params function executeMaintenance(MaintenanceExecution calldata params) external; ///@notice Allows for withdrawals and deposits for pools along with liq deployment ///@param params Contains various data for executing against pools and controllers function executeRollover(RolloverExecution calldata params) external; ///@notice Completes cycle rollover, publishes rewards hash to ipfs ///@param rewardsIpfsHash rewards hash uploaded to ipfs function completeRollover(string calldata rewardsIpfsHash) external; ///@notice Gets reward hash by cycle index ///@param index Cycle index to retrieve rewards hash ///@return String memory hash function cycleRewardsHashes(uint256 index) external view returns (string memory); ///@notice Gets current starting block ///@return uint256 with block number function getCurrentCycle() external view returns (uint256); ///@notice Gets current cycle index ///@return uint256 current cycle number function getCurrentCycleIndex() external view returns (uint256); ///@notice Gets current cycle duration ///@return uint256 in block of cycle duration function getCycleDuration() external view returns (uint256); ///@notice Gets cycle rollover status, true for rolling false for not ///@return Bool representing whether cycle is rolling over or not function getRolloverStatus() external view returns (bool); /// @notice Sets next cycle start time manually /// @param nextCycleStartTime uint256 that represents start of next cycle function setNextCycleStartTime(uint256 nextCycleStartTime) external; /// @notice Sweeps amanager contract for any leftover funds /// @param addresses array of addresses of pools to sweep funds into function sweep(address[] calldata addresses) external; /// @notice Setup a role using internal function _setupRole /// @param role keccak256 of the role keccak256("MY_ROLE"); function setupRole(bytes32 role) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.11; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import "../interfaces/IManager.sol"; /// @title Interface for Pool /// @notice Allows users to deposit ERC-20 tokens to be deployed to market makers. /// @notice Mints 1:1 tAsset on deposit, represeting an IOU for the undelrying token that is freely transferable. /// @notice Holders of tAsset earn rewards based on duration their tokens were deployed and the demand for that asset. /// @notice Holders of tAsset can redeem for underlying asset after issuing requestWithdrawal and waiting for the next cycle. interface ILiquidityPool { struct WithdrawalInfo { uint256 minCycle; uint256 amount; } event WithdrawalRequested(address requestor, uint256 amount); event DepositsPaused(); event DepositsUnpaused(); /// @notice Transfers amount of underlying token from user to this pool and mints fToken to the msg.sender. /// @notice Depositor must have previously granted transfer approval to the pool via underlying token contract. /// @notice Liquidity deposited is deployed on the next cycle - unless a withdrawal request is submitted, in which case the liquidity will be withheld. function deposit(uint256 amount) external; /// @notice Transfers amount of underlying token from user to this pool and mints fToken to the account. /// @notice Depositor must have previously granted transfer approval to the pool via underlying token contract. /// @notice Liquidity deposited is deployed on the next cycle - unless a withdrawal request is submitted, in which case the liquidity will be withheld. function depositFor(address account, uint256 amount) external; /// @notice Requests that the manager prepare funds for withdrawal next cycle /// @notice Invoking this function when sender already has a currently pending request will overwrite that requested amount and reset the cycle timer /// @param amount Amount of fTokens requested to be redeemed function requestWithdrawal(uint256 amount) external; function approveManager(uint256 amount) external; /// @notice Sender must first invoke requestWithdrawal in a previous cycle /// @notice This function will burn the fAsset and transfers underlying asset back to sender /// @notice Will execute a partial withdrawal if either available liquidity or previously requested amount is insufficient /// @param amount Amount of fTokens to redeem, value can be in excess of available tokens, operation will be reduced to maximum permissible function withdraw(uint256 amount) external; /// @return Reference to the underlying ERC-20 contract function underlyer() external view returns (ERC20Upgradeable); /// @return Amount of liquidity that should not be deployed for market making (this liquidity will be used for completing requested withdrawals) function withheldLiquidity() external view returns (uint256); /// @notice Get withdraw requests for an account /// @param account User account to check /// @return minCycle Cycle - block number - that must be active before withdraw is allowed, amount Token amount requested function requestedWithdrawals(address account) external view returns (uint256, uint256); /// @notice Pause deposits on the pool. Withdraws still allowed function pause() external; /// @notice Unpause deposits on the pool. function unpause() external; // @notice Pause deposits only on the pool. function pauseDeposit() external; // @notice Unpause deposits only on the pool. function unpauseDeposit() external; } // 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 // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // 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 EnumerableSetUpgradeable { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.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/EnumerableSetUpgradeable.sol"; import "../utils/AddressUpgradeable.sol"; import "../utils/ContextUpgradeable.sol"; import "../proxy/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, 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 { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using AddressUpgradeable for address; struct RoleData { EnumerableSetUpgradeable.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()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; import "../../fxPortal/IFxStateSender.sol"; /// @notice Configuration entity for sending events to Governance layer struct Destinations { IFxStateSender fxStateSender; address destinationOnL2; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; /// @notice Event sent to Governance layer when a cycle rollover is complete struct CycleRolloverEvent { bytes32 eventSig; uint256 cycleIndex; uint256 timestamp; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; pragma experimental ABIEncoderV2; import "./Destinations.sol"; interface IEventSender { event DestinationsSet(address fxStateSender, address destinationOnL2); event EventSendSet(bool eventSendSet); /// @notice Configure the Polygon state sender root and destination for messages sent /// @param fxStateSender Address of Polygon State Sender Root contract /// @param destinationOnL2 Destination address of events sent. Should be our Event Proxy function setDestinations(address fxStateSender, address destinationOnL2) external; /// @notice Enables or disables the sending of events function setEventSend(bool eventSendSet) external; } // 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 pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface IFxStateSender { function sendMessageToChild(address _receiver, bytes calldata _data) external; }
@notice Transfers amount of underlying token from user to this pool and mints fToken to the msg.sender. @notice Depositor must have previously granted transfer approval to the pool via underlying token contract. @notice Liquidity deposited is deployed on the next cycle - unless a withdrawal request is submitted, in which case the liquidity will be withheld. @notice Transfers amount of underlying token from user to this pool and mints fToken to the account. @notice Depositor must have previously granted transfer approval to the pool via underlying token contract. @notice Liquidity deposited is deployed on the next cycle - unless a withdrawal request is submitted, in which case the liquidity will be withheld. @notice Requests that the manager prepare funds for withdrawal next cycle @notice Invoking this function when sender already has a currently pending request will overwrite that requested amount and reset the cycle timer @param amount Amount of fTokens requested to be redeemed @notice Sender must first invoke requestWithdrawal in a previous cycle @notice This function will burn the fAsset and transfers underlying asset back to sender @notice Will execute a partial withdrawal if either available liquidity or previously requested amount is insufficient @param amount Amount of fTokens to redeem, value can be in excess of available tokens, operation will be reduced to maximum permissible @return Reference to the underlying ERC-20 contract @return Amount of liquidity that should not be deployed for market making (this liquidity will be used for completing requested withdrawals) @notice Get withdraw requests for an account @param account User account to check @return minCycle Cycle - block number - that must be active before withdraw is allowed, amount Token amount requested @notice Pause deposits on the pool. Withdraws still allowed @notice Unpause deposits on the pool. @notice Pause deposits only on the pool. @notice Unpause deposits only on the pool. SPDX-License-Identifier: MIT* @dev Collection of functions related to the address type/
library Address { function deposit(uint256 amount) external; function depositFor(address account, uint256 amount) external; function requestWithdrawal(uint256 amount) external; function approveManager(uint256 amount) external; function withdraw(uint256 amount) external; function underlyer() external view returns (ERC20Upgradeable); function withheldLiquidity() external view returns (uint256); function requestedWithdrawals(address account) external view returns (uint256, uint256); function pause() external; function unpause() external; function pauseDeposit() external; function unpauseDeposit() external; } pragma solidity >=0.6.2 <0.8.0; function isContract(address account) internal view returns (bool) { uint256 size; return size > 0; } assembly { size := extcodesize(account) } function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); require(success, "Address: unable to send value, recipient may have reverted"); } (bool success, ) = recipient.call{ value: amount }(""); function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); return _verifyCallResult(success, returndata, errorMessage); } (bool success, bytes memory returndata) = target.call{ value: value }(data); function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } } else { function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } revert(errorMessage); } } } } else { }
1,261,996
[ 1, 1429, 18881, 3844, 434, 6808, 1147, 628, 729, 358, 333, 2845, 471, 312, 28142, 284, 1345, 358, 326, 1234, 18, 15330, 18, 225, 4019, 538, 1811, 1297, 1240, 7243, 17578, 7412, 23556, 358, 326, 2845, 3970, 6808, 1147, 6835, 18, 225, 511, 18988, 24237, 443, 1724, 329, 353, 19357, 603, 326, 1024, 8589, 300, 3308, 279, 598, 9446, 287, 590, 353, 9638, 16, 316, 1492, 648, 326, 4501, 372, 24237, 903, 506, 598, 76, 488, 18, 225, 2604, 18881, 3844, 434, 6808, 1147, 628, 729, 358, 333, 2845, 471, 312, 28142, 284, 1345, 358, 326, 2236, 18, 225, 4019, 538, 1811, 1297, 1240, 7243, 17578, 7412, 23556, 358, 326, 2845, 3970, 6808, 1147, 6835, 18, 225, 511, 18988, 24237, 443, 1724, 329, 353, 19357, 603, 326, 1024, 8589, 300, 3308, 279, 598, 9446, 287, 590, 353, 9638, 16, 316, 1492, 648, 326, 4501, 372, 24237, 903, 506, 598, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 12083, 5267, 288, 203, 565, 445, 443, 1724, 12, 11890, 5034, 3844, 13, 3903, 31, 203, 203, 565, 445, 443, 1724, 1290, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 3903, 31, 203, 203, 565, 445, 590, 1190, 9446, 287, 12, 11890, 5034, 3844, 13, 3903, 31, 203, 203, 565, 445, 6617, 537, 1318, 12, 11890, 5034, 3844, 13, 3903, 31, 203, 203, 565, 445, 598, 9446, 12, 11890, 5034, 3844, 13, 3903, 31, 203, 203, 565, 445, 3613, 715, 264, 1435, 3903, 1476, 1135, 261, 654, 39, 3462, 10784, 429, 1769, 203, 203, 565, 445, 598, 76, 488, 48, 18988, 24237, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 3764, 1190, 9446, 1031, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 16, 2254, 5034, 1769, 203, 203, 565, 445, 11722, 1435, 3903, 31, 203, 203, 565, 445, 640, 19476, 1435, 3903, 31, 203, 203, 565, 445, 11722, 758, 1724, 1435, 3903, 31, 203, 203, 565, 445, 640, 19476, 758, 1724, 1435, 3903, 31, 203, 97, 203, 203, 203, 683, 9454, 18035, 560, 1545, 20, 18, 26, 18, 22, 411, 20, 18, 28, 18, 20, 31, 203, 203, 565, 445, 353, 8924, 12, 2867, 2236, 13, 2713, 1476, 1135, 261, 6430, 13, 288, 203, 203, 3639, 2254, 5034, 963, 31, 203, 3639, 327, 963, 405, 374, 31, 203, 565, 289, 203, 203, 3639, 19931, 288, 963, 519, 1110, 7000, 554, 12, 4631, 13, 289, 203, 565, 445, 1366, 620, 12, 2867, 8843, 429, 8027, 16, 2254, 5034, 3844, 2 ]
pragma solidity 0.5.17; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0) && _to != address(this)); // 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 ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0) && _to != address(this)); uint256 _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // require (_value <= _allowance); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = _allowance.sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } interface tokenRecipient { function receiveApproval(address _from, uint256 _value, bytes calldata _extraData) external; } contract SOIL is StandardToken, Ownable { string public constant name = "SOIL.ESTATE"; string public constant symbol = "SOIL"; uint public constant decimals = 18; // there is no problem in using * here instead of .mul() uint256 public constant initialSupply = 100000 * (10 ** uint256(decimals)); // Constructors constructor () public { totalSupply = initialSupply; balances[msg.sender] = initialSupply; // Send all tokens to owner emit Transfer(address(0), msg.sender, initialSupply); } function approveAndCall(address _spender, uint256 _value, bytes calldata _extraData) external returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, _extraData); return true; } } function transferAnyERC20Token(address _tokenAddress, address _to, uint _amount) public onlyOwner { ERC20(_tokenAddress).transfer(_to, _amount); } }
there is no problem in using * here instead of .mul() Constructors
contract SOIL is StandardToken, Ownable { string public constant name = "SOIL.ESTATE"; string public constant symbol = "SOIL"; uint public constant decimals = 18; uint256 public constant initialSupply = 100000 * (10 ** uint256(decimals)); constructor () public { totalSupply = initialSupply; emit Transfer(address(0), msg.sender, initialSupply); } function approveAndCall(address _spender, uint256 _value, bytes calldata _extraData) external returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, _extraData); return true; } } function approveAndCall(address _spender, uint256 _value, bytes calldata _extraData) external returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, _extraData); return true; } } function transferAnyERC20Token(address _tokenAddress, address _to, uint _amount) public onlyOwner { ERC20(_tokenAddress).transfer(_to, _amount); } }
1,200,209
[ 1, 18664, 353, 1158, 6199, 316, 1450, 225, 2674, 3560, 434, 263, 16411, 1435, 14291, 1383, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 7460, 2627, 353, 8263, 1345, 16, 14223, 6914, 288, 203, 203, 565, 533, 1071, 5381, 508, 273, 315, 3584, 2627, 18, 41, 7998, 14432, 203, 565, 533, 1071, 5381, 3273, 273, 315, 3584, 2627, 14432, 203, 565, 2254, 1071, 5381, 15105, 273, 6549, 31, 203, 565, 2254, 5034, 1071, 5381, 2172, 3088, 1283, 273, 25259, 380, 261, 2163, 2826, 2254, 5034, 12, 31734, 10019, 203, 203, 565, 3885, 1832, 1071, 288, 203, 3639, 2078, 3088, 1283, 273, 2172, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 1234, 18, 15330, 16, 2172, 3088, 1283, 1769, 203, 565, 289, 203, 377, 203, 565, 445, 6617, 537, 1876, 1477, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 16, 1731, 745, 892, 389, 7763, 751, 13, 203, 3639, 3903, 203, 3639, 1135, 261, 6430, 2216, 13, 7010, 565, 288, 203, 3639, 1147, 18241, 17571, 264, 273, 1147, 18241, 24899, 87, 1302, 264, 1769, 203, 3639, 309, 261, 12908, 537, 24899, 87, 1302, 264, 16, 389, 1132, 3719, 288, 203, 5411, 17571, 264, 18, 18149, 23461, 12, 3576, 18, 15330, 16, 389, 1132, 16, 389, 7763, 751, 1769, 203, 5411, 327, 638, 31, 203, 3639, 289, 203, 565, 289, 203, 377, 203, 565, 445, 6617, 537, 1876, 1477, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 16, 1731, 745, 892, 389, 7763, 751, 13, 203, 3639, 3903, 203, 3639, 1135, 261, 6430, 2216, 13, 7010, 565, 288, 203, 3639, 1147, 18241, 17571, 264, 273, 1147, 18241, 24899, 87, 2 ]
pragma solidity 0.5.13; import "./interfaces/IERC721Full.sol"; import "./utils/SafeMath.sol"; /// @title Augur Markets interface /// @notice Gets the winner of each market from Augur interface IMarket { function getWinningPayoutNumerator(uint256 _outcome) external view returns (uint256); } /// @title Dai contract interface /// @notice Various cash functions interface Cash { function approve(address _spender, uint256 _amount) external returns (bool); function balanceOf(address _ownesr) external view returns (uint256); function faucet(uint256 _amount) external; function transfer(address _to, uint256 _amount) external returns (bool); function transferFrom(address _from, address _to, uint256 _amount) external returns (bool); } /// @title Augur OICash interface /// @notice adding or removing open interest to secure the Augur Oracle interface OICash { function deposit(uint256 _amount) external returns (bool); function withdraw(uint256 _amount) external returns (bool); } //TODO: replace completesets with OICash //TODO: update design pattens to take into account the recent changes //TODO: change front end to only approve the same amount that is being sent //TODO: add test where someone calls exit and they are not the current owner //TODO: add tests where current owner calls newRental twice // ^ will also need to figure out how to pass this number in the correct format because decimal // ^ does not seem to work for more than 100 dai, it needs big number /// @title Harber /// @author Andrew Stanger contract Harber { using SafeMath for uint256; /// NUMBER OF TOKENS /// @dev also equals number of markets on augur uint256 constant public numberOfTokens = 20; /// CONTRACT VARIABLES /// ERC721: IERC721Full public team; /// Augur contracts: IMarket[numberOfTokens] public market; OICash public augur; Cash public cash; /// UINTS, ADDRESSES, BOOLS /// @dev my whiskey fund, for my 1% cut address private andrewsAddress; /// @dev the addresses of the various Augur binary markets. One market for each token. Initiated in the constructor and does not change. address[numberOfTokens] public marketAddresses; /// @dev in attodai (so $100 = 100000000000000000000) uint256[numberOfTokens] public price; /// @dev an easy way to track the above across all tokens. It should always increment at the same time as the above increments. uint256 public totalCollected; /// @dev used to determine the rent due. Rent is due for the period (now - timeLastCollected), at which point timeLastCollected is set to now. uint256[numberOfTokens] public timeLastCollected; /// @dev when a token was bought. used only for front end 'owned since' section. Rent collection only needs timeLastCollected. uint256[numberOfTokens] public timeAcquired; /// @dev tracks the position of the current owner in the ownerTracker mapping uint256[numberOfTokens] public currentOwnerIndex; /// WINNING OUTCOME VARIABLES /// @dev start with invalid winning outcome uint256 public winningOutcome = 42069; //// @dev so the function to manually set the winner can only be called long after /// @dev ...it should have resolved via Augur. Must be public so others can verify it is accurate. uint256 public marketExpectedResolutionTime; /// MARKET RESOLUTION VARIABLES /// @dev step1: bool public marketsResolved = false; // must be false for step1, true for step2 bool public marketsResolvedWithoutErrors = false; // set in step 1. If true, normal payout. If false, return all funds /// @dev step 2: bool public step2Complete = false; // must be false for step2, true for complete /// @dev step 3: bool public step3Complete = false; // must be false for step2, true for complete /// @dev complete: uint256 public daiAvailableToDistribute; /// STRUCTS struct purchase { address owner; uint256 price; } /// MAPPINGS /// @dev keeps track of all previous owners of a token, including the price, so that if the current owner's deposit runs out, /// @dev ...ownership can be reverted to a previous owner with the previous price. Index 0 is NOT used, this tells the contract to foreclose. /// @dev this does NOT keep a reliable list of all owners, if it reverts to a previous owner then the next owner will overwrite the owner that was in that slot. /// @dev the variable currentOwnerIndex is used to track the location of the current owner. mapping (uint256 => mapping (uint256 => purchase) ) public ownerTracker; /// @dev how many seconds each user has held each token for, for determining winnings mapping (uint256 => mapping (address => uint256) ) public timeHeld; /// @dev sums all the timeHelds for each token. Not required, but saves on gas when paying out. Should always increment at the same time as timeHeld mapping (uint256 => uint256) public totalTimeHeld; /// @dev keeps track of all the deposits for each token, for each owner. Unused deposits are not returned automatically when there is a new buyer. /// @dev they can be withdrawn manually however. Unused deposits are returned automatically upon resolution of the market mapping (uint256 => mapping (address => uint256) ) public deposits; /// @dev keeps track of all the rent paid by each user. So that it can be returned in case of an invalid market outcome. Only required in this instance. mapping (address => uint256) public collectedPerUser; ////////////// CONSTRUCTOR ////////////// constructor(address _andrewsAddress, address _addressOfToken, address _addressOfCashContract, address[numberOfTokens] memory _addressesOfMarkets, address _addressOfOICashContract, address _addressOfMainAugurContract, uint _marketExpectedResolutionTime) public { marketExpectedResolutionTime = _marketExpectedResolutionTime; andrewsAddress = _andrewsAddress; marketAddresses = _addressesOfMarkets; // this is to make the market addresses public so users can check the actual augur markets for themselves // external contract variables: team = IERC721Full(_addressOfToken); cash = Cash(_addressOfCashContract); augur = OICash(_addressOfOICashContract); // initialise arrays for (uint i = 0; i < numberOfTokens; i++) { currentOwnerIndex[i]=0; market[i] = IMarket(_addressesOfMarkets[i]); } // approve Augur contract to transfer this contract's dai cash.approve(_addressOfMainAugurContract,(2**256)-1); } event LogNewRental(address indexed newOwner, uint256 indexed newPrice, uint256 indexed tokenId); event LogPriceChange(uint256 indexed newPrice, uint256 indexed tokenId); event LogForeclosure(address indexed prevOwner, uint256 indexed tokenId); event LogRentCollection(uint256 indexed rentCollected, uint256 indexed tokenId); event LogReturnToPreviousOwner(uint256 indexed tokenId, address indexed previousOwner); event LogDepositWithdrawal(uint256 indexed daiWithdrawn, uint256 indexed tokenId, address indexed returnedTo); event LogDepositIncreased(uint256 indexed daiDeposited, uint256 indexed tokenId, address indexed sentBy); event LogExit(uint256 indexed tokenId); event LogStep1Complete(bool indexed didAugurMarketsResolve, uint256 indexed winningOutcome, bool indexed didAugurMarketsResolveCorrectly); event LogStep2Complete(uint256 indexed daiAvailableToDistribute); event LogWinningsPaid(address indexed paidTo, uint256 indexed amountPaid); event LogRentReturned(address indexed returnedTo, uint256 indexed amountReturned); event LogAndrewPaid(uint256 indexed additionsToWhiskeyFund); ////////////// MODIFIERS ////////////// /// @notice prevents functions from being interacted with after the end of the competition /// @dev should be on all public/external 'ordinary course of business' functions modifier notResolved() { require(marketsResolved == false); _; } /// @notice checks the team exists modifier tokenExists(uint256 _tokenId) { require(_tokenId >= 0 && _tokenId < numberOfTokens, "This token does not exist"); _; } /// @notice what it says on the tin modifier amountNotZero(uint256 _dai) { require(_dai > 0, "Amount must be above zero"); _; } ////////////// VIEW FUNCTIONS ////////////// /// @dev used in testing only function getOwnerTrackerPrice(uint256 _tokenId, uint256 _index) public view returns (uint256) { return (ownerTracker[_tokenId][_index].price); } /// @dev used in testing only function getOwnerTrackerAddress(uint256 _tokenId, uint256 _index) public view returns (address) { return (ownerTracker[_tokenId][_index].owner); } /// @dev called in collectRent function, and various other view functions function rentOwed(uint256 _tokenId) public view returns (uint256 augurFundsDue) { return price[_tokenId].mul(now.sub(timeLastCollected[_tokenId])).div(1 days); } /// @dev for front end only /// @return how much the current owner has deposited function liveDepositAbleToWithdraw(uint256 _tokenId) public view returns (uint256) { uint256 _rentOwed = rentOwed(_tokenId); address _currentOwner = team.ownerOf(_tokenId); if(_rentOwed >= deposits[_tokenId][_currentOwner]) { return 0; } else { return deposits[_tokenId][_currentOwner].sub(_rentOwed); } } /// @dev for front end only /// @return how much the current user has deposited (note: user not owner) function userDepositAbleToWithdraw(uint256 _tokenId) public view returns (uint256) { uint256 _rentOwed = rentOwed(_tokenId); address _currentOwner = team.ownerOf(_tokenId); if(_currentOwner == msg.sender) { if(_rentOwed >= deposits[_tokenId][msg.sender]) { return 0; } else { return deposits[_tokenId][msg.sender].sub(_rentOwed); } } else { return deposits[_tokenId][msg.sender]; } } /// @dev for front end only /// @return estimated rental expiry time function rentalExpiryTime(uint256 _tokenId) public view returns (uint256) { uint256 pps; pps = price[_tokenId].div(1 days); if (pps == 0) { return now; //if price is so low that pps = 0 just return current time as a fallback } else { return now + liveDepositAbleToWithdraw(_tokenId).div(pps); } } ////////////// AUGUR FUNCTIONS ////////////// // * internal * /// @notice send the Dai to Augur function _augurDeposit(uint256 _rentOwed) internal { augur.deposit(_rentOwed); } // * internal * /// @notice receive the Dai back from Augur function _augurWithdraw() internal { augur.withdraw(totalCollected); } // * internal * /// @notice THIS FUNCTION HAS NOT BEEN TESTED ON AUGUR YET /// @notice checks if all X (x = number of tokens = number of teams) markets have resolved to either yes, no, or invalid /// @return true if yes, false if no function _haveAllAugurMarketsResolved() internal view returns(bool) { uint256 _resolvedOutcomesCount = 0; for (uint i = 0; i < numberOfTokens; i++) { // binary market has three outcomes: 0 (invalid), 1 (yes), 2 (no) if (market[i].getWinningPayoutNumerator(0) > 0 || market[i].getWinningPayoutNumerator(1) > 0 || market[i].getWinningPayoutNumerator(2) > 0 ) { _resolvedOutcomesCount = _resolvedOutcomesCount.add(1); } } // returns true if all resolved, false otherwise return (_resolvedOutcomesCount == numberOfTokens); } // * internal * /// @notice THIS FUNCTION HAS NOT BEEN TESTED ON AUGUR YET /// @notice checks if all markets have resolved without conflicts or errors /// @return true if yes, false if no /// @dev this function will also set the winningOutcome variable function _haveAllAugurMarketsResolvedWithoutErrors() internal returns(bool) { uint256 _winningOutcomesCount = 0; uint256 _invalidOutcomesCount = 0; for (uint i = 0; i < numberOfTokens; i++) { if (market[i].getWinningPayoutNumerator(0) > 0) { _invalidOutcomesCount = _invalidOutcomesCount.add(1); } if (market[i].getWinningPayoutNumerator(1) > 0) { winningOutcome = i; // <- the winning outcome (a global variable) is set here _winningOutcomesCount = _winningOutcomesCount.add(1); } } return (_winningOutcomesCount == 1 && _invalidOutcomesCount == 0); } ////////////// DAI CONTRACT FUNCTIONS ////////////// // * internal * /// @notice common function for all outgoing DAI transfers function _sendCash(address _to, uint256 _amount) internal { require(cash.transfer(_to,_amount)); } // * internal * /// @notice common function for all incoming DAI transfers function _receiveCash(address _from, uint256 _amount) internal { require(cash.transferFrom(_from, address(this), _amount)); } // * internal * /// @return DAI balance of the contract /// @dev this is used to know how much exists to payout to winners function _getContractsCashBalance() internal view returns (uint256) { return cash.balanceOf(address(this)); } ////////////// MARKET RESOLUTION FUNCTIONS ////////////// /// @notice the first of three functions which must be called, one after the other, to conclude the competition /// @notice winnings can be paid out (or funds returned) only when these two steps are completed /// @notice this function checks whether the Augur markets have resolved, and if yes, whether they resolved correct or not /// @dev they are split into two sections due to the presence of step1BemergencyExit and step1CcircuitBreaker /// @dev can be called by anyone /// @dev can be called multiple times, but only once after markets have indeed resolved /// @dev the two arguments passed are for testing only function step1checkMarketsResolved() external { require(marketsResolved == false, "Step1 can only be completed once"); // first check if all X markets have all resolved one way or the other if (_haveAllAugurMarketsResolved()) { // do a final rent collection before the contract is locked down collectRentAllTokens(); // lock everything down marketsResolved = true; // now check if they all resolved without errors. It is set to false upon contract initialisation // this function also sets winningOutcome if there is one if (_haveAllAugurMarketsResolvedWithoutErrors()) { marketsResolvedWithoutErrors = true; } emit LogStep1Complete(true, winningOutcome, marketsResolvedWithoutErrors); } } /// @notice emergency function in case the augur markets never resolve for whatever reason /// @notice returns all funds to all users /// @notice can only be called 6 months after augur markets should have ended function step1BemergencyExit() external { require(marketsResolved == false, "Step1 can only be completed once"); require(now > (marketExpectedResolutionTime + 15778800), "Must wait 6 months for Augur Oracle"); collectRentAllTokens(); marketsResolved = true; emit LogStep1Complete(false, winningOutcome, false); } /// @notice Same as above, except that only I can call it, and I can call it whenever /// @notice to be clear, this only allows me to return all funds. I can not set a winner. function step1CcircuitBreaker() external { require(marketsResolved == false, "Step1 can only be completed once"); require(msg.sender == andrewsAddress, "Only owner can call this"); collectRentAllTokens(); marketsResolved = true; emit LogStep1Complete(false, winningOutcome, false); } /// @notice the second of the three functions which must be called, one after the other, to conclude the competition /// @dev gets funds back from Augur, gets the available funds for distribution /// @dev can be called by anyone, but only once function step2withdrawFromAugur() external { require(marketsResolved == true, "Must wait for market resolution"); require(step2Complete == false, "Step2 should only be run once"); step2Complete = true; uint256 _balanceBefore = _getContractsCashBalance(); _augurWithdraw(); uint256 _balanceAfter = _getContractsCashBalance(); // daiAvailableToDistribute therefore does not include unused deposits daiAvailableToDistribute = _balanceAfter.sub(_balanceBefore); emit LogStep2Complete(daiAvailableToDistribute); } /// @notice the final of the three functions which must be called, one after the other, to conclude the competition /// @notice pays me my 1% if markets resolved correctly. If not I don't deserve shit /// @dev this was originally included within step3 but it was modifed so that ineraction with Dai contract happened at the end function step3payAndrew() external { require(step2Complete == true, "Must wait for market resolution"); require(step3Complete == false, "Step3 should only be run once"); step3Complete = true; if (marketsResolvedWithoutErrors) { uint256 _andrewsWellEarntMonies = daiAvailableToDistribute.div(100); daiAvailableToDistribute = daiAvailableToDistribute.sub(_andrewsWellEarntMonies); _sendCash(andrewsAddress,_andrewsWellEarntMonies); emit LogAndrewPaid(_andrewsWellEarntMonies); } } /// @notice the final function of the competition resolution process. Pays out winnings, or returns funds, as necessary /// @dev users pull dai into their account. Replaces previous push vesion which required looping over unbounded mapping. function complete() external { require(step3Complete == true, "Step3 must be completed first"); if (marketsResolvedWithoutErrors) { _payoutWinnings(); } else { _returnRent(); } } // * internal * /// @notice pays winnings to the winners /// @dev must be internal and only called by complete function _payoutWinnings() internal { uint256 _winnersTimeHeld = timeHeld[winningOutcome][msg.sender]; if (_winnersTimeHeld > 0) { timeHeld[winningOutcome][msg.sender] = 0; // otherwise they can keep paying themselves over and over uint256 _numerator = daiAvailableToDistribute.mul(_winnersTimeHeld); uint256 _winningsToTransfer = _numerator.div(totalTimeHeld[winningOutcome]); _sendCash(msg.sender, _winningsToTransfer); emit LogWinningsPaid(msg.sender, _winningsToTransfer); } } // * internal * /// @notice returns all funds to users in case of invalid outcome /// @dev must be internal and only called by complete function _returnRent() internal { uint256 _rentCollected = collectedPerUser[msg.sender]; if (_rentCollected > 0) { collectedPerUser[msg.sender] = 0; // otherwise they can keep paying themselves over and over uint256 _numerator = daiAvailableToDistribute.mul(_rentCollected); uint256 _rentToToReturn = _numerator.div(totalCollected); _sendCash(msg.sender, _rentToToReturn); emit LogRentReturned(msg.sender, _rentToToReturn); } } /// @notice withdraw full deposit after markets have resolved /// @dev the other withdraw deposit functions are locked when markets have resolved so must use this one /// @dev ... which can only be called if markets have resolved. This function is also different in that it does /// @dev ... not attempt to collect rent or transfer ownership to a previous owner function withdrawDepositAfterResolution() external { require(marketsResolved == true, "step1 must be completed first"); for (uint i = 0; i < numberOfTokens; i++) { uint256 _depositToReturn = deposits[i][msg.sender]; if (_depositToReturn > 0) { deposits[i][msg.sender] = 0; _sendCash(msg.sender, _depositToReturn); emit LogDepositWithdrawal(_depositToReturn, i, msg.sender); } } } ////////////// ORDINARY COURSE OF BUSINESS FUNCTIONS ////////////// /// @notice collects rent for all tokens /// @dev makes it easy for me to call whenever I want to keep people paying their rent, thus cannot be internal /// @dev cannot be external because it is called within the step1 functions, therefore public function collectRentAllTokens() public notResolved() { for (uint i = 0; i < numberOfTokens; i++) { _collectRent(i); } } /// @notice collects rent for a specific token /// @dev also calculates and updates how long the current user has held the token for /// @dev called frequently internally, so cant be external. /// @dev is not a problem if called externally, but making internal to save gas function _collectRent(uint256 _tokenId) internal notResolved() { //only collect rent if the token is owned (ie, if owned by the contract this implies unowned) if (team.ownerOf(_tokenId) != address(this)) { uint256 _rentOwed = rentOwed(_tokenId); address _currentOwner = team.ownerOf(_tokenId); uint256 _timeOfThisCollection; if (_rentOwed >= deposits[_tokenId][_currentOwner]) { // run out of deposit. Calculate time it was actually paid for, then revert to previous owner _timeOfThisCollection = timeLastCollected[_tokenId].add(((now.sub(timeLastCollected[_tokenId])).mul(deposits[_tokenId][_currentOwner]).div(_rentOwed))); _rentOwed = deposits[_tokenId][_currentOwner]; // take what's left _revertToPreviousOwner(_tokenId); } else { // normal collection _timeOfThisCollection = now; } // decrease deposit by rent owed deposits[_tokenId][_currentOwner] = deposits[_tokenId][_currentOwner].sub(_rentOwed); // the 'important bit', where the duration the token has been held by each user is updated // it is essential that timeHeld and totalTimeHeld are incremented together such that the sum of // the first is equal to the second uint256 _timeHeldToIncrement = (_timeOfThisCollection.sub(timeLastCollected[_tokenId])); //just for readability timeHeld[_tokenId][_currentOwner] = timeHeld[_tokenId][_currentOwner].add(_timeHeldToIncrement); totalTimeHeld[_tokenId] = totalTimeHeld[_tokenId].add(_timeHeldToIncrement); // it is also essential that collectedPerUser and totalCollected are all incremented together // such that the sum of the first two (individually) is equal to the third collectedPerUser[_currentOwner] = collectedPerUser[_currentOwner].add(_rentOwed); totalCollected = totalCollected.add(_rentOwed); _augurDeposit(_rentOwed); emit LogRentCollection(_rentOwed, _tokenId); } // timeLastCollected is updated regardless of whether the token is owned, so that the clock starts ticking // ... when the first owner buys it, because this function is run before ownership changes upon calling // ... newRental timeLastCollected[_tokenId] = now; } /// @notice to rent a token function newRental(uint256 _newPrice, uint256 _tokenId, uint256 _deposit) external tokenExists(_tokenId) amountNotZero(_deposit) notResolved() { require(_newPrice > price[_tokenId], "Price must be higher than current price"); _collectRent(_tokenId); // require(1==2, "STFU"); address _currentOwner = team.ownerOf(_tokenId); if (_currentOwner == msg.sender) { // bought by current owner (ie, token ownership does not change, so it is as if the current owner // ... called changePrice and depositDai seperately) _changePrice(_newPrice, _tokenId); _depositDai(_deposit, _tokenId); } else { // bought by different user (the normal situation) // deposits are updated via depositDai function if _currentOwner = msg.sender // therefore deposits only updated inside this else section deposits[_tokenId][msg.sender] = deposits[_tokenId][msg.sender].add(_deposit); // update currentOwnerIndex and ownerTracker currentOwnerIndex[_tokenId] = currentOwnerIndex[_tokenId].add(1); ownerTracker[_tokenId][currentOwnerIndex[_tokenId]].price = _newPrice; ownerTracker[_tokenId][currentOwnerIndex[_tokenId]].owner = msg.sender; // update timeAcquired for the front end timeAcquired[_tokenId] = now; _transferTokenTo(_currentOwner, msg.sender, _newPrice, _tokenId); _receiveCash(msg.sender, _deposit); emit LogNewRental(msg.sender, _newPrice, _tokenId); } } /// @notice add new dai deposit to an existing rental /// @dev it is possible a user's deposit could be reduced to zero following _collectRent /// @dev they would then increase their deposit despite no longer owning it /// @dev this is ok, they can withdraw via withdrawDeposit. function depositDai(uint256 _dai, uint256 _tokenId) external amountNotZero(_dai) tokenExists(_tokenId) notResolved() { _collectRent(_tokenId); _depositDai(_dai, _tokenId); } /// @dev depositDai is split into two, because it needs to be called direct from newRental /// @dev ... without collecing rent first (otherwise it would be collected twice, possibly causing logic errors) function _depositDai(uint256 _dai, uint256 _tokenId) internal { deposits[_tokenId][msg.sender] = deposits[_tokenId][msg.sender].add(_dai); _receiveCash(msg.sender, _dai); emit LogDepositIncreased(_dai, _tokenId, msg.sender); } /// @notice increase the price of an existing rental /// @dev can't be external because also called within newRental function changePrice(uint256 _newPrice, uint256 _tokenId) public tokenExists(_tokenId) notResolved() { require(_newPrice > price[_tokenId], "New price must be higher than current price"); require(msg.sender == team.ownerOf(_tokenId), "Not owner"); _collectRent(_tokenId); _changePrice(_newPrice, _tokenId); } /// @dev changePrice is split into two, because it needs to be called direct from newRental /// @dev ... without collecing rent first (otherwise it would be collected twice, possibly causing logic errors) function _changePrice(uint256 _newPrice, uint256 _tokenId) internal { // below is the only instance when price is modifed outside of the _transferTokenTo function price[_tokenId] = _newPrice; ownerTracker[_tokenId][currentOwnerIndex[_tokenId]].price = _newPrice; emit LogPriceChange(price[_tokenId], _tokenId); } /// @notice withdraw deposit /// @dev do not need to be the current owner function withdrawDeposit(uint256 _dai, uint256 _tokenId) external amountNotZero(_dai) tokenExists(_tokenId) notResolved() returns (uint256) { _collectRent(_tokenId); // if statement needed because deposit may have just reduced to zero following _collectRent if (deposits[_tokenId][msg.sender] > 0) { _withdrawDeposit(_dai, _tokenId); emit LogDepositWithdrawal(_dai, _tokenId, msg.sender); } } /// @notice withdraw full deposit /// @dev do not need to be the current owner function exit(uint256 _tokenId) external tokenExists(_tokenId) notResolved() { _collectRent(_tokenId); // if statement needed because deposit may have just reduced to zero following _collectRent modifier if (deposits[_tokenId][msg.sender] > 0) { _withdrawDeposit(deposits[_tokenId][msg.sender], _tokenId); emit LogExit(_tokenId); } } /* internal */ /// @notice actually withdraw the deposit and call _revertToPreviousOwner if necessary function _withdrawDeposit(uint256 _dai, uint256 _tokenId) internal { require(deposits[_tokenId][msg.sender] >= _dai, 'Withdrawing too much'); deposits[_tokenId][msg.sender] = deposits[_tokenId][msg.sender].sub(_dai); address _currentOwner = team.ownerOf(_tokenId); if(_currentOwner == msg.sender && deposits[_tokenId][msg.sender] == 0) { _revertToPreviousOwner(_tokenId); } _sendCash(msg.sender, _dai); } /* internal */ /// @notice if a users deposit runs out, either return to previous owner or foreclose function _revertToPreviousOwner(uint256 _tokenId) internal { bool _reverted = false; bool _toForeclose = false; uint256 _index; address _previousOwner; while (_reverted == false) { assert(currentOwnerIndex[_tokenId] >=0); currentOwnerIndex[_tokenId] = currentOwnerIndex[_tokenId].sub(1); // currentOwnerIndex will now point to previous owner _index = currentOwnerIndex[_tokenId]; // just for readability _previousOwner = ownerTracker[_tokenId][_index].owner; //if no previous owners. price -> zero, foreclose //if previous owner still has a deposit, transfer to them, update the price to what it used to be if (_index == 0) { _toForeclose = true; _reverted = true; } else if (deposits[_tokenId][_previousOwner] > 0) { _reverted = true; } } if (_toForeclose) { _foreclose(_tokenId); } else { address _currentOwner = team.ownerOf(_tokenId); uint256 _oldPrice = ownerTracker[_tokenId][_index].price; _transferTokenTo(_currentOwner, _previousOwner, _oldPrice, _tokenId); emit LogReturnToPreviousOwner(_tokenId, _previousOwner); } } /* internal */ /// @notice return token to the contract and return price to zero function _foreclose(uint256 _tokenId) internal { address _currentOwner = team.ownerOf(_tokenId); // third field is price, ie price goes to zero _transferTokenTo(_currentOwner, address(this), 0, _tokenId); emit LogForeclosure(_currentOwner, _tokenId); } /* internal */ /// @notice transfer ERC 721 between users /// @dev there is no event emitted as this is handled in ERC721.sol function _transferTokenTo(address _currentOwner, address _newOwner, uint256 _newPrice, uint256 _tokenId) internal { require(_currentOwner != address(0) && _newOwner != address(0) , "Cannot send to/from zero address"); team.transferFrom(_currentOwner, _newOwner, _tokenId); price[_tokenId] = _newPrice; } }
@notice the final of the three functions which must be called, one after the other, to conclude the competition @notice pays me my 1% if markets resolved correctly. If not I don't deserve shit @dev this was originally included within step3 but it was modifed so that ineraction with Dai contract happened at the end
function step3payAndrew() external { require(step2Complete == true, "Must wait for market resolution"); require(step3Complete == false, "Step3 should only be run once"); step3Complete = true; if (marketsResolvedWithoutErrors) { uint256 _andrewsWellEarntMonies = daiAvailableToDistribute.div(100); daiAvailableToDistribute = daiAvailableToDistribute.sub(_andrewsWellEarntMonies); _sendCash(andrewsAddress,_andrewsWellEarntMonies); emit LogAndrewPaid(_andrewsWellEarntMonies); } }
15,828,462
[ 1, 5787, 727, 434, 326, 8925, 4186, 1492, 1297, 506, 2566, 16, 1245, 1839, 326, 1308, 16, 358, 356, 1571, 326, 25163, 608, 225, 293, 8271, 1791, 3399, 404, 9, 309, 2267, 2413, 4640, 8783, 18, 971, 486, 467, 2727, 1404, 5620, 537, 699, 305, 225, 333, 1703, 24000, 5849, 3470, 2235, 23, 1496, 518, 1703, 681, 430, 329, 1427, 716, 316, 264, 1128, 598, 463, 10658, 6835, 17497, 622, 326, 679, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2235, 23, 10239, 1876, 16052, 1435, 3903, 288, 203, 3639, 2583, 12, 4119, 22, 6322, 422, 638, 16, 315, 10136, 2529, 364, 13667, 7861, 8863, 203, 3639, 2583, 12, 4119, 23, 6322, 422, 629, 16, 315, 4160, 23, 1410, 1338, 506, 1086, 3647, 8863, 3639, 203, 3639, 2235, 23, 6322, 273, 638, 31, 203, 203, 3639, 309, 261, 3355, 2413, 12793, 8073, 4229, 13, 288, 203, 5411, 2254, 5034, 389, 464, 266, 4749, 59, 1165, 41, 297, 496, 11415, 606, 273, 5248, 77, 5268, 774, 1669, 887, 18, 2892, 12, 6625, 1769, 203, 5411, 5248, 77, 5268, 774, 1669, 887, 273, 5248, 77, 5268, 774, 1669, 887, 18, 1717, 24899, 464, 266, 4749, 59, 1165, 41, 297, 496, 11415, 606, 1769, 203, 5411, 389, 4661, 39, 961, 12, 464, 266, 4749, 1887, 16, 67, 464, 266, 4749, 59, 1165, 41, 297, 496, 11415, 606, 1769, 203, 5411, 3626, 1827, 1876, 16052, 16507, 350, 24899, 464, 266, 4749, 59, 1165, 41, 297, 496, 11415, 606, 1769, 203, 3639, 289, 1377, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import './interface/IMasterChef.sol'; import './interface/IDDX.sol'; import './interface/ITokenLock.sol'; import './uniswapv2/interfaces/IWHT.sol'; import './uniswapv2/libraries/TransferHelper.sol'; import './uniswapv2/interfaces/IUniswapV2Factory.sol'; import './toB/IPreVault.sol'; contract DDXPool is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; address public immutable WToken; //lock half address public tokenLock; using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet private _multLP; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. uint256 multLpRewardDebt; //multLp Reward debt. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. DDXs to distribute per block. uint256 lastRewardBlock; // Last block number that DDXs distribution occurs. uint256 accDDXPerShare; // Accumulated DDXs per share, times 1e12. uint256 accMultLpPerShare; //Accumulated multLp per share uint256 totalAmount; // Total amount of current pool deposit. address investPool;// token to invest Pool } // The DDX Token! IDDX public ddx; uint public ddxPerBlockInitLength; mapping(uint256=>uint256) public ddxPerBlockInit; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Corresponding to the pid of the multLP pool mapping(uint256 => uint256) public poolCorrespond; // pid corresponding address mapping(address => uint256) public LpOfPid; // Control mining bool public paused = false; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when DDX mining starts. uint256 public startBlock; // multLP MasterChef address public multLpChef; // multLP Token address public multLpToken; // How many blocks are halved uint256 public halvingPeriod = 1576800; //=365*720*24/4 address public factory; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( IDDX _ddx, uint256 _startBlock, uint256 _halvingPeriod, //1576800, address _WToken, address _factory, address _tokenLock ) public { ddx = _ddx; startBlock = _startBlock; halvingPeriod = _halvingPeriod; WToken = _WToken; factory = _factory; tokenLock= _tokenLock; } function setStartBlock(uint256 _startBlock) public onlyOwner { startBlock = _startBlock; } function setBonusPool(uint256 pid,address bonusAddress) public onlyOwner{ PoolInfo storage pool = poolInfo[pid]; pool.investPool = bonusAddress; } function setHalvedPeroid(uint256 _halvingPeriod) public onlyOwner { halvingPeriod = _halvingPeriod; } // Set the number of ddx produced by each block function setDDXPerBlockInit(uint256 []memory _ddxPerBlockInit) public onlyOwner { massUpdatePools(); ddxPerBlockInitLength = _ddxPerBlockInit.length; for(uint i=0;i<ddxPerBlockInitLength;i++){ ddxPerBlockInit[i] = _ddxPerBlockInit[i]; } } function poolLength() public view returns (uint256) { return poolInfo.length; } function addMultLP(address _addLP) public onlyOwner returns (bool) { require(_addLP != address(0), "LP is the zero address"); IERC20(_addLP).approve(multLpChef, uint256(- 1)); return EnumerableSet.add(_multLP, _addLP); } function isMultLP(address _LP) public view returns (bool) { return EnumerableSet.contains(_multLP, _LP); } function getMultLPLength() public view returns (uint256) { return EnumerableSet.length(_multLP); } function getMultLPAddress(uint256 _pid) public view returns (address){ require(_pid <= getMultLPLength() - 1, "not find this multLP"); return EnumerableSet.at(_multLP, _pid); } function setPause() public onlyOwner { paused = !paused; } function setMultLP(address _multLpToken, address _multLpChef) public onlyOwner { require(_multLpToken != address(0) && _multLpChef != address(0), "is the zero address"); multLpToken = _multLpToken; multLpChef = _multLpChef; } function replaceMultLP(address _multLpToken, address _multLpChef) public onlyOwner { require(_multLpToken != address(0) && _multLpChef != address(0), "is the zero address"); require(paused == true, "No mining suspension"); multLpToken = _multLpToken; multLpChef = _multLpChef; uint256 length = getMultLPLength(); while (length > 0) { address dAddress = EnumerableSet.at(_multLP, 0); uint256 pid = LpOfPid[dAddress]; IMasterChef(multLpChef).emergencyWithdraw(poolCorrespond[pid]); EnumerableSet.remove(_multLP, dAddress); 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, IERC20 _lpToken, bool _withUpdate,address _investPool) public onlyOwner { require(address(_lpToken) != address(0), "_lpToken is the zero address"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken : _lpToken, allocPoint : _allocPoint, lastRewardBlock : lastRewardBlock, accDDXPerShare : 0, accMultLpPerShare : 0, totalAmount : 0, investPool: _investPool })); LpOfPid[address(_lpToken)] = poolLength() - 1; } // Update the given pool's DDX allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // The current pool corresponds to the pid of the multLP pool function setPoolCorr(uint256 _pid, uint256 _sid) public onlyOwner { require(_pid <= poolLength() - 1, "not find this pool"); poolCorrespond[_pid] = _sid; } function phase(uint256 blockNumber) public view returns (uint256) { if (halvingPeriod == 0) { return 0; } if (blockNumber > startBlock) { return (blockNumber.sub(startBlock).sub(1)).div(halvingPeriod); } return 0; } function reward(uint256 blockNumber) public view returns (uint256 ddxPerBlockCal) { uint256 _phase = phase(blockNumber); ddxPerBlockCal = 0; if(_phase < ddxPerBlockInitLength) { ddxPerBlockCal = ddxPerBlockInit[_phase]; } else { ddxPerBlockCal = ddxPerBlockInit[ddxPerBlockInitLength-1]; for(uint i=ddxPerBlockInitLength;i<=_phase;i++) { ddxPerBlockCal = ddxPerBlockCal.mul(99).div(100); } } } function getDDXBlockReward(uint256 _lastRewardBlock) public view returns (uint256) { uint256 blockReward = 0; uint256 n = phase(_lastRewardBlock); uint256 m = phase(block.number); while (n < m) { n++; uint256 r = n.mul(halvingPeriod).add(startBlock); blockReward = blockReward.add((r.sub(_lastRewardBlock)).mul(reward(r))); _lastRewardBlock = r; } blockReward = blockReward.add((block.number.sub(_lastRewardBlock)).mul(reward(block.number))); return blockReward; } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply; if (isMultLP(address(pool.lpToken))) { if (pool.totalAmount == 0) { pool.lastRewardBlock = block.number; return; } lpSupply = pool.totalAmount; } else { // lpSupply = pool.lpToken.balanceOf(address(this)); lpSupply = pool.totalAmount; if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } } uint256 blockReward = getDDXBlockReward(pool.lastRewardBlock); if (blockReward <= 0) { return; } uint256 ddxReward = blockReward.mul(pool.allocPoint).div(totalAllocPoint); bool minRet = ddx.mint(address(this), ddxReward); if (minRet) { pool.accDDXPerShare = pool.accDDXPerShare.add(ddxReward.mul(1e12).div(lpSupply)); } pool.lastRewardBlock = block.number; } // View function to see pending DDXs on frontend. function pending(uint256 _pid, address _user) external view returns (uint256, uint256){ PoolInfo storage pool = poolInfo[_pid]; if (isMultLP(address(pool.lpToken))) { (uint256 ddxAmount, uint256 tokenAmount) = pendingDDXAndToken(_pid, _user); return (ddxAmount, tokenAmount); } else { uint256 ddxAmount = pendingDDX(_pid, _user); return (ddxAmount, 0); } } function pendingDDXAndToken(uint256 _pid, address _user) private view returns (uint256, uint256){ PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accDDXPerShare = pool.accDDXPerShare; uint256 accMultLpPerShare = pool.accMultLpPerShare; if (user.amount > 0) { uint256 TokenPending = IMasterChef(multLpChef).pending(poolCorrespond[_pid], address(this)); accMultLpPerShare = accMultLpPerShare.add(TokenPending.mul(1e12).div(pool.totalAmount)); uint256 userPending = user.amount.mul(accMultLpPerShare).div(1e12).sub(user.multLpRewardDebt); if (block.number > pool.lastRewardBlock) { uint256 blockReward = getDDXBlockReward(pool.lastRewardBlock); uint256 ddxReward = blockReward.mul(pool.allocPoint).div(totalAllocPoint); accDDXPerShare = accDDXPerShare.add(ddxReward.mul(1e12).div(pool.totalAmount)); return (user.amount.mul(accDDXPerShare).div(1e12).sub(user.rewardDebt), userPending); } if (block.number == pool.lastRewardBlock) { return (user.amount.mul(accDDXPerShare).div(1e12).sub(user.rewardDebt), userPending); } } return (0, 0); } function pendingDDX(uint256 _pid, address _user) private view returns (uint256){ PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accDDXPerShare = pool.accDDXPerShare; // uint256 lpSupply = pool.lpToken.balanceOf(address(this)); uint256 lpSupply = pool.totalAmount; if (user.amount > 0) { if (block.number > pool.lastRewardBlock) { uint256 blockReward = getDDXBlockReward(pool.lastRewardBlock); uint256 ddxReward = blockReward.mul(pool.allocPoint).div(totalAllocPoint); accDDXPerShare = accDDXPerShare.add(ddxReward.mul(1e12).div(lpSupply)); return user.amount.mul(accDDXPerShare).div(1e12).sub(user.rewardDebt); } if (block.number == pool.lastRewardBlock) { return user.amount.mul(accDDXPerShare).div(1e12).sub(user.rewardDebt); } } return 0; } // Deposit LP tokens to Pool for DDX allocation. function deposit(uint256 _pid, uint256 _amount,address to) public notPause { PoolInfo storage pool = poolInfo[_pid]; if (isMultLP(address(pool.lpToken))) { depositDDXAndToken(_pid, _amount, to); } else { depositDDX(_pid, _amount, to); } // if(msg.value>0){ // address bpool = bonusPools[_pid]; // uint256 amountNative = msg.value; // if(bpool!=address(0x0)){ // IWHT(WToken).deposit{value: amountNative}(); // assert(IWHT(WToken).transfer(bpool, amountNative)); // uint256 pendingAmount = amountNative.mul(1e10); // pool.lpToken.safeTransfer(to, pendingAmount); // }else{ // IWHT(WToken).deposit{value: amountNative}(); // } // } } function depositDDXAndToken(uint256 _pid, uint256 _amount, address _user) private { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; updatePool(_pid); if (user.amount > 0) { uint256 pendingAmount = user.amount.mul(pool.accDDXPerShare).div(1e12).sub(user.rewardDebt); if (pendingAmount > 0) { safeDDXTransfer(_user, pendingAmount); } uint256 beforeToken = IERC20(multLpToken).balanceOf(address(this)); IMasterChef(multLpChef).deposit(poolCorrespond[_pid], 0); uint256 afterToken = IERC20(multLpToken).balanceOf(address(this)); pool.accMultLpPerShare = pool.accMultLpPerShare.add(afterToken.sub(beforeToken).mul(1e12).div(pool.totalAmount)); uint256 tokenPending = user.amount.mul(pool.accMultLpPerShare).div(1e12).sub(user.multLpRewardDebt); if (tokenPending > 0) { IERC20(multLpToken).safeTransfer(_user, tokenPending); } } if (_amount > 0) { if(pool.investPool==address(0x0)) { pool.lpToken.safeTransferFrom(_user, address(this), _amount); }else{ pool.lpToken.safeTransferFrom(_user, pool.investPool, _amount); IPreVault(pool.investPool).deposit(address(pool.lpToken)); } if (pool.totalAmount == 0) { IMasterChef(multLpChef).deposit(poolCorrespond[_pid], _amount); user.amount = user.amount.add(_amount); pool.totalAmount = pool.totalAmount.add(_amount); } else { uint256 beforeToken = IERC20(multLpToken).balanceOf(address(this)); IMasterChef(multLpChef).deposit(poolCorrespond[_pid], _amount); uint256 afterToken = IERC20(multLpToken).balanceOf(address(this)); pool.accMultLpPerShare = pool.accMultLpPerShare.add(afterToken.sub(beforeToken).mul(1e12).div(pool.totalAmount)); user.amount = user.amount.add(_amount); pool.totalAmount = pool.totalAmount.add(_amount); } } user.rewardDebt = user.amount.mul(pool.accDDXPerShare).div(1e12); user.multLpRewardDebt = user.amount.mul(pool.accMultLpPerShare).div(1e12); emit Deposit(_user, _pid, _amount); } function depositDDX(uint256 _pid, uint256 _amount, address _user) private { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; updatePool(_pid); if (user.amount > 0) { uint256 pendingAmount = user.amount.mul(pool.accDDXPerShare).div(1e12).sub(user.rewardDebt); if (pendingAmount > 0) { safeDDXTransfer(_user, pendingAmount); } } if (_amount > 0) { // pool.lpToken.safeTransferFrom(_user, address(this), _amount); if(pool.investPool==address(0x0)) { pool.lpToken.safeTransferFrom(_user, address(this), _amount); }else{ pool.lpToken.safeTransferFrom(_user, pool.investPool, _amount); IPreVault(pool.investPool).deposit(address(pool.lpToken)); } user.amount = user.amount.add(_amount); pool.totalAmount = pool.totalAmount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accDDXPerShare).div(1e12); emit Deposit(_user, _pid, _amount); } // Withdraw LP tokens from Pool. function withdraw(uint256 _pid, uint256 _amount) public notPause { PoolInfo storage pool = poolInfo[_pid]; if (isMultLP(address(pool.lpToken))) { withdrawDDXAndToken(_pid, _amount, msg.sender); } else { withdrawDDX(_pid, _amount, msg.sender); } } function withdrawDDXAndToken(uint256 _pid, uint256 _amount, address _user) private { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; require(user.amount >= _amount, "withdrawDDXAndToken: not good"); updatePool(_pid); uint256 pendingAmount = user.amount.mul(pool.accDDXPerShare).div(1e12).sub(user.rewardDebt); if (pendingAmount > 0) { safeDDXTransfer(_user, pendingAmount); } if (_amount > 0) { uint256 beforeToken = IERC20(multLpToken).balanceOf(address(this)); IMasterChef(multLpChef).withdraw(poolCorrespond[_pid], _amount); uint256 afterToken = IERC20(multLpToken).balanceOf(address(this)); pool.accMultLpPerShare = pool.accMultLpPerShare.add(afterToken.sub(beforeToken).mul(1e12).div(pool.totalAmount)); uint256 tokenPending = user.amount.mul(pool.accMultLpPerShare).div(1e12).sub(user.multLpRewardDebt); if (tokenPending > 0) { IERC20(multLpToken).safeTransfer(_user, tokenPending); } user.amount = user.amount.sub(_amount); pool.totalAmount = pool.totalAmount.sub(_amount); uint256 lpBal = pool.lpToken.balanceOf(address(this)) ; if(lpBal < _amount && pool.investPool != address(0x0) ) { IPreVault(pool.investPool).withdraw(address(pool.lpToken),_amount.sub(lpBal)); } pool.lpToken.safeTransfer(_user, _amount); } user.rewardDebt = user.amount.mul(pool.accDDXPerShare).div(1e12); user.multLpRewardDebt = user.amount.mul(pool.accMultLpPerShare).div(1e12); emit Withdraw(_user, _pid, _amount); } function withdrawDDX(uint256 _pid, uint256 _amount, address _user) private { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; require(user.amount >= _amount, "withdrawDDX: not good"); updatePool(_pid); uint256 pendingAmount = user.amount.mul(pool.accDDXPerShare).div(1e12).sub(user.rewardDebt); if (pendingAmount > 0) { safeDDXTransfer(_user, pendingAmount); } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.totalAmount = pool.totalAmount.sub(_amount); uint256 lpBal = pool.lpToken.balanceOf(address(this)) ; if(lpBal < _amount && pool.investPool != address(0x0) ) { IPreVault(pool.investPool).withdraw(address(pool.lpToken),_amount.sub(lpBal)); } pool.lpToken.safeTransfer(_user, _amount); } user.rewardDebt = user.amount.mul(pool.accDDXPerShare).div(1e12); emit Withdraw(_user, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public notPause { PoolInfo storage pool = poolInfo[_pid]; if (isMultLP(address(pool.lpToken))) { emergencyWithdrawDDXAndToken(_pid, msg.sender); } else { emergencyWithdrawDDX(_pid, msg.sender); } } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyNative(uint256 amount) public onlyOwner { TransferHelper.safeTransferNative(msg.sender,amount) ; } function emergencyWithdrawDDXAndToken(uint256 _pid, address _user) private { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 amount = user.amount; uint256 beforeToken = IERC20(multLpToken).balanceOf(address(this)); IMasterChef(multLpChef).withdraw(poolCorrespond[_pid], amount); uint256 afterToken = IERC20(multLpToken).balanceOf(address(this)); pool.accMultLpPerShare = pool.accMultLpPerShare.add(afterToken.sub(beforeToken).mul(1e12).div(pool.totalAmount)); user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(_user, amount); pool.totalAmount = pool.totalAmount.sub(amount); emit EmergencyWithdraw(_user, _pid, amount); } function emergencyWithdrawDDX(uint256 _pid, address _user) private { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(_user, amount); pool.totalAmount = pool.totalAmount.sub(amount); emit EmergencyWithdraw(_user, _pid, amount); } // Safe DDX transfer function, just in case if rounding error causes pool to not have enough DDXs. function safeDDXTransfer(address _to, uint256 _amount) internal { uint256 ddxBal = ddx.balanceOf(address(this)); if (_amount > ddxBal) { _amount = ddxBal; } (uint256 upperFee,uint256 upperFeeTotal) = IUniswapV2Factory(factory).getReferAmount(_to,_amount); if(upperFee>0){ ddx.mint(address(factory), upperFee); IUniswapV2Factory(factory).rewardUpper(_to,address(ddx),upperFee,upperFeeTotal); } if (tokenLock != address(0) && ITokenLock(tokenLock).lockRate() > 0) { ITokenLock(tokenLock).getReward(_to); uint256 lock = ITokenLock(tokenLock).calLockAmount(_amount); ITokenLock(tokenLock).lockToken(_to, lock); _amount = _amount.sub(lock); } ddx.transfer(_to, _amount); } modifier notPause() { require(paused == false, "Mining has been suspended"); _; } function setTokenLock(address _address) public onlyOwner { require(_address != address(0), "address is not 0"); tokenLock = _address; TransferHelper.safeApprove(address(ddx), tokenLock, uint256(- 1)); } }
pool.lpToken.safeTransferFrom(_user, address(this), _amount);
function depositDDX(uint256 _pid, uint256 _amount, address _user) private { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; updatePool(_pid); if (user.amount > 0) { uint256 pendingAmount = user.amount.mul(pool.accDDXPerShare).div(1e12).sub(user.rewardDebt); if (pendingAmount > 0) { safeDDXTransfer(_user, pendingAmount); } } if (_amount > 0) { if(pool.investPool==address(0x0)) { pool.lpToken.safeTransferFrom(_user, address(this), _amount); pool.lpToken.safeTransferFrom(_user, pool.investPool, _amount); IPreVault(pool.investPool).deposit(address(pool.lpToken)); } user.amount = user.amount.add(_amount); pool.totalAmount = pool.totalAmount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accDDXPerShare).div(1e12); emit Deposit(_user, _pid, _amount); }
5,371,050
[ 1, 6011, 18, 9953, 1345, 18, 4626, 5912, 1265, 24899, 1355, 16, 1758, 12, 2211, 3631, 389, 8949, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 5698, 60, 12, 11890, 5034, 389, 6610, 16, 2254, 5034, 389, 8949, 16, 1758, 389, 1355, 13, 3238, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 67, 1355, 15533, 203, 3639, 1089, 2864, 24899, 6610, 1769, 203, 3639, 309, 261, 1355, 18, 8949, 405, 374, 13, 288, 203, 5411, 2254, 5034, 4634, 6275, 273, 729, 18, 8949, 18, 16411, 12, 6011, 18, 8981, 5698, 60, 2173, 9535, 2934, 2892, 12, 21, 73, 2138, 2934, 1717, 12, 1355, 18, 266, 2913, 758, 23602, 1769, 203, 5411, 309, 261, 9561, 6275, 405, 374, 13, 288, 203, 7734, 4183, 5698, 60, 5912, 24899, 1355, 16, 4634, 6275, 1769, 203, 5411, 289, 203, 3639, 289, 203, 3639, 309, 261, 67, 8949, 405, 374, 13, 288, 203, 5411, 309, 12, 6011, 18, 5768, 395, 2864, 631, 2867, 12, 20, 92, 20, 3719, 203, 5411, 288, 203, 7734, 2845, 18, 9953, 1345, 18, 4626, 5912, 1265, 24899, 1355, 16, 1758, 12, 2211, 3631, 389, 8949, 1769, 203, 7734, 2845, 18, 9953, 1345, 18, 4626, 5912, 1265, 24899, 1355, 16, 2845, 18, 5768, 395, 2864, 16, 389, 8949, 1769, 203, 7734, 467, 1386, 12003, 12, 6011, 18, 5768, 395, 2864, 2934, 323, 1724, 12, 2867, 12, 6011, 18, 9953, 1345, 10019, 203, 5411, 289, 203, 2398, 203, 5411, 729, 18, 8949, 273, 729, 18, 8949, 18, 1289, 24899, 8949, 1769, 203, 5411, 2845, 18, 4963, 6275, 273, 2845, 18, 4963, 2 ]
/** *Submitted for verification at Etherscan.io on 2022-01-04 */ // SPDX-License-Identifier: MIT // Amended by HashLips /** !Disclaimer! These contracts have been used to create tutorials, and was created for the purpose to teach people how to create smart contracts on the blockchain. please review this code on your own before using any of the following code for production. HashLips will not be liable in any way if for the use of the code. That being said, the code has been tested to the best of the developers' knowledge to work as intended. */ // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/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 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/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/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/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/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/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/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/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. 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 {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: @openzeppelin/contracts/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() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } pragma solidity >=0.7.0 <0.9.0; contract SamuraiTeaClub is ERC721Enumerable, Ownable { using Strings for uint256; string baseURI; string public baseExtension = ".json"; uint256 public cost = 0.055 ether; uint256 public maxSupply = 7999; uint256 public maxMintAmount = 100; bool public paused = true; bool public revealed = false; string public notRevealedUri; constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedUri ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); setNotRevealedURI(_initNotRevealedUri); } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // public function mint(uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(!paused); require(_mintAmount > 0); require(_mintAmount <= maxMintAmount); require(supply + _mintAmount <= maxSupply); if (msg.sender != owner()) { require(msg.value >= cost * _mintAmount); } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if(revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } //only owner function reveal() public onlyOwner() { revealed = true; } function setCost(uint256 _newCost) public onlyOwner() { cost = _newCost; } function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner() { maxMintAmount = _newmaxMintAmount; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function pause(bool _state) public onlyOwner { paused = _state; } function withdraw() public payable onlyOwner { (bool success, ) = payable(msg.sender).call{value: address(this).balance}(""); require(success); } }
* @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); }
6,804,169
[ 1, 49, 28142, 1375, 2316, 548, 68, 471, 29375, 518, 358, 1375, 869, 8338, 9744, 30, 10858, 434, 333, 707, 353, 19169, 477, 11349, 16, 999, 288, 67, 4626, 49, 474, 97, 17334, 3323, 29076, 30, 300, 1375, 2316, 548, 68, 1297, 486, 1005, 18, 300, 1375, 869, 68, 2780, 506, 326, 3634, 1758, 18, 7377, 1282, 279, 288, 5912, 97, 871, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 282, 445, 389, 81, 474, 12, 2867, 358, 16, 2254, 5034, 1147, 548, 13, 2713, 5024, 288, 203, 4202, 2583, 12, 869, 480, 1758, 12, 20, 3631, 315, 654, 39, 27, 5340, 30, 312, 474, 358, 326, 3634, 1758, 8863, 203, 4202, 2583, 12, 5, 67, 1808, 12, 2316, 548, 3631, 315, 654, 39, 27, 5340, 30, 1147, 1818, 312, 474, 329, 8863, 203, 7010, 4202, 389, 5771, 1345, 5912, 12, 2867, 12, 20, 3631, 358, 16, 1147, 548, 1769, 203, 7010, 4202, 389, 70, 26488, 63, 869, 65, 1011, 404, 31, 203, 4202, 389, 995, 414, 63, 2316, 548, 65, 273, 358, 31, 203, 7010, 4202, 3626, 12279, 12, 2867, 12, 20, 3631, 358, 16, 1147, 548, 1769, 203, 282, 289, 203, 7010, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.8.9; //SPDX-License-Identifier: MIT import "hardhat/console.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "./lib/InterestHelper.sol"; /// @title LoaNFT - NFTs as collateral for loans /// @author Manuel Tumiati /// @notice Users can request and obtain loans using their NFTs as collateral /// @dev There are 2 structs for Loan requests and Loans. The active requests and loans are /// stored in arrays and tracked using mappings for gas optimization. /// requestId and loanId are the same and are computed by hashing the sender address, /// the NFT contract address and the tokenId together /// This contract makes use of solidity-interests-helper by Nick Ward /// https://github.com/wolflo/solidity-interest-helper contract LoaNFT is Ownable, Pausable, IERC721Receiver, Interest { // Keeps track of the state when a request become effectively a loan enum LoanStatus { INITIAL, FUNDED, ACTIVE, REPAID, CLOSED } // Definition of a request object struct LoanRequest { address applicant; // person who wants to receive a loan using an NFT as collateral uint256 amount; // requested amount in eth address erc721contract; // address of the ERC721 NFT contract uint256 tokenId; // tokenid of the NFT the user is willing to put as collateral for the loan uint32 loanDuration; // loan duration in number of blocks uint256 yearlyInterestRate; // interest rate on a yearly basis } // Definition of a loan object struct Loan { address applicant; // person who wants to receive a loan using an NFT as collateral address supplier; // person who provide liquidity accepting an NFT as collateral uint256 amount; // requested amount in eth address erc721contract; // address of the ERC721 NFT contract uint256 tokenId; // tokenid of the NFT placed as collateral for the loan uint256 yearlyInterestRate; // interest rate on a yearly basis uint256 deadline; // deadline to repay the loan. Only available when the loan is active uint256 startedAt; // timestamp when to start counting the interests uint256 finalInterests; // interests computed during the repay LoanStatus status; // current state of the loan } // Mapping of all the loan requests LoanRequest[] public loanRequests; // Tracks the index of each loan request inside the mapping mapping(bytes32 => uint256) private loanRequestsTracker; // List of all the active loans Loan[] public loans; // Tracks the index of each loan inside the mapping mapping(bytes32 => uint256) private loansTracker; // Constant used to mark a request or a loan as removed inside the trackers uint256 constant MAX_UINT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; /// @notice Loan Request created event /// @param requestId Id of the request /// @param applicant User who requested the loan /// @param amount Amount of money the user is requesting /// @param loanDuration Max duration of the loan (in seconds) /// @param yearlyInterestRate Yearly interest rate the user is willing to pay for the loan event LoanRequested( bytes32 indexed requestId, address indexed applicant, uint256 amount, uint32 loanDuration, uint256 yearlyInterestRate ); /// @notice Liquidity Provided event /// @param requestId Id of the request /// @param applicant User who requested the loan /// @param supplier User who provided liquidity for the loan /// @param amount Amount of money the user is requesting /// @param loanDuration Max duration of the loan (in seconds) /// @param yearlyInterestRate Yearly interest rate the user is willing to pay for the loan event LiquidityProvided( bytes32 indexed requestId, address indexed applicant, address indexed supplier, uint256 amount, uint32 loanDuration, uint256 yearlyInterestRate ); /// @notice Loan Withdraw event. It's fired whenever the applicant starts the loan /// @param requestId Id of the request /// @param applicant User who requested the loan /// @param supplier User who provided liquidity for the loan event LoanWithdraw( bytes32 indexed requestId, address indexed applicant, address indexed supplier ); /// @notice Loan Repaid event. It's fired whenever the applicant repays the loan /// @param requestId Id of the request /// @param applicant User who requested the loan /// @param supplier User who provided liquidity for the loan event LoanRepaid( bytes32 indexed requestId, address indexed applicant, address indexed supplier ); /// @notice Loan Extinguished with money event. It's fired whenever the supplier calls the redeem functions and the /// loan was repaid by the applicant. In this case the supplier gets money + interests back /// @param requestId Id of the request /// @param applicant User who requested the loan /// @param supplier User who provided liquidity for the loan event LoanExtinguishedWithMoney( bytes32 indexed requestId, address indexed applicant, address indexed supplier ); /// @notice Loan Extinguished with NFT event. It's fired whenever the supplier calls the redeem functions, but the /// loan was not repaid by the applicant. In this case the supplier gets the NFT that was placed as collateral /// @param requestId Id of the request /// @param applicant User who requested the loan /// @param supplier User who provided liquidity for the loan event LoanExtinguishedWithNFT( bytes32 indexed requestId, address indexed applicant, address indexed supplier ); /// @notice Returns a loan request from the mapping /// @param _requestId Id of the request to return function getLoanRequest(bytes32 _requestId) public view returns (LoanRequest memory) { uint256 index = loanRequestsTracker[_requestId]; require(index != 0, "Request does not exist"); return loanRequests[index - 1]; } /// @notice Returns a loan from the mapping /// @param _loanId Id of the loan to return function getLoan(bytes32 _loanId) public view returns (Loan memory) { uint256 index = loansTracker[_loanId]; require(index != 0, "Loan does not exist"); return loans[index - 1]; } /// @notice Public function that returns the list af all loan requests /// @dev it's used by the UI to show the list of requests function getAllLoanRequests() public view returns (LoanRequest[] memory) { return loanRequests; } /// @notice Public function that returns the list af all loans /// @dev it's used by the UI to show the list of loans function getAllLoans() public view returns (Loan[] memory) { return loans; } /// @notice Adds a loan request to the array and keeps track of it in the mapping /// @param _requestId Id of the request to add /// @param _loanRequest Request object to add function _addLoanRequest( bytes32 _requestId, LoanRequest memory _loanRequest ) internal { loanRequests.push(_loanRequest); uint256 index = loanRequests.length; loanRequestsTracker[_requestId] = index; } /// @notice Removes the loan request with the given requestId from the array and updates the tracker /// @param _requestId Id of the request to remove function _removeRequest(bytes32 _requestId) internal { require(loanRequests.length > 0, "There are no requests to remove"); // Index of the element to remove uint256 index = loanRequestsTracker[_requestId] - 1; uint256 lastIndex = loanRequests.length - 1; if (index != lastIndex) { // Last friend inside the array LoanRequest memory last = loanRequests[lastIndex]; // Change the last with the element to remove loanRequests[index] = last; // Compute the request id for the last request bytes32 lastRequestId = _computeRequestId( last.applicant, last.erc721contract, last.tokenId ); // Update the Index loanRequestsTracker[lastRequestId] = index + 1; } // Clear the previous index by setting the maximum integer loanRequestsTracker[_requestId] = MAX_UINT; // Reduce the size of the array by 1 loanRequests.pop(); } /// @notice Adds a loan to the array and keeps track of it in the mapping /// @param _loanId Id of the loan to add /// @param _loan Loan object to add function _addLoan(bytes32 _loanId, Loan memory _loan) internal { loans.push(_loan); uint256 index = loans.length; loansTracker[_loanId] = index; } /// @notice Removes the loan with the given loanId from the array and updates the tracker /// @param _loanId Id of the loan to remove function _removeLoan(bytes32 _loanId) internal { require(loans.length > 0, "There are no loans to remove"); // Index of the element to remove uint256 index = loansTracker[_loanId] - 1; uint256 lastIndex = loans.length - 1; if (index != lastIndex) { // Last friend inside the array Loan memory last = loans[lastIndex]; // Change the last with the element to remove loans[index] = last; // Compute the loan id for the last request bytes32 lastLoanId = _computeRequestId( last.applicant, last.erc721contract, last.tokenId ); // Update the Index loansTracker[lastLoanId] = index + 1; } // Clear the previous index by setting the maximum integer loansTracker[_loanId] = MAX_UINT; // Reduce the size of the array by 1 loans.pop(); } /// @notice Utility function to compute a requestId /// @param sender The address of the user who owns the NFT /// @param erc721contract The address of the NFT contract /// @param tokenId The id of the token the user wants to place as collateral for a loan function _computeRequestId( address sender, address erc721contract, uint256 tokenId ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(sender, erc721contract, tokenId)); } /// @notice Utility function that returns the computed interests for the given loan id /// @param loanId Id of the loan you want to compute the accrued interests function getLoanInterests(bytes32 loanId) public view returns (uint256) { require( loansTracker[loanId] != 0 && loansTracker[loanId] != MAX_UINT, "The loan does not exist" ); Loan memory loan = getLoan(loanId); uint256 effectiveRatePerSecond = yearlyRateToRay( loan.yearlyInterestRate ); uint256 elapsedTime; if (block.timestamp >= loan.deadline) { elapsedTime = loan.deadline - loan.startedAt; } else { elapsedTime = block.timestamp - loan.startedAt; } if (loan.status == LoanStatus.REPAID) { return loan.finalInterests; } else { return accrueInterest( loan.amount, effectiveRatePerSecond, elapsedTime ) - loan.amount; } } /// @notice Allow the user to request a Loan /// @param amount Amount of money the user wants to receive on loan /// @param erc721contract The address of the NFT contract /// @param tokenId The id of the token the user wants to place as collateral for a loan /// @param loanDuration Max duration of the loan (in seconds) /// @param yearlyInterestRate Yearly interest rate the user is willing to pay for the loan function requestLoan( uint256 amount, address erc721contract, uint256 tokenId, uint32 loanDuration, uint256 yearlyInterestRate ) public whenNotPaused { bytes32 requestId = _computeRequestId( msg.sender, erc721contract, tokenId ); require( loanRequestsTracker[requestId] == 0 || loanRequestsTracker[requestId] == MAX_UINT, "A loan request is already active for this request. Remove it first" ); require( loansTracker[requestId] == 0 || loansTracker[requestId] == MAX_UINT, "A loan is already active for this NFT" ); // Instanciate the ERC721 contract for the transfer IERC721 nftContract = IERC721(erc721contract); _addLoanRequest( requestId, LoanRequest({ applicant: msg.sender, erc721contract: erc721contract, amount: amount, tokenId: tokenId, loanDuration: loanDuration, yearlyInterestRate: yearlyInterestRate }) ); // Transfer the NFT from the user to the contract nftContract.safeTransferFrom(msg.sender, address(this), tokenId); emit LoanRequested( requestId, msg.sender, amount, loanDuration, yearlyInterestRate ); } /// @notice Allow another user to provide liquidity for the loan /// @param requestId id of the request you want to provide liquidity for function provideLiquidityForALoan(bytes32 requestId) public payable whenNotPaused { require( loansTracker[requestId] == 0 || loansTracker[requestId] == MAX_UINT, "A loan is already active for this NFT" ); require( loanRequestsTracker[requestId] != 0 && loanRequestsTracker[requestId] != MAX_UINT, "The loan request does not exist" ); LoanRequest memory loanRequest = getLoanRequest(requestId); require( msg.value == loanRequest.amount, "You are providing the wrong amount of money for this loan" ); Loan memory loan = Loan({ applicant: loanRequest.applicant, supplier: msg.sender, erc721contract: loanRequest.erc721contract, amount: loanRequest.amount, tokenId: loanRequest.tokenId, yearlyInterestRate: loanRequest.yearlyInterestRate, deadline: block.timestamp + loanRequest.loanDuration, startedAt: 0, finalInterests: 0, status: LoanStatus.FUNDED }); _addLoan(requestId, loan); _removeRequest(requestId); emit LiquidityProvided( requestId, loan.applicant, msg.sender, loanRequest.amount, loanRequest.loanDuration, loanRequest.yearlyInterestRate ); } /// @notice Allow the originator of the request to withdraw the money he got on loan /// @param loanId id of the loan you want to withdraw function widthrawLoan(bytes32 loanId) public whenNotPaused { require( loansTracker[loanId] != 0 && loansTracker[loanId] != MAX_UINT, "The loan does not exist" ); Loan memory loan = getLoan(loanId); require( loan.applicant == msg.sender, "This loan does not belong to you" ); require( loan.status == LoanStatus.FUNDED, "The loan is in the wrong state" ); loans[loansTracker[loanId] - 1].status = LoanStatus.ACTIVE; loans[loansTracker[loanId] - 1].startedAt = block.timestamp; payable(loan.applicant).transfer(loan.amount); emit LoanWithdraw(loanId, loan.applicant, loan.supplier); } /// @notice Allow the originator of the request to repay the loan /// @param loanId id of the loan you want to repay function repayLoan(bytes32 loanId) public payable whenNotPaused { require( loansTracker[loanId] != 0 && loansTracker[loanId] != MAX_UINT, "The loan does not exist" ); Loan memory loan = getLoan(loanId); require( loan.applicant == msg.sender, "This loan does not belong to you" ); require( loan.status == LoanStatus.ACTIVE, "The loan is not active. Nothing to repay" ); require(block.timestamp < loan.deadline, "Too late"); uint256 interests = getLoanInterests(loanId); require( msg.value >= loan.amount + interests, "You must repay the amount + the interests" ); loans[loansTracker[loanId] - 1].status = LoanStatus.REPAID; loans[loansTracker[loanId] - 1].finalInterests = interests; // Pay back the extra amount that has been sent as tollerance uint256 difference = msg.value - (loan.amount + interests); payable(msg.sender).transfer(difference); // Instanciate the ERC721 contract for the transfer IERC721 nftContract = IERC721(getLoan(loanId).erc721contract); nftContract.safeTransferFrom( address(this), msg.sender, getLoan(loanId).tokenId ); emit LoanRepaid(loanId, loan.applicant, loan.supplier); } /// @notice Allow the liquidity provider for the loan to get the money back if the loan has been repaid or /// get back the collateral NFT if it hasn't /// @param loanId id of the loan you want to redeem function redeemLoanOrNFT(bytes32 loanId) public payable whenNotPaused { require( loansTracker[loanId] != 0 && loansTracker[loanId] != MAX_UINT, "The loan does not exist" ); Loan memory loan = getLoan(loanId); require( loan.supplier == msg.sender, "This loan has not been funded by you" ); require( loan.status == LoanStatus.REPAID || (loan.status == LoanStatus.ACTIVE && block.timestamp > loan.deadline), "Conditions to redeem the loan doesn't match" ); if (loan.status == LoanStatus.REPAID) { _payLoanBack(loanId); } else if ( loan.status == LoanStatus.ACTIVE && block.timestamp >= loan.deadline ) { _sendNFTToTheSupplier(loanId); } _removeLoan(loanId); } /// @notice Utility function that sends money back for a specific loan /// @param loanId id of the loan to pay back function _payLoanBack(bytes32 loanId) internal { Loan memory loan = getLoan(loanId); uint256 amount = loan.amount + loan.finalInterests; loans[loansTracker[loanId] - 1].status = LoanStatus.CLOSED; payable(msg.sender).transfer(amount); emit LoanExtinguishedWithMoney(loanId, loan.applicant, loan.supplier); } /// @notice Utility function that sends the NFT back for a specific loan /// @param loanId id of the loan to pay back function _sendNFTToTheSupplier(bytes32 loanId) internal { Loan memory loan = getLoan(loanId); loans[loansTracker[loanId] - 1].status = LoanStatus.CLOSED; IERC721(loan.erc721contract).safeTransferFrom( address(this), msg.sender, loan.tokenId ); emit LoanExtinguishedWithNFT(loanId, loan.applicant, loan.supplier); } /// @notice Emergency function that pauses the contract preventig the execution /// in case of bugs or attacks function emergencyPause() public onlyOwner { _pause(); } /// @notice Emergency function that resumes the state of the contract function emergencyResume() public onlyOwner { _unpause(); } /// @notice Emergency function that allows the contract owner to withdraw all the money /// in case of bugs or attacks function emengencyWithdraw() public onlyOwner whenPaused { payable(owner()).transfer(address(this).balance); } /// @notice Function needed to let the contract being able to receive ERC721 NFTs /// @dev Mandatory for IERC721Receiver function onERC721Received( address, address, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC721Received.selector; } }
@notice Allow the originator of the request to withdraw the money he got on loan @param loanId id of the loan you want to withdraw
function widthrawLoan(bytes32 loanId) public whenNotPaused { require( loansTracker[loanId] != 0 && loansTracker[loanId] != MAX_UINT, "The loan does not exist" ); Loan memory loan = getLoan(loanId); require( loan.applicant == msg.sender, "This loan does not belong to you" ); require( loan.status == LoanStatus.FUNDED, "The loan is in the wrong state" ); loans[loansTracker[loanId] - 1].status = LoanStatus.ACTIVE; loans[loansTracker[loanId] - 1].startedAt = block.timestamp; payable(loan.applicant).transfer(loan.amount); emit LoanWithdraw(loanId, loan.applicant, loan.supplier); }
14,108,037
[ 1, 7009, 326, 4026, 639, 434, 326, 590, 358, 598, 9446, 326, 15601, 3904, 2363, 603, 28183, 225, 28183, 548, 612, 434, 326, 28183, 1846, 2545, 358, 598, 9446, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1835, 1899, 1504, 304, 12, 3890, 1578, 28183, 548, 13, 1071, 1347, 1248, 28590, 288, 203, 3639, 2583, 12, 203, 5411, 437, 634, 8135, 63, 383, 304, 548, 65, 480, 374, 597, 437, 634, 8135, 63, 383, 304, 548, 65, 480, 4552, 67, 57, 3217, 16, 203, 5411, 315, 1986, 28183, 1552, 486, 1005, 6, 203, 3639, 11272, 203, 203, 3639, 3176, 304, 3778, 28183, 273, 336, 1504, 304, 12, 383, 304, 548, 1769, 203, 203, 3639, 2583, 12, 203, 5411, 28183, 18, 438, 1780, 970, 422, 1234, 18, 15330, 16, 203, 5411, 315, 2503, 28183, 1552, 486, 10957, 358, 1846, 6, 203, 3639, 11272, 203, 3639, 2583, 12, 203, 5411, 28183, 18, 2327, 422, 3176, 304, 1482, 18, 42, 2124, 7660, 16, 203, 5411, 315, 1986, 28183, 353, 316, 326, 7194, 919, 6, 203, 3639, 11272, 203, 203, 3639, 437, 634, 63, 383, 634, 8135, 63, 383, 304, 548, 65, 300, 404, 8009, 2327, 273, 3176, 304, 1482, 18, 13301, 31, 203, 3639, 437, 634, 63, 383, 634, 8135, 63, 383, 304, 548, 65, 300, 404, 8009, 14561, 861, 273, 1203, 18, 5508, 31, 203, 203, 3639, 8843, 429, 12, 383, 304, 18, 438, 1780, 970, 2934, 13866, 12, 383, 304, 18, 8949, 1769, 203, 203, 3639, 3626, 3176, 304, 1190, 9446, 12, 383, 304, 548, 16, 28183, 18, 438, 1780, 970, 16, 28183, 18, 2859, 5742, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "./MOSToken.sol"; // A funding contract that allows purchase of shares contract DAOFunding is ReentrancyGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ address public governance; IERC20 public wantToken; MOSToken public daoToken; uint256 public rate; uint256 public convertCap; uint256 public currentBalance; bool public whitelistEnabled; mapping(address => bool) public isWhitelisted; address[] public whitelist; mapping(address => uint256) public records; // Tracking of shares of funders to avoid going over sharesCap /* ========== CONSTRUCTOR ========== */ constructor( address _wantToken, address _daoToken, uint _rate, uint _convertCap, bool _whitelistEnabled, uint _existingBalance // this is to migrate old data ) { wantToken = IERC20(_wantToken); daoToken = MOSToken(_daoToken); rate = _rate; convertCap = _convertCap; whitelistEnabled = _whitelistEnabled; currentBalance = _existingBalance; governance = msg.sender; } /* ========== MODIFIER ========== */ modifier onlyGovernance() { require(msg.sender == governance, "!gov"); _; } modifier onlyWhitelist() { if (whitelistEnabled) { require(isWhitelisted[msg.sender] == true, "!whitelist"); } _; } /* ========== MUTATIVE FUNCTIONS ========== */ // fund the dao and get dao token function contribute(uint256 _amount) external nonReentrant onlyWhitelist { uint256 w = _amount.mul(rate); require(currentBalance.add(w) <= convertCap, "cap-exceeded"); wantToken.safeTransferFrom(msg.sender, address(this), _amount); daoToken.mint(msg.sender, w); currentBalance = currentBalance.add(w); records[msg.sender] = records[msg.sender].add(_amount); } /* ========== VIEW FUNCTIONS ========== */ function whitelistLength() external view returns (uint256) { return whitelist.length; } function holdings(address _token) public view returns (uint) { return IERC20(_token).balanceOf(address(this)); } /* ========== RESTRICTED FUNCTIONS ========== */ function takeOut( address _token, address _destination, uint _amount ) external onlyGovernance { require(_amount <= holdings(_token), "!insufficient"); SafeERC20.safeTransfer(IERC20(_token), _destination, _amount); } function setGovernance(address _governance) external onlyGovernance { governance = _governance; } function setWantToken(address _want) external onlyGovernance { wantToken = IERC20(_want); } function setDAOToken(address _dao) external onlyGovernance { daoToken = MOSToken(_dao); } function setRate(uint _rate) external onlyGovernance { rate = _rate; } function setConvertCap(uint _convertCap) external onlyGovernance { convertCap = _convertCap; } function setWhitelistEnabled(bool _status) external onlyGovernance { whitelistEnabled = _status; } function addToWhitelist(address _user) external onlyGovernance { require(isWhitelisted[_user] == false, "already in whitelist"); isWhitelisted[_user] = true; whitelist.push(_user); } function removeFromWhitelist(address _user) external onlyGovernance { require(isWhitelisted[_user] == true, "not in whitelist"); isWhitelisted[_user] = false; // find the index uint indexToDelete = 0; bool found = false; for (uint i = 0; i < whitelist.length; i++) { if (whitelist[i] == _user) { indexToDelete = i; found = true; break; } } // remove element require(found == true, "user not found in whitelist"); whitelist[indexToDelete] = whitelist[whitelist.length - 1]; whitelist.pop(); } // use with cautiou // this is to prevent removeFromWhitelist function failed. function forceRemoveUserInWhitelist(address _user) external onlyGovernance { require(isWhitelisted[_user] == true, "not in whitelist"); isWhitelisted[_user] = false; } // use with cautiou // this is to prevent removeFromWhitelist function failed. function forceRemoveIndexFromWhitelist(uint _indexToDelete) external onlyGovernance { // remove element whitelist[_indexToDelete] = whitelist[whitelist.length - 1]; whitelist.pop(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `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, allowance(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 = allowance(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 Updates `owner` s allowance for `spender` based on spent `amount`. * * 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 {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev 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); } // 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 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the subtraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (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: Unlicense pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract MOSToken is ERC20, Ownable { bool public transferEnable; uint256 public maxSupply; mapping (address => bool) public isMinter; constructor () public ERC20("MetaOasis DAO", "MOS") { transferEnable = false; maxSupply = 1_000_000_000 ether; } function setMaxSupply(uint256 _maxSupply) external onlyOwner { require(_maxSupply < maxSupply, "!excess"); require(_maxSupply >= totalSupply(), "!less than totalSupply"); maxSupply = _maxSupply; } function setMinter(address _minter, bool _status) external onlyOwner { isMinter[_minter] = _status; } function setTransferEnable() external onlyOwner { transferEnable = !transferEnable; } /// @notice Creates `_amount` token to `_to`. Must only be called by minter function mint(address _to, uint256 _amount) external { require(isMinter[msg.sender] == true, "!minter"); require((totalSupply() + _amount) <= maxSupply, "!excess"); _mint(_to, _amount); } /** * @dev See {ERC20-_beforeTokenTransfer}. * * Requirements: * * - the contract has enabled transfer */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override { super._beforeTokenTransfer(from, to, amount); if (!transferEnable) { require(from == address(0), "ERC20: only allow mint"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.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 (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); } }
@notice Creates `_amount` token to `_to`. Must only be called by minter
function mint(address _to, uint256 _amount) external { require(isMinter[msg.sender] == true, "!minter"); require((totalSupply() + _amount) <= maxSupply, "!excess"); _mint(_to, _amount); }
100,437
[ 1, 2729, 1375, 67, 8949, 68, 1147, 358, 1375, 67, 869, 8338, 6753, 1338, 506, 2566, 635, 1131, 387, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 3903, 288, 203, 3639, 2583, 12, 291, 49, 2761, 63, 3576, 18, 15330, 65, 422, 638, 16, 17528, 1154, 387, 8863, 203, 3639, 2583, 12443, 4963, 3088, 1283, 1435, 397, 389, 8949, 13, 1648, 943, 3088, 1283, 16, 17528, 338, 614, 8863, 203, 3639, 389, 81, 474, 24899, 869, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.8.0; pragma experimental ABIEncoderV2; import { IVault } from "./IVault.sol"; import { VaultBase } from "./VaultBase.sol"; import { IFujiAdmin } from "../IFujiAdmin.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { AggregatorV3Interface } from "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IFujiERC1155 } from "../FujiERC1155/IFujiERC1155.sol"; import { IProvider } from "../Providers/IProvider.sol"; import { IAlphaWhiteList } from "../IAlphaWhiteList.sol"; import { Errors } from "../Libraries/Errors.sol"; interface IVaultHarvester { function collectRewards(uint256 _farmProtocolNum) external returns (address claimedToken); } contract VaultETHUSDT is IVault, VaultBase, ReentrancyGuard { uint256 internal constant _BASE = 1e18; struct Factor { uint64 a; uint64 b; } // Safety factor Factor public safetyF; // Collateralization factor Factor public collatF; //State variables address[] public providers; address public override activeProvider; IFujiAdmin private _fujiAdmin; address public override fujiERC1155; AggregatorV3Interface public oracle; modifier isAuthorized() { require( msg.sender == _fujiAdmin.getController() || msg.sender == owner(), Errors.VL_NOT_AUTHORIZED ); _; } modifier onlyFlash() { require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED); _; } constructor() public { vAssets.collateralAsset = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // ETH vAssets.borrowAsset = address(0xdAC17F958D2ee523a2206206994597C13D831ec7); // USDT // 1.05 safetyF.a = 21; safetyF.b = 20; // 1.269 collatF.a = 80; collatF.b = 63; } receive() external payable {} //Core functions /** * @dev Deposits collateral and borrows underlying in a single function call from activeProvider * @param _collateralAmount: amount to be deposited * @param _borrowAmount: amount to be borrowed */ function depositAndBorrow(uint256 _collateralAmount, uint256 _borrowAmount) external payable { deposit(_collateralAmount); borrow(_borrowAmount); } /** * @dev Paybacks the underlying asset and withdraws collateral in a single function call from activeProvider * @param _paybackAmount: amount of underlying asset to be payback, pass -1 to pay full amount * @param _collateralAmount: amount of collateral to be withdrawn, pass -1 to withdraw maximum amount */ function paybackAndWithdraw(int256 _paybackAmount, int256 _collateralAmount) external payable { payback(_paybackAmount); withdraw(_collateralAmount); } /** * @dev Deposit Vault's type collateral to activeProvider * call Controller checkrates * @param _collateralAmount: to be deposited * Emits a {Deposit} event. */ function deposit(uint256 _collateralAmount) public payable override { require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR); // Alpha Whitelist Routine require( IAlphaWhiteList(_fujiAdmin.getaWhiteList()).whiteListRoutine( msg.sender, vAssets.collateralID, _collateralAmount, fujiERC1155 ), Errors.SP_ALPHA_WHITELIST ); // Delegate Call Deposit to current provider _deposit(_collateralAmount, address(activeProvider)); // Collateral Management IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, ""); emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount); } /** * @dev Withdraws Vault's type collateral from activeProvider * call Controller checkrates * @param _withdrawAmount: amount of collateral to withdraw * otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors) * Emits a {Withdraw} event. */ function withdraw(int256 _withdrawAmount) public override nonReentrant { // If call from Normal User do typical, otherwise Fliquidator if (msg.sender != _fujiAdmin.getFliquidator()) { updateF1155Balances(); // Get User Collateral in this Vault uint256 providedCollateral = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID); // Check User has collateral require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL); // Get Required Collateral with Factors to maintain debt position healthy uint256 neededCollateral = getNeededCollateralFor( IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID), true ); uint256 amountToWithdraw = _withdrawAmount < 0 ? providedCollateral.sub(neededCollateral) : uint256(_withdrawAmount); // Check Withdrawal amount, and that it will not fall undercollaterized. require( amountToWithdraw != 0 && providedCollateral.sub(amountToWithdraw) >= neededCollateral, Errors.VL_INVALID_WITHDRAW_AMOUNT ); // Collateral Management before Withdraw Operation IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw); // Delegate Call Withdraw to current provider _withdraw(amountToWithdraw, address(activeProvider)); // Transer Assets to User IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, amountToWithdraw); emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw); } else { // Logic used when called by Fliquidator _withdraw(uint256(_withdrawAmount), address(activeProvider)); IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, uint256(_withdrawAmount)); } } /** * @dev Borrows Vault's type underlying amount from activeProvider * @param _borrowAmount: token amount of underlying to borrow * Emits a {Borrow} event. */ function borrow(uint256 _borrowAmount) public override nonReentrant { updateF1155Balances(); uint256 providedCollateral = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID); // Get Required Collateral with Factors to maintain debt position healthy uint256 neededCollateral = getNeededCollateralFor( _borrowAmount.add(IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID)), true ); // Check Provided Collateral is not Zero, and greater than needed to maintain healthy position require( _borrowAmount != 0 && providedCollateral > neededCollateral, Errors.VL_INVALID_BORROW_AMOUNT ); // Debt Management IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, ""); // Delegate Call Borrow to current provider _borrow(_borrowAmount, address(activeProvider)); // Transer Assets to User IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _borrowAmount); emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount); } /** * @dev Paybacks Vault's type underlying to activeProvider * @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount * Emits a {Repay} event. */ function payback(int256 _repayAmount) public payable override { // If call from Normal User do typical, otherwise Fliquidator if (msg.sender != _fujiAdmin.getFliquidator()) { updateF1155Balances(); uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID); // Check User Debt is greater than Zero and amount is not Zero require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK); // TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt // If passed argument amount is negative do MAX uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount); // Check User Allowance require( IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback, Errors.VL_MISSING_ERC20_ALLOWANCE ); // Transfer Asset from User to Vault IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), amountToPayback); // Delegate Call Payback to current provider _payback(amountToPayback, address(activeProvider)); //TODO: Transfer corresponding Debt Amount to Fuji Treasury // Debt Management IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback); emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance); } else { // Logic used when called by Fliquidator _payback(uint256(_repayAmount), address(activeProvider)); } } /** * @dev Changes Vault debt and collateral to newProvider, called by Flasher * @param _newProvider new provider's address * @param _flashLoanAmount amount of flashloan underlying to repay Flashloan * Emits a {Switch} event. */ function executeSwitch( address _newProvider, uint256 _flashLoanAmount, uint256 fee ) external override onlyFlash whenNotPaused { // Compute Ratio of transfer before payback uint256 ratio = _flashLoanAmount.mul(1e18).div( IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset) ); // Payback current provider _payback(_flashLoanAmount, activeProvider); // Withdraw collateral proportional ratio from current provider uint256 collateraltoMove = IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18); _withdraw(collateraltoMove, activeProvider); // Deposit to the new provider _deposit(collateraltoMove, _newProvider); // Borrow from the new provider, borrowBalance + premium _borrow(_flashLoanAmount.add(fee), _newProvider); // return borrowed amount to Flasher IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(fee)); emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove); } //Setter, change state functions /** * @dev Sets the fujiAdmin Address * @param _newFujiAdmin: FujiAdmin Contract Address */ function setFujiAdmin(address _newFujiAdmin) public onlyOwner { _fujiAdmin = IFujiAdmin(_newFujiAdmin); } /** * @dev Sets a new active provider for the Vault * @param _provider: fuji address of the new provider * Emits a {SetActiveProvider} event. */ function setActiveProvider(address _provider) external override isAuthorized { activeProvider = _provider; emit SetActiveProvider(_provider); } //Administrative functions /** * @dev Sets a fujiERC1155 Collateral and Debt Asset manager for this vault and initializes it. * @param _fujiERC1155: fuji ERC1155 address */ function setFujiERC1155(address _fujiERC1155) external isAuthorized { fujiERC1155 = _fujiERC1155; vAssets.collateralID = IFujiERC1155(_fujiERC1155).addInitializeAsset( IFujiERC1155.AssetType.collateralToken, address(this) ); vAssets.borrowID = IFujiERC1155(_fujiERC1155).addInitializeAsset( IFujiERC1155.AssetType.debtToken, address(this) ); } /** * @dev Set Factors "a" and "b" for a Struct Factor * For safetyF; Sets Safety Factor of Vault, should be > 1, a/b * For collatF; Sets Collateral Factor of Vault, should be > 1, a/b * @param _newFactorA: Nominator * @param _newFactorB: Denominator * @param _isSafety: safetyF or collatF */ function setFactor( uint64 _newFactorA, uint64 _newFactorB, bool _isSafety ) external isAuthorized { if (_isSafety) { safetyF.a = _newFactorA; safetyF.b = _newFactorB; } else { collatF.a = _newFactorA; collatF.b = _newFactorB; } } /** * @dev Sets the Oracle address (Must Comply with AggregatorV3Interface) * @param _oracle: new Oracle address */ function setOracle(address _oracle) external isAuthorized { oracle = AggregatorV3Interface(_oracle); } /** * @dev Set providers to the Vault * @param _providers: new providers' addresses */ function setProviders(address[] calldata _providers) external isAuthorized { providers = _providers; } /** * @dev External Function to call updateState in F1155 */ function updateF1155Balances() public override { uint256 borrowBals; uint256 depositBals; // take into account all balances across providers uint256 length = providers.length; for (uint256 i = 0; i < length; i++) { borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.borrowAsset)); } for (uint256 i = 0; i < length; i++) { depositBals = depositBals.add( IProvider(providers[i]).getDepositBalance(vAssets.collateralAsset) ); } IFujiERC1155(fujiERC1155).updateState(vAssets.borrowID, borrowBals); IFujiERC1155(fujiERC1155).updateState(vAssets.collateralID, depositBals); } //Getter Functions /** * @dev Returns an array of the Vault's providers */ function getProviders() external view override returns (address[] memory) { return providers; } /** * @dev Returns an amount to be paid as bonus for liquidation * @param _amount: Vault underlying type intended to be liquidated * @param _flash: Flash or classic type of liquidation, bonus differs */ function getLiquidationBonusFor(uint256 _amount, bool _flash) external view override returns (uint256) { if (_flash) { // Bonus Factors for Flash Liquidation (uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL(); return _amount.mul(a).div(b); } else { //Bonus Factors for Normal Liquidation (uint64 a, uint64 b) = _fujiAdmin.getBonusLiq(); return _amount.mul(a).div(b); } } /** * @dev Returns the amount of collateral needed, including or not safety factors * @param _amount: Vault underlying type intended to be borrowed * @param _withFactors: Inidicate if computation should include safety_Factors */ function getNeededCollateralFor(uint256 _amount, bool _withFactors) public view override returns (uint256) { // Get price of DAI in ETH (, int256 latestPrice, , , ) = oracle.latestRoundData(); uint256 minimumReq = (_amount.mul(1e12).mul(uint256(latestPrice))).div(_BASE); if (_withFactors) { return minimumReq.mul(collatF.a).mul(safetyF.a).div(collatF.b).div(safetyF.b); } else { return minimumReq; } } /** * @dev Returns the borrow balance of the Vault's underlying at a particular provider * @param _provider: address of a provider */ function borrowBalance(address _provider) external view override returns (uint256) { return IProvider(_provider).getBorrowBalance(vAssets.borrowAsset); } /** * @dev Returns the deposit balance of the Vault's type collateral at a particular provider * @param _provider: address of a provider */ function depositBalance(address _provider) external view override returns (uint256) { return IProvider(_provider).getDepositBalance(vAssets.collateralAsset); } /** * @dev Harvests the Rewards from baseLayer Protocols * @param _farmProtocolNum: number per VaultHarvester Contract for specific farm */ function harvestRewards(uint256 _farmProtocolNum) public onlyOwner { address tokenReturned = IVaultHarvester(_fujiAdmin.getVaultHarvester()).collectRewards(_farmProtocolNum); uint256 tokenBal = IERC20(tokenReturned).balanceOf(address(this)); require(tokenReturned != address(0) && tokenBal > 0, Errors.VL_HARVESTING_FAILED); IERC20(tokenReturned).uniTransfer(payable(_fujiAdmin.getTreasury()), tokenBal); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; pragma experimental ABIEncoderV2; interface IVault { // Events // Log Users Deposit event Deposit(address indexed userAddrs, address indexed asset, uint256 amount); // Log Users withdraw event Withdraw(address indexed userAddrs, address indexed asset, uint256 amount); // Log Users borrow event Borrow(address indexed userAddrs, address indexed asset, uint256 amount); // Log Users debt repay event Payback(address indexed userAddrs, address indexed asset, uint256 amount); // Log New active provider event SetActiveProvider(address providerAddr); // Log Switch providers event Switch( address vault, address fromProviderAddrs, address toProviderAddr, uint256 debtamount, uint256 collattamount ); // Core Vault Functions function deposit(uint256 _collateralAmount) external payable; function withdraw(int256 _withdrawAmount) external; function borrow(uint256 _borrowAmount) external; function payback(int256 _repayAmount) external payable; function executeSwitch( address _newProvider, uint256 _flashLoanDebt, uint256 _fee ) external; //Getter Functions function activeProvider() external view returns (address); function borrowBalance(address _provider) external view returns (uint256); function depositBalance(address _provider) external view returns (uint256); function getNeededCollateralFor(uint256 _amount, bool _withFactors) external view returns (uint256); function getLiquidationBonusFor(uint256 _amount, bool _flash) external view returns (uint256); function getProviders() external view returns (address[] memory); function fujiERC1155() external view returns (address); //Setter Functions function setActiveProvider(address _provider) external; function updateF1155Balances() external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { UniERC20 } from "../Libraries/LibUniERC20.sol"; contract VaultControl is Ownable, Pausable { using SafeMath for uint256; using UniERC20 for IERC20; //Asset Struct struct VaultAssets { address collateralAsset; address borrowAsset; uint64 collateralID; uint64 borrowID; } //Vault Struct for Managed Assets VaultAssets public vAssets; //Pause Functions /** * @dev Emergency Call to stop all basic money flow functions. */ function pause() public onlyOwner { _pause(); } /** * @dev Emergency Call to stop all basic money flow functions. */ function unpause() public onlyOwner { _pause(); } } contract VaultBase is VaultControl { // Internal functions /** * @dev Executes deposit operation with delegatecall. * @param _amount: amount to be deposited * @param _provider: address of provider to be used */ function _deposit(uint256 _amount, address _provider) internal { bytes memory data = abi.encodeWithSignature("deposit(address,uint256)", vAssets.collateralAsset, _amount); _execute(_provider, data); } /** * @dev Executes withdraw operation with delegatecall. * @param _amount: amount to be withdrawn * @param _provider: address of provider to be used */ function _withdraw(uint256 _amount, address _provider) internal { bytes memory data = abi.encodeWithSignature("withdraw(address,uint256)", vAssets.collateralAsset, _amount); _execute(_provider, data); } /** * @dev Executes borrow operation with delegatecall. * @param _amount: amount to be borrowed * @param _provider: address of provider to be used */ function _borrow(uint256 _amount, address _provider) internal { bytes memory data = abi.encodeWithSignature("borrow(address,uint256)", vAssets.borrowAsset, _amount); _execute(_provider, data); } /** * @dev Executes payback operation with delegatecall. * @param _amount: amount to be paid back * @param _provider: address of provider to be used */ function _payback(uint256 _amount, address _provider) internal { bytes memory data = abi.encodeWithSignature("payback(address,uint256)", vAssets.borrowAsset, _amount); _execute(_provider, data); } /** * @dev Returns byte response of delegatcalls */ function _execute(address _target, bytes memory _data) internal whenNotPaused returns (bytes memory response) { /* solhint-disable */ assembly { let succeeded := delegatecall(sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0) let size := returndatasize() response := mload(0x40) mstore(0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f)))) mstore(response, size) returndatacopy(add(response, 0x20), 0, size) switch iszero(succeeded) case 1 { // throw if delegatecall failed revert(add(response, 0x20), size) } } /* solhint-disable */ } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12 <0.8.0; interface IFujiAdmin { function getFlasher() external view returns (address); function getFliquidator() external view returns (address); function getController() external view returns (address); function getTreasury() external view returns (address payable); function getaWhiteList() external view returns (address); function getVaultHarvester() external view returns (address); function getBonusFlashL() external view returns (uint64, uint64); function getBonusLiq() external view returns (uint64, uint64); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; interface AggregatorV3Interface { function decimals() external view returns (uint8); function description() external view returns (string memory); function version() external view returns (uint256); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData(uint80 _roundId) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.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.12; pragma experimental ABIEncoderV2; interface IFujiERC1155 { //Asset Types enum AssetType { //uint8 = 0 collateralToken, //uint8 = 1 debtToken } //General Getter Functions function getAssetID(AssetType _type, address _assetAddr) external view returns (uint256); function qtyOfManagedAssets() external view returns (uint64); function balanceOf(address _account, uint256 _id) external view returns (uint256); //function splitBalanceOf(address account,uint256 _AssetID) external view returns (uint256,uint256); //function balanceOfBatchType(address account, AssetType _Type) external view returns (uint256); //Permit Controlled Functions function mint( address _account, uint256 _id, uint256 _amount, bytes memory _data ) external; function burn( address _account, uint256 _id, uint256 _amount ) external; function updateState(uint256 _assetID, uint256 _newBalance) external; function addInitializeAsset(AssetType _type, address _addr) external returns (uint64); } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.0; interface IProvider { //Basic Core Functions function deposit(address _collateralAsset, uint256 _collateralAmount) external payable; function borrow(address _borrowAsset, uint256 _borrowAmount) external payable; function withdraw(address _collateralAsset, uint256 _collateralAmount) external payable; function payback(address _borrowAsset, uint256 _borrowAmount) external payable; // returns the borrow annualized rate for an asset in ray (1e27) //Example 8.5% annual interest = 0.085 x 10^27 = 85000000000000000000000000 or 85*(10**24) function getBorrowRateFor(address _asset) external view returns (uint256); function getBorrowBalance(address _asset) external view returns (uint256); function getDepositBalance(address _asset) external view returns (uint256); function getBorrowBalanceOf(address _asset, address _who) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12 <0.8.0; interface IAlphaWhiteList { function whiteListRoutine( address _usrAddrs, uint64 _assetId, uint256 _amount, address _erc1155 ) external returns(bool); } // SPDX-License-Identifier: agpl-3.0 pragma solidity <0.8.0; /** * @title Errors library * @author Fuji * @notice Defines the error messages emitted by the different contracts of the Aave protocol * @dev Error messages prefix glossary: * - VL = Validation Logic 100 series * - MATH = Math libraries 200 series * - RF = Refinancing 300 series * - VLT = vault 400 series * - SP = Special 900 series */ library Errors { //Errors string public constant VL_INDEX_OVERFLOW = "100"; // index overflows uint128 string public constant VL_INVALID_MINT_AMOUNT = "101"; //invalid amount to mint string public constant VL_INVALID_BURN_AMOUNT = "102"; //invalid amount to burn string public constant VL_AMOUNT_ERROR = "103"; //Input value >0, and for ETH msg.value and amount shall match string public constant VL_INVALID_WITHDRAW_AMOUNT = "104"; //Withdraw amount exceeds provided collateral, or falls undercollaterized string public constant VL_INVALID_BORROW_AMOUNT = "105"; //Borrow amount does not meet collaterization string public constant VL_NO_DEBT_TO_PAYBACK = "106"; //Msg sender has no debt amount to be payback string public constant VL_MISSING_ERC20_ALLOWANCE = "107"; //Msg sender has not approved ERC20 full amount to transfer string public constant VL_USER_NOT_LIQUIDATABLE = "108"; //User debt position is not liquidatable string public constant VL_DEBT_LESS_THAN_AMOUNT = "109"; //User debt is less than amount to partial close string public constant VL_PROVIDER_ALREADY_ADDED = "110"; // Provider is already added in Provider Array string public constant VL_NOT_AUTHORIZED = "111"; //Not authorized string public constant VL_INVALID_COLLATERAL = "112"; //There is no Collateral, or Collateral is not in active in vault string public constant VL_NO_ERC20_BALANCE = "113"; //User does not have ERC20 balance string public constant VL_INPUT_ERROR = "114"; //Check inputs. For ERC1155 batch functions, array sizes should match. string public constant VL_ASSET_EXISTS = "115"; //Asset intended to be added already exists in FujiERC1155 string public constant VL_ZERO_ADDR_1155 = "116"; //ERC1155: balance/transfer for zero address string public constant VL_NOT_A_CONTRACT = "117"; //Address is not a contract. string public constant VL_INVALID_ASSETID_1155 = "118"; //ERC1155 Asset ID is invalid. string public constant VL_NO_ERC1155_BALANCE = "119"; //ERC1155: insufficient balance for transfer. string public constant VL_MISSING_ERC1155_APPROVAL = "120"; //ERC1155: transfer caller is not owner nor approved. string public constant VL_RECEIVER_REJECT_1155 = "121"; //ERC1155Receiver rejected tokens string public constant VL_RECEIVER_CONTRACT_NON_1155 = "122"; //ERC1155: transfer to non ERC1155Receiver implementer string public constant VL_OPTIMIZER_FEE_SMALL = "123"; //Fuji OptimizerFee has to be > 1 RAY (1e27) string public constant VL_UNDERCOLLATERIZED_ERROR = "124"; // Flashloan-Flashclose cannot be used when User's collateral is worth less than intended debt position to close. string public constant VL_MINIMUM_PAYBACK_ERROR = "125"; // Minimum Amount payback should be at least Fuji Optimizerfee accrued interest. string public constant VL_HARVESTING_FAILED = "126"; //Harvesting Function failed, check provided _farmProtocolNum or no claimable balance. string public constant MATH_DIVISION_BY_ZERO = "201"; string public constant MATH_ADDITION_OVERFLOW = "202"; string public constant MATH_MULTIPLICATION_OVERFLOW = "203"; string public constant RF_NO_GREENLIGHT = "300"; // Conditions for refinancing are not met, greenLight, deltaAPRThreshold, deltatimestampThreshold string public constant RF_INVALID_RATIO_VALUES = "301"; // Ratio Value provided is invalid, _ratioA/_ratioB <= 1, and > 0, or activeProvider borrowBalance = 0 string public constant RF_CHECK_RATES_FALSE = "302"; //Check Rates routine returned False string public constant VLT_CALLER_MUST_BE_VAULT = "401"; // The caller of this function must be a vault string public constant SP_ALPHA_WHITELIST = "901"; // One ETH cap value for Alpha Version < 1 ETH } // 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 "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; 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 { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; library UniERC20 { using SafeERC20 for IERC20; IERC20 private constant _ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); IERC20 private constant _ZERO_ADDRESS = IERC20(0); function isETH(IERC20 token) internal pure returns (bool) { return (token == _ZERO_ADDRESS || token == _ETH_ADDRESS); } function uniBalanceOf(IERC20 token, address account) internal view returns (uint256) { if (isETH(token)) { return account.balance; } else { return token.balanceOf(account); } } function uniTransfer( IERC20 token, address payable to, uint256 amount ) internal { if (amount > 0) { if (isETH(token)) { to.transfer(amount); } else { token.safeTransfer(to, amount); } } } function uniApprove( IERC20 token, address to, uint256 amount ) internal { require(!isETH(token), "Approve called on ETH"); if (amount == 0) { token.safeApprove(to, 0); } else { uint256 allowance = token.allowance(address(this), to); if (allowance < amount) { if (allowance > 0) { token.safeApprove(to, 0); } token.safeApprove(to, amount); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./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.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.4.25 <0.8.0; pragma experimental ABIEncoderV2; import { IVault } from "./IVault.sol"; import { VaultBase } from "./VaultBase.sol"; import { IFujiAdmin } from "../IFujiAdmin.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { AggregatorV3Interface } from "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IFujiERC1155 } from "../FujiERC1155/IFujiERC1155.sol"; import { IProvider } from "../Providers/IProvider.sol"; import { IAlphaWhiteList } from "../IAlphaWhiteList.sol"; import { Errors } from "../Libraries/Errors.sol"; interface IVaultHarvester { function collectRewards(uint256 _farmProtocolNum) external returns (address claimedToken); } contract VaultETHUSDC is IVault, VaultBase, ReentrancyGuard { uint256 internal constant _BASE = 1e18; struct Factor { uint64 a; uint64 b; } // Safety factor Factor public safetyF; // Collateralization factor Factor public collatF; //State variables address[] public providers; address public override activeProvider; IFujiAdmin private _fujiAdmin; address public override fujiERC1155; AggregatorV3Interface public oracle; modifier isAuthorized() { require( msg.sender == owner() || msg.sender == _fujiAdmin.getController(), Errors.VL_NOT_AUTHORIZED ); _; } modifier onlyFlash() { require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED); _; } constructor() public { vAssets.collateralAsset = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // ETH vAssets.borrowAsset = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); // USDC // 1.05 safetyF.a = 21; safetyF.b = 20; // 1.269 collatF.a = 80; collatF.b = 63; } receive() external payable {} //Core functions /** * @dev Deposits collateral and borrows underlying in a single function call from activeProvider * @param _collateralAmount: amount to be deposited * @param _borrowAmount: amount to be borrowed */ function depositAndBorrow(uint256 _collateralAmount, uint256 _borrowAmount) external payable { deposit(_collateralAmount); borrow(_borrowAmount); } /** * @dev Paybacks the underlying asset and withdraws collateral in a single function call from activeProvider * @param _paybackAmount: amount of underlying asset to be payback, pass -1 to pay full amount * @param _collateralAmount: amount of collateral to be withdrawn, pass -1 to withdraw maximum amount */ function paybackAndWithdraw(int256 _paybackAmount, int256 _collateralAmount) external payable { payback(_paybackAmount); withdraw(_collateralAmount); } /** * @dev Deposit Vault's type collateral to activeProvider * call Controller checkrates * @param _collateralAmount: to be deposited * Emits a {Deposit} event. */ function deposit(uint256 _collateralAmount) public payable override { require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR); // Alpha Whitelist Routine require( IAlphaWhiteList(_fujiAdmin.getaWhiteList()).whiteListRoutine( msg.sender, vAssets.collateralID, _collateralAmount, fujiERC1155 ), Errors.SP_ALPHA_WHITELIST ); // Delegate Call Deposit to current provider _deposit(_collateralAmount, address(activeProvider)); // Collateral Management IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, ""); emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount); } /** * @dev Withdraws Vault's type collateral from activeProvider * call Controller checkrates * @param _withdrawAmount: amount of collateral to withdraw * otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors) * Emits a {Withdraw} event. */ function withdraw(int256 _withdrawAmount) public override nonReentrant { // If call from Normal User do typical, otherwise Fliquidator if (msg.sender != _fujiAdmin.getFliquidator()) { updateF1155Balances(); // Get User Collateral in this Vault uint256 providedCollateral = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID); // Check User has collateral require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL); // Get Required Collateral with Factors to maintain debt position healthy uint256 neededCollateral = getNeededCollateralFor( IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID), true ); uint256 amountToWithdraw = _withdrawAmount < 0 ? providedCollateral.sub(neededCollateral) : uint256(_withdrawAmount); // Check Withdrawal amount, and that it will not fall undercollaterized. require( amountToWithdraw != 0 && providedCollateral.sub(amountToWithdraw) >= neededCollateral, Errors.VL_INVALID_WITHDRAW_AMOUNT ); // Collateral Management before Withdraw Operation IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw); // Delegate Call Withdraw to current provider _withdraw(amountToWithdraw, address(activeProvider)); // Transer Assets to User IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, amountToWithdraw); emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw); } else { // Logic used when called by Fliquidator _withdraw(uint256(_withdrawAmount), address(activeProvider)); IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, uint256(_withdrawAmount)); } } /** * @dev Borrows Vault's type underlying amount from activeProvider * @param _borrowAmount: token amount of underlying to borrow * Emits a {Borrow} event. */ function borrow(uint256 _borrowAmount) public override nonReentrant { updateF1155Balances(); uint256 providedCollateral = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID); // Get Required Collateral with Factors to maintain debt position healthy uint256 neededCollateral = getNeededCollateralFor( _borrowAmount.add(IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID)), true ); // Check Provided Collateral is not Zero, and greater than needed to maintain healthy position require( _borrowAmount != 0 && providedCollateral > neededCollateral, Errors.VL_INVALID_BORROW_AMOUNT ); // Debt Management IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, ""); // Delegate Call Borrow to current provider _borrow(_borrowAmount, address(activeProvider)); // Transer Assets to User IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _borrowAmount); emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount); } /** * @dev Paybacks Vault's type underlying to activeProvider * @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount * Emits a {Repay} event. */ function payback(int256 _repayAmount) public payable override { // If call from Normal User do typical, otherwise Fliquidator if (msg.sender != _fujiAdmin.getFliquidator()) { updateF1155Balances(); uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID); // Check User Debt is greater than Zero and amount is not Zero require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK); // TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt // If passed argument amount is negative do MAX uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount); // Check User Allowance require( IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback, Errors.VL_MISSING_ERC20_ALLOWANCE ); // Transfer Asset from User to Vault IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), amountToPayback); // Delegate Call Payback to current provider _payback(amountToPayback, address(activeProvider)); //TODO: Transfer corresponding Debt Amount to Fuji Treasury // Debt Management IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback); emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance); } else { // Logic used when called by Fliquidator _payback(uint256(_repayAmount), address(activeProvider)); } } /** * @dev Changes Vault debt and collateral to newProvider, called by Flasher * @param _newProvider new provider's address * @param _flashLoanAmount amount of flashloan underlying to repay Flashloan * Emits a {Switch} event. */ function executeSwitch( address _newProvider, uint256 _flashLoanAmount, uint256 _fee ) external override onlyFlash whenNotPaused { // Compute Ratio of transfer before payback uint256 ratio = (_flashLoanAmount).mul(1e18).div( IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset) ); // Payback current provider _payback(_flashLoanAmount, activeProvider); // Withdraw collateral proportional ratio from current provider uint256 collateraltoMove = IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18); _withdraw(collateraltoMove, activeProvider); // Deposit to the new provider _deposit(collateraltoMove, _newProvider); // Borrow from the new provider, borrowBalance + premium _borrow(_flashLoanAmount.add(_fee), _newProvider); // return borrowed amount to Flasher IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(_fee)); emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove); } //Setter, change state functions /** * @dev Sets the fujiAdmin Address * @param _newFujiAdmin: FujiAdmin Contract Address */ function setFujiAdmin(address _newFujiAdmin) external onlyOwner { _fujiAdmin = IFujiAdmin(_newFujiAdmin); } /** * @dev Sets a new active provider for the Vault * @param _provider: fuji address of the new provider * Emits a {SetActiveProvider} event. */ function setActiveProvider(address _provider) external override isAuthorized { activeProvider = _provider; emit SetActiveProvider(_provider); } //Administrative functions /** * @dev Sets a fujiERC1155 Collateral and Debt Asset manager for this vault and initializes it. * @param _fujiERC1155: fuji ERC1155 address */ function setFujiERC1155(address _fujiERC1155) external isAuthorized { fujiERC1155 = _fujiERC1155; vAssets.collateralID = IFujiERC1155(_fujiERC1155).addInitializeAsset( IFujiERC1155.AssetType.collateralToken, address(this) ); vAssets.borrowID = IFujiERC1155(_fujiERC1155).addInitializeAsset( IFujiERC1155.AssetType.debtToken, address(this) ); } /** * @dev Set Factors "a" and "b" for a Struct Factor * For safetyF; Sets Safety Factor of Vault, should be > 1, a/b * For collatF; Sets Collateral Factor of Vault, should be > 1, a/b * @param _newFactorA: Nominator * @param _newFactorB: Denominator * @param _isSafety: safetyF or collatF */ function setFactor( uint64 _newFactorA, uint64 _newFactorB, bool _isSafety ) external isAuthorized { if (_isSafety) { safetyF.a = _newFactorA; safetyF.b = _newFactorB; } else { collatF.a = _newFactorA; collatF.b = _newFactorB; } } /** * @dev Sets the Oracle address (Must Comply with AggregatorV3Interface) * @param _oracle: new Oracle address */ function setOracle(address _oracle) external isAuthorized { oracle = AggregatorV3Interface(_oracle); } /** * @dev Set providers to the Vault * @param _providers: new providers' addresses */ function setProviders(address[] calldata _providers) external isAuthorized { providers = _providers; } /** * @dev External Function to call updateState in F1155 */ function updateF1155Balances() public override { uint256 borrowBals; uint256 depositBals; // take into account all balances across providers uint256 length = providers.length; for (uint256 i = 0; i < length; i++) { borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.borrowAsset)); } for (uint256 i = 0; i < length; i++) { depositBals = depositBals.add( IProvider(providers[i]).getDepositBalance(vAssets.collateralAsset) ); } IFujiERC1155(fujiERC1155).updateState(vAssets.borrowID, borrowBals); IFujiERC1155(fujiERC1155).updateState(vAssets.collateralID, depositBals); } //Getter Functions /** * @dev Returns an array of the Vault's providers */ function getProviders() external view override returns (address[] memory) { return providers; } /** * @dev Returns an amount to be paid as bonus for liquidation * @param _amount: Vault underlying type intended to be liquidated * @param _flash: Flash or classic type of liquidation, bonus differs */ function getLiquidationBonusFor(uint256 _amount, bool _flash) external view override returns (uint256) { if (_flash) { // Bonus Factors for Flash Liquidation (uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL(); return _amount.mul(a).div(b); } else { //Bonus Factors for Normal Liquidation (uint64 a, uint64 b) = _fujiAdmin.getBonusLiq(); return _amount.mul(a).div(b); } } /** * @dev Returns the amount of collateral needed, including or not safety factors * @param _amount: Vault underlying type intended to be borrowed * @param _withFactors: Inidicate if computation should include safety_Factors */ function getNeededCollateralFor(uint256 _amount, bool _withFactors) public view override returns (uint256) { // Get price of USDC in ETH (, int256 latestPrice, , , ) = oracle.latestRoundData(); uint256 minimumReq = (_amount.mul(1e12).mul(uint256(latestPrice))).div(_BASE); if (_withFactors) { return minimumReq.mul(collatF.a).mul(safetyF.a).div(collatF.b).div(safetyF.b); } else { return minimumReq; } } /** * @dev Returns the borrow balance of the Vault's underlying at a particular provider * @param _provider: address of a provider */ function borrowBalance(address _provider) external view override returns (uint256) { return IProvider(_provider).getBorrowBalance(vAssets.borrowAsset); } /** * @dev Returns the deposit balance of the Vault's type collateral at a particular provider * @param _provider: address of a provider */ function depositBalance(address _provider) external view override returns (uint256) { return IProvider(_provider).getDepositBalance(vAssets.collateralAsset); } /** * @dev Harvests the Rewards from baseLayer Protocols * @param _farmProtocolNum: number per VaultHarvester Contract for specific farm */ function harvestRewards(uint256 _farmProtocolNum) external onlyOwner { address tokenReturned = IVaultHarvester(_fujiAdmin.getVaultHarvester()).collectRewards(_farmProtocolNum); uint256 tokenBal = IERC20(tokenReturned).balanceOf(address(this)); require(tokenReturned != address(0) && tokenBal > 0, Errors.VL_HARVESTING_FAILED); IERC20(tokenReturned).uniTransfer(payable(_fujiAdmin.getTreasury()), tokenBal); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12 <0.8.0; pragma experimental ABIEncoderV2; import { IVault } from "./IVault.sol"; import { VaultBase } from "./VaultBase.sol"; import { IFujiAdmin } from "../IFujiAdmin.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import { AggregatorV3Interface } from "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IFujiERC1155 } from "../FujiERC1155/IFujiERC1155.sol"; import { IProvider } from "../Providers/IProvider.sol"; import { IAlphaWhiteList } from "../IAlphaWhiteList.sol"; import { Errors } from "../Libraries/Errors.sol"; interface IVaultHarvester { function collectRewards(uint256 _farmProtocolNum) external returns (address claimedToken); } contract VaultETHDAI is IVault, VaultBase, ReentrancyGuard { uint256 internal constant _BASE = 1e18; struct Factor { uint64 a; uint64 b; } // Safety factor Factor public safetyF; // Collateralization factor Factor public collatF; //State variables address[] public providers; address public override activeProvider; IFujiAdmin private _fujiAdmin; address public override fujiERC1155; AggregatorV3Interface public oracle; modifier isAuthorized() { require( msg.sender == owner() || msg.sender == _fujiAdmin.getController(), Errors.VL_NOT_AUTHORIZED ); _; } modifier onlyFlash() { require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED); _; } constructor() public { vAssets.collateralAsset = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // ETH vAssets.borrowAsset = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); // DAI // 1.05 safetyF.a = 21; safetyF.b = 20; // 1.269 collatF.a = 80; collatF.b = 63; } receive() external payable {} //Core functions /** * @dev Deposits collateral and borrows underlying in a single function call from activeProvider * @param _collateralAmount: amount to be deposited * @param _borrowAmount: amount to be borrowed */ function depositAndBorrow(uint256 _collateralAmount, uint256 _borrowAmount) external payable { deposit(_collateralAmount); borrow(_borrowAmount); } /** * @dev Paybacks the underlying asset and withdraws collateral in a single function call from activeProvider * @param _paybackAmount: amount of underlying asset to be payback, pass -1 to pay full amount * @param _collateralAmount: amount of collateral to be withdrawn, pass -1 to withdraw maximum amount */ function paybackAndWithdraw(int256 _paybackAmount, int256 _collateralAmount) external payable { payback(_paybackAmount); withdraw(_collateralAmount); } /** * @dev Deposit Vault's type collateral to activeProvider * call Controller checkrates * @param _collateralAmount: to be deposited * Emits a {Deposit} event. */ function deposit(uint256 _collateralAmount) public payable override { require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR); // Alpha Whitelist Routine require( IAlphaWhiteList(_fujiAdmin.getaWhiteList()).whiteListRoutine( msg.sender, vAssets.collateralID, _collateralAmount, fujiERC1155 ), Errors.SP_ALPHA_WHITELIST ); // Delegate Call Deposit to current provider _deposit(_collateralAmount, address(activeProvider)); // Collateral Management IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, ""); emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount); } /** * @dev Withdraws Vault's type collateral from activeProvider * call Controller checkrates * @param _withdrawAmount: amount of collateral to withdraw * otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors) * Emits a {Withdraw} event. */ function withdraw(int256 _withdrawAmount) public override nonReentrant { // If call from Normal User do typical, otherwise Fliquidator if (msg.sender != _fujiAdmin.getFliquidator()) { updateF1155Balances(); // Get User Collateral in this Vault uint256 providedCollateral = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID); // Check User has collateral require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL); // Get Required Collateral with Factors to maintain debt position healthy uint256 neededCollateral = getNeededCollateralFor( IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID), true ); uint256 amountToWithdraw = _withdrawAmount < 0 ? providedCollateral.sub(neededCollateral) : uint256(_withdrawAmount); // Check Withdrawal amount, and that it will not fall undercollaterized. require( amountToWithdraw != 0 && providedCollateral.sub(amountToWithdraw) >= neededCollateral, Errors.VL_INVALID_WITHDRAW_AMOUNT ); // Collateral Management before Withdraw Operation IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw); // Delegate Call Withdraw to current provider _withdraw(amountToWithdraw, address(activeProvider)); // Transer Assets to User IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, amountToWithdraw); emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw); } else { // Logic used when called by Fliquidator _withdraw(uint256(_withdrawAmount), address(activeProvider)); IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, uint256(_withdrawAmount)); } } /** * @dev Borrows Vault's type underlying amount from activeProvider * @param _borrowAmount: token amount of underlying to borrow * Emits a {Borrow} event. */ function borrow(uint256 _borrowAmount) public override nonReentrant { updateF1155Balances(); uint256 providedCollateral = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID); // Get Required Collateral with Factors to maintain debt position healthy uint256 neededCollateral = getNeededCollateralFor( _borrowAmount.add(IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID)), true ); // Check Provided Collateral is not Zero, and greater than needed to maintain healthy position require( _borrowAmount != 0 && providedCollateral > neededCollateral, Errors.VL_INVALID_BORROW_AMOUNT ); // Debt Management IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, ""); // Delegate Call Borrow to current provider _borrow(_borrowAmount, address(activeProvider)); // Transer Assets to User IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _borrowAmount); emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount); } /** * @dev Paybacks Vault's type underlying to activeProvider * @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount * Emits a {Repay} event. */ function payback(int256 _repayAmount) public payable override { // If call from Normal User do typical, otherwise Fliquidator if (msg.sender != _fujiAdmin.getFliquidator()) { updateF1155Balances(); uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID); // Check User Debt is greater than Zero and amount is not Zero require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK); // TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt // If passed argument amount is negative do MAX uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount); // Check User Allowance require( IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback, Errors.VL_MISSING_ERC20_ALLOWANCE ); // Transfer Asset from User to Vault IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), amountToPayback); // Delegate Call Payback to current provider _payback(amountToPayback, address(activeProvider)); //TODO: Transfer corresponding Debt Amount to Fuji Treasury // Debt Management IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback); emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance); } else { // Logic used when called by Fliquidator _payback(uint256(_repayAmount), address(activeProvider)); } } /** * @dev Changes Vault debt and collateral to newProvider, called by Flasher * @param _newProvider new provider's address * @param _flashLoanAmount amount of flashloan underlying to repay Flashloan * Emits a {Switch} event. */ function executeSwitch( address _newProvider, uint256 _flashLoanAmount, uint256 _fee ) external override onlyFlash whenNotPaused { // Compute Ratio of transfer before payback uint256 ratio = _flashLoanAmount.mul(1e18).div( IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset) ); // Payback current provider _payback(_flashLoanAmount, activeProvider); // Withdraw collateral proportional ratio from current provider uint256 collateraltoMove = IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18); _withdraw(collateraltoMove, activeProvider); // Deposit to the new provider _deposit(collateraltoMove, _newProvider); // Borrow from the new provider, borrowBalance + premium _borrow(_flashLoanAmount.add(_fee), _newProvider); // return borrowed amount to Flasher IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(_fee)); emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove); } //Setter, change state functions /** * @dev Sets a new active provider for the Vault * @param _provider: fuji address of the new provider * Emits a {SetActiveProvider} event. */ function setActiveProvider(address _provider) external override isAuthorized { activeProvider = _provider; emit SetActiveProvider(_provider); } //Administrative functions /** * @dev Sets the fujiAdmin Address * @param _newFujiAdmin: FujiAdmin Contract Address */ function setFujiAdmin(address _newFujiAdmin) external onlyOwner { _fujiAdmin = IFujiAdmin(_newFujiAdmin); } /** * @dev Sets a fujiERC1155 Collateral and Debt Asset manager for this vault and initializes it. * @param _fujiERC1155: fuji ERC1155 address */ function setFujiERC1155(address _fujiERC1155) external isAuthorized { fujiERC1155 = _fujiERC1155; vAssets.collateralID = IFujiERC1155(_fujiERC1155).addInitializeAsset( IFujiERC1155.AssetType.collateralToken, address(this) ); vAssets.borrowID = IFujiERC1155(_fujiERC1155).addInitializeAsset( IFujiERC1155.AssetType.debtToken, address(this) ); } /** * @dev Set Factors "a" and "b" for a Struct Factor * For safetyF; Sets Safety Factor of Vault, should be > 1, a/b * For collatF; Sets Collateral Factor of Vault, should be > 1, a/b * @param _newFactorA: Nominator * @param _newFactorB: Denominator * @param _isSafety: safetyF or collatF */ function setFactor( uint64 _newFactorA, uint64 _newFactorB, bool _isSafety ) external isAuthorized { if (_isSafety) { safetyF.a = _newFactorA; safetyF.b = _newFactorB; } else { collatF.a = _newFactorA; collatF.b = _newFactorB; } } /** * @dev Sets the Oracle address (Must Comply with AggregatorV3Interface) * @param _oracle: new Oracle address */ function setOracle(address _oracle) external isAuthorized { oracle = AggregatorV3Interface(_oracle); } /** * @dev Set providers to the Vault * @param _providers: new providers' addresses */ function setProviders(address[] calldata _providers) external isAuthorized { providers = _providers; } /** * @dev External Function to call updateState in F1155 */ function updateF1155Balances() public override { uint256 borrowBals; uint256 depositBals; // take into balances across all providers uint256 length = providers.length; for (uint256 i = 0; i < length; i++) { borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.borrowAsset)); } for (uint256 i = 0; i < length; i++) { depositBals = depositBals.add( IProvider(providers[i]).getDepositBalance(vAssets.collateralAsset) ); } IFujiERC1155(fujiERC1155).updateState(vAssets.borrowID, borrowBals); IFujiERC1155(fujiERC1155).updateState(vAssets.collateralID, depositBals); } //Getter Functions /** * @dev Returns an array of the Vault's providers */ function getProviders() external view override returns (address[] memory) { return providers; } /** * @dev Returns an amount to be paid as bonus for liquidation * @param _amount: Vault underlying type intended to be liquidated * @param _flash: Flash or classic type of liquidation, bonus differs */ function getLiquidationBonusFor(uint256 _amount, bool _flash) external view override returns (uint256) { if (_flash) { // Bonus Factors for Flash Liquidation (uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL(); return _amount.mul(a).div(b); } else { //Bonus Factors for Normal Liquidation (uint64 a, uint64 b) = _fujiAdmin.getBonusLiq(); return _amount.mul(a).div(b); } } /** * @dev Returns the amount of collateral needed, including or not safety factors * @param _amount: Vault underlying type intended to be borrowed * @param _withFactors: Inidicate if computation should include safety_Factors */ function getNeededCollateralFor(uint256 _amount, bool _withFactors) public view override returns (uint256) { // Get price of DAI in ETH (, int256 latestPrice, , , ) = oracle.latestRoundData(); uint256 minimumReq = (_amount.mul(uint256(latestPrice))).div(_BASE); if (_withFactors) { return minimumReq.mul(collatF.a).mul(safetyF.a).div(collatF.b).div(safetyF.b); } else { return minimumReq; } } /** * @dev Returns the borrow balance of the Vault's underlying at a particular provider * @param _provider: address of a provider */ function borrowBalance(address _provider) external view override returns (uint256) { return IProvider(_provider).getBorrowBalance(vAssets.borrowAsset); } /** * @dev Returns the deposit balance of the Vault's type collateral at a particular provider * @param _provider: address of a provider */ function depositBalance(address _provider) external view override returns (uint256) { return IProvider(_provider).getDepositBalance(vAssets.collateralAsset); } /** * @dev Harvests the Rewards from baseLayer Protocols * @param _farmProtocolNum: number per VaultHarvester Contract for specific farm */ function harvestRewards(uint256 _farmProtocolNum) external onlyOwner { address tokenReturned = IVaultHarvester(_fujiAdmin.getVaultHarvester()).collectRewards(_farmProtocolNum); uint256 tokenBal = IERC20(tokenReturned).balanceOf(address(this)); require(tokenReturned != address(0) && tokenBal > 0, Errors.VL_HARVESTING_FAILED); IERC20(tokenReturned).uniTransfer(payable(_fujiAdmin.getTreasury()), tokenBal); } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.8.0; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { UniERC20 } from "../Libraries/LibUniERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IProvider } from "./IProvider.sol"; interface LQTYInterface {} contract LQTYHelpers { function _initializeTrouve() internal { //TODO function } } contract ProviderLQTY is IProvider, LQTYHelpers { using SafeMath for uint256; using UniERC20 for IERC20; function deposit(address collateralAsset, uint256 collateralAmount) external payable override { collateralAsset; collateralAmount; //TODO } function borrow(address borrowAsset, uint256 borrowAmount) external payable override { borrowAsset; borrowAmount; //TODO } function withdraw(address collateralAsset, uint256 collateralAmount) external payable override { collateralAsset; collateralAmount; //TODO } function payback(address borrowAsset, uint256 borrowAmount) external payable override { borrowAsset; borrowAmount; //TODO } function getBorrowRateFor(address asset) external view override returns (uint256) { asset; //TODO return 0; } function getBorrowBalance(address _asset) external view override returns (uint256) { _asset; //TODO return 0; } function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) { _asset; _who; //TODO return 0; } function getDepositBalance(address _asset) external view override returns (uint256) { _asset; //TODO return 0; } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.5; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { UniERC20 } from "../Libraries/LibUniERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IProvider } from "./IProvider.sol"; interface IWethERC20 is IERC20 { function deposit() external payable; function withdraw(uint256) external; } interface SoloMarginContract { struct Info { address owner; uint256 number; } struct Price { uint256 value; } struct Value { uint256 value; } struct Rate { uint256 value; } enum ActionType { Deposit, Withdraw, Transfer, Buy, Sell, Trade, Liquidate, Vaporize, Call } enum AssetDenomination { Wei, Par } enum AssetReference { Delta, Target } struct AssetAmount { bool sign; AssetDenomination denomination; AssetReference ref; uint256 value; } struct ActionArgs { ActionType actionType; uint256 accountId; AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } struct Wei { bool sign; uint256 value; } function operate(Info[] calldata _accounts, ActionArgs[] calldata _actions) external; function getAccountWei(Info calldata _account, uint256 _marketId) external view returns (Wei memory); function getNumMarkets() external view returns (uint256); function getMarketTokenAddress(uint256 _marketId) external view returns (address); function getAccountValues(Info memory _account) external view returns (Value memory, Value memory); function getMarketInterestRate(uint256 _marketId) external view returns (Rate memory); } contract HelperFunct { /** * @dev get Dydx Solo Address */ function getDydxAddress() public pure returns (address addr) { addr = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; } /** * @dev get WETH address */ function getWETHAddr() public pure returns (address weth) { weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; } /** * @dev Return ethereum address */ function _getEthAddr() internal pure returns (address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // ETH Address } /** * @dev Get Dydx Market ID from token Address */ function _getMarketId(SoloMarginContract _solo, address _token) internal view returns (uint256 _marketId) { uint256 markets = _solo.getNumMarkets(); address token = _token == _getEthAddr() ? getWETHAddr() : _token; bool check = false; for (uint256 i = 0; i < markets; i++) { if (token == _solo.getMarketTokenAddress(i)) { _marketId = i; check = true; break; } } require(check, "DYDX Market doesnt exist!"); } /** * @dev Get Dydx Acccount arg */ function _getAccountArgs() internal view returns (SoloMarginContract.Info[] memory) { SoloMarginContract.Info[] memory accounts = new SoloMarginContract.Info[](1); accounts[0] = (SoloMarginContract.Info(address(this), 0)); return accounts; } /** * @dev Get Dydx Actions args. */ function _getActionsArgs( uint256 _marketId, uint256 _amt, bool _sign ) internal view returns (SoloMarginContract.ActionArgs[] memory) { SoloMarginContract.ActionArgs[] memory actions = new SoloMarginContract.ActionArgs[](1); SoloMarginContract.AssetAmount memory amount = SoloMarginContract.AssetAmount( _sign, SoloMarginContract.AssetDenomination.Wei, SoloMarginContract.AssetReference.Delta, _amt ); bytes memory empty; SoloMarginContract.ActionType action = _sign ? SoloMarginContract.ActionType.Deposit : SoloMarginContract.ActionType.Withdraw; actions[0] = SoloMarginContract.ActionArgs( action, 0, amount, _marketId, 0, address(this), 0, empty ); return actions; } } contract ProviderDYDX is IProvider, HelperFunct { using SafeMath for uint256; using UniERC20 for IERC20; bool public donothing = true; //Provider Core Functions /** * @dev Deposit ETH/ERC20_Token. * @param _asset: token address to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to deposit. */ function deposit(address _asset, uint256 _amount) external payable override { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); if (_asset == _getEthAddr()) { IWethERC20 tweth = IWethERC20(getWETHAddr()); tweth.deposit{ value: _amount }(); tweth.approve(getDydxAddress(), _amount); } else { IWethERC20 tweth = IWethERC20(_asset); tweth.approve(getDydxAddress(), _amount); } dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, true)); } /** * @dev Withdraw ETH/ERC20_Token. * @param _asset: token address to withdraw. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to withdraw. */ function withdraw(address _asset, uint256 _amount) external payable override { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, false)); if (_asset == _getEthAddr()) { IWethERC20 tweth = IWethERC20(getWETHAddr()); tweth.approve(address(tweth), _amount); tweth.withdraw(_amount); } } /** * @dev Borrow ETH/ERC20_Token. * @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to borrow. */ function borrow(address _asset, uint256 _amount) external payable override { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, false)); if (_asset == _getEthAddr()) { IWethERC20 tweth = IWethERC20(getWETHAddr()); tweth.approve(address(_asset), _amount); tweth.withdraw(_amount); } } /** * @dev Payback borrowed ETH/ERC20_Token. * @param _asset token address to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to payback. */ function payback(address _asset, uint256 _amount) external payable override { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); if (_asset == _getEthAddr()) { IWethERC20 tweth = IWethERC20(getWETHAddr()); tweth.deposit{ value: _amount }(); tweth.approve(getDydxAddress(), _amount); } else { IWethERC20 tweth = IWethERC20(_asset); tweth.approve(getDydxAddress(), _amount); } dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, true)); } /** * @dev Returns the current borrowing rate (APR) of a ETH/ERC20_Token, in ray(1e27). * @param _asset: token address to query the current borrowing rate. */ function getBorrowRateFor(address _asset) external view override returns (uint256) { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); SoloMarginContract.Rate memory _rate = dydxContract.getMarketInterestRate(marketId); return (_rate.value).mul(1e9).mul(365 days); } /** * @dev Returns the borrow balance of a ETH/ERC20_Token. * @param _asset: token address to query the balance. */ function getBorrowBalance(address _asset) external view override returns (uint256) { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); SoloMarginContract.Info memory account = SoloMarginContract.Info({ owner: msg.sender, number: 0 }); SoloMarginContract.Wei memory structbalance = dydxContract.getAccountWei(account, marketId); return structbalance.value; } /** * @dev Returns the borrow balance of a ETH/ERC20_Token. * @param _asset: token address to query the balance. * @param _who: address of the account. */ function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); SoloMarginContract.Info memory account = SoloMarginContract.Info({ owner: _who, number: 0 }); SoloMarginContract.Wei memory structbalance = dydxContract.getAccountWei(account, marketId); return structbalance.value; } /** * @dev Returns the borrow balance of a ETH/ERC20_Token. * @param _asset: token address to query the balance. */ function getDepositBalance(address _asset) external view override returns (uint256) { SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress()); uint256 marketId = _getMarketId(dydxContract, _asset); SoloMarginContract.Info memory account = SoloMarginContract.Info({ owner: msg.sender, number: 0 }); SoloMarginContract.Wei memory structbalance = dydxContract.getAccountWei(account, marketId); return structbalance.value; } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.5; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { UniERC20 } from "../Libraries/LibUniERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IProvider } from "./IProvider.sol"; interface IGenCToken is IERC20 { function redeem(uint256) external returns (uint256); function redeemUnderlying(uint256) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function borrowRatePerBlock() external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function getCash() external view returns (uint256); } interface ICErc20 is IGenCToken { function mint(uint256) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); } interface ICEth is IGenCToken { function mint() external payable; function repayBorrow() external payable; function repayBorrowBehalf(address borrower) external payable; } interface IComptroller { function markets(address) external returns (bool, uint256); function enterMarkets(address[] calldata) external returns (uint256[] memory); function exitMarket(address cTokenAddress) external returns (uint256); function getAccountLiquidity(address) external view returns ( uint256, uint256, uint256 ); } interface IFujiMappings { function addressMapping(address) external view returns (address); } contract HelperFunct { function _isETH(address token) internal pure returns (bool) { return (token == address(0) || token == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)); } function _getMappingAddr() internal pure returns (address) { return 0x6b09443595BFb8F91eA837c7CB4Fe1255782093b; } function _getComptrollerAddress() internal pure returns (address) { return 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; } //Compound functions /** * @dev Approves vault's assets as collateral for Compound Protocol. * @param _cTokenAddress: asset type to be approved as collateral. */ function _enterCollatMarket(address _cTokenAddress) internal { // Create a reference to the corresponding network Comptroller IComptroller comptroller = IComptroller(_getComptrollerAddress()); address[] memory cTokenMarkets = new address[](1); cTokenMarkets[0] = _cTokenAddress; comptroller.enterMarkets(cTokenMarkets); } /** * @dev Removes vault's assets as collateral for Compound Protocol. * @param _cTokenAddress: asset type to be removed as collateral. */ function _exitCollatMarket(address _cTokenAddress) internal { // Create a reference to the corresponding network Comptroller IComptroller comptroller = IComptroller(_getComptrollerAddress()); comptroller.exitMarket(_cTokenAddress); } } contract ProviderCompound is IProvider, HelperFunct { using SafeMath for uint256; using UniERC20 for IERC20; //Provider Core Functions /** * @dev Deposit ETH/ERC20_Token. * @param _asset: token address to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to deposit. */ function deposit(address _asset, uint256 _amount) external payable override { //Get cToken address from mapping address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); //Enter and/or ensure collateral market is enacted _enterCollatMarket(cTokenAddr); if (_isETH(_asset)) { // Create a reference to the cToken contract ICEth cToken = ICEth(cTokenAddr); //Compound protocol Mints cTokens, ETH method cToken.mint{ value: _amount }(); } else { // Create reference to the ERC20 contract IERC20 erc20token = IERC20(_asset); // Create a reference to the cToken contract ICErc20 cToken = ICErc20(cTokenAddr); //Checks, Vault balance of ERC20 to make deposit require(erc20token.balanceOf(address(this)) >= _amount, "Not enough Balance"); //Approve to move ERC20tokens erc20token.uniApprove(address(cTokenAddr), _amount); // Compound Protocol mints cTokens, trhow error if not require(cToken.mint(_amount) == 0, "Deposit-failed"); } } /** * @dev Withdraw ETH/ERC20_Token. * @param _asset: token address to withdraw. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to withdraw. */ function withdraw(address _asset, uint256 _amount) external payable override { //Get cToken address from mapping address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); // Create a reference to the corresponding cToken contract IGenCToken cToken = IGenCToken(cTokenAddr); //Compound Protocol Redeem Process, throw errow if not. require(cToken.redeemUnderlying(_amount) == 0, "Withdraw-failed"); } /** * @dev Borrow ETH/ERC20_Token. * @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to borrow. */ function borrow(address _asset, uint256 _amount) external payable override { //Get cToken address from mapping address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); // Create a reference to the corresponding cToken contract IGenCToken cToken = IGenCToken(cTokenAddr); //Enter and/or ensure collateral market is enacted //_enterCollatMarket(cTokenAddr); //Compound Protocol Borrow Process, throw errow if not. require(cToken.borrow(_amount) == 0, "borrow-failed"); } /** * @dev Payback borrowed ETH/ERC20_Token. * @param _asset token address to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount: token amount to payback. */ function payback(address _asset, uint256 _amount) external payable override { //Get cToken address from mapping address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); if (_isETH(_asset)) { // Create a reference to the corresponding cToken contract ICEth cToken = ICEth(cTokenAddr); cToken.repayBorrow{ value: msg.value }(); } else { // Create reference to the ERC20 contract IERC20 erc20token = IERC20(_asset); // Create a reference to the corresponding cToken contract ICErc20 cToken = ICErc20(cTokenAddr); // Check there is enough balance to pay require(erc20token.balanceOf(address(this)) >= _amount, "Not-enough-token"); erc20token.uniApprove(address(cTokenAddr), _amount); cToken.repayBorrow(_amount); } } /** * @dev Returns the current borrowing rate (APR) of a ETH/ERC20_Token, in ray(1e27). * @param _asset: token address to query the current borrowing rate. */ function getBorrowRateFor(address _asset) external view override returns (uint256) { address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); //Block Rate transformed for common mantissa for Fuji in ray (1e27), Note: Compound uses base 1e18 uint256 bRateperBlock = (IGenCToken(cTokenAddr).borrowRatePerBlock()).mul(10**9); // The approximate number of blocks per year that is assumed by the Compound interest rate model uint256 blocksperYear = 2102400; return bRateperBlock.mul(blocksperYear); } /** * @dev Returns the borrow balance of a ETH/ERC20_Token. * @param _asset: token address to query the balance. */ function getBorrowBalance(address _asset) external view override returns (uint256) { address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); return IGenCToken(cTokenAddr).borrowBalanceStored(msg.sender); } /** * @dev Return borrow balance of ETH/ERC20_Token. * This function is the accurate way to get Compound borrow balance. * It costs ~84K gas and is not a view function. * @param _asset token address to query the balance. * @param _who address of the account. */ function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) { address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); return IGenCToken(cTokenAddr).borrowBalanceCurrent(_who); } /** * @dev Returns the deposit balance of a ETH/ERC20_Token. * @param _asset: token address to query the balance. */ function getDepositBalance(address _asset) external view override returns (uint256) { address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset); uint256 cTokenBal = IGenCToken(cTokenAddr).balanceOf(msg.sender); uint256 exRate = IGenCToken(cTokenAddr).exchangeRateStored(); return exRate.mul(cTokenBal).div(1e18); } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.0; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { UniERC20 } from "../Libraries/LibUniERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IProvider } from "./IProvider.sol"; interface ITokenInterface { function approve(address, uint256) external; function transfer(address, uint256) external; function transferFrom( address, address, uint256 ) external; function deposit() external payable; function withdraw(uint256) external; function balanceOf(address) external view returns (uint256); function decimals() external view returns (uint256); } interface IAaveInterface { function deposit( address _asset, uint256 _amount, address _onBehalfOf, uint16 _referralCode ) external; function withdraw( address _asset, uint256 _amount, address _to ) external; function borrow( address _asset, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode, address _onBehalfOf ) external; function repay( address _asset, uint256 _amount, uint256 _rateMode, address _onBehalfOf ) external; function setUserUseReserveAsCollateral(address _asset, bool _useAsCollateral) external; } interface AaveLendingPoolProviderInterface { function getLendingPool() external view returns (address); } interface AaveDataProviderInterface { function getReserveTokensAddresses(address _asset) external view returns ( address aTokenAddress, address stableDebtTokenAddress, address variableDebtTokenAddress ); function getUserReserveData(address _asset, address _user) external view returns ( uint256 currentATokenBalance, uint256 currentStableDebt, uint256 currentVariableDebt, uint256 principalStableDebt, uint256 scaledVariableDebt, uint256 stableBorrowRate, uint256 liquidityRate, uint40 stableRateLastUpdated, bool usageAsCollateralEnabled ); function getReserveData(address _asset) external view returns ( uint256 availableLiquidity, uint256 totalStableDebt, uint256 totalVariableDebt, uint256 liquidityRate, uint256 variableBorrowRate, uint256 stableBorrowRate, uint256 averageStableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex, uint40 lastUpdateTimestamp ); } interface AaveAddressProviderRegistryInterface { function getAddressesProvidersList() external view returns (address[] memory); } contract ProviderAave is IProvider { using SafeMath for uint256; using UniERC20 for IERC20; function _getAaveProvider() internal pure returns (AaveLendingPoolProviderInterface) { return AaveLendingPoolProviderInterface(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5); //mainnet } function _getAaveDataProvider() internal pure returns (AaveDataProviderInterface) { return AaveDataProviderInterface(0x057835Ad21a177dbdd3090bB1CAE03EaCF78Fc6d); //mainnet } function _getWethAddr() internal pure returns (address) { return 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // Mainnet WETH Address } function _getEthAddr() internal pure returns (address) { return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // ETH Address } function _getIsColl( AaveDataProviderInterface _aaveData, address _token, address _user ) internal view returns (bool isCol) { (, , , , , , , , isCol) = _aaveData.getUserReserveData(_token, _user); } function _convertEthToWeth( bool _isEth, ITokenInterface _token, uint256 _amount ) internal { if (_isEth) _token.deposit{ value: _amount }(); } function _convertWethToEth( bool _isEth, ITokenInterface _token, uint256 _amount ) internal { if (_isEth) { _token.approve(address(_token), _amount); _token.withdraw(_amount); } } /** * @dev Return the borrowing rate of ETH/ERC20_Token. * @param _asset to query the borrowing rate. */ function getBorrowRateFor(address _asset) external view override returns (uint256) { AaveDataProviderInterface aaveData = _getAaveDataProvider(); (, , , , uint256 variableBorrowRate, , , , , ) = AaveDataProviderInterface(aaveData).getReserveData( _asset == _getEthAddr() ? _getWethAddr() : _asset ); return variableBorrowRate; } /** * @dev Return borrow balance of ETH/ERC20_Token. * @param _asset token address to query the balance. */ function getBorrowBalance(address _asset) external view override returns (uint256) { AaveDataProviderInterface aaveData = _getAaveDataProvider(); bool isEth = _asset == _getEthAddr(); address _token = isEth ? _getWethAddr() : _asset; (, , uint256 variableDebt, , , , , , ) = aaveData.getUserReserveData(_token, msg.sender); return variableDebt; } /** * @dev Return borrow balance of ETH/ERC20_Token. * @param _asset token address to query the balance. * @param _who address of the account. */ function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) { AaveDataProviderInterface aaveData = _getAaveDataProvider(); bool isEth = _asset == _getEthAddr(); address _token = isEth ? _getWethAddr() : _asset; (, , uint256 variableDebt, , , , , , ) = aaveData.getUserReserveData(_token, _who); return variableDebt; } /** * @dev Return deposit balance of ETH/ERC20_Token. * @param _asset token address to query the balance. */ function getDepositBalance(address _asset) external view override returns (uint256) { AaveDataProviderInterface aaveData = _getAaveDataProvider(); bool isEth = _asset == _getEthAddr(); address _token = isEth ? _getWethAddr() : _asset; (uint256 atokenBal, , , , , , , , ) = aaveData.getUserReserveData(_token, msg.sender); return atokenBal; } /** * @dev Deposit ETH/ERC20_Token. * @param _asset token address to deposit.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount token amount to deposit. */ function deposit(address _asset, uint256 _amount) external payable override { IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool()); AaveDataProviderInterface aaveData = _getAaveDataProvider(); bool isEth = _asset == _getEthAddr(); address _token = isEth ? _getWethAddr() : _asset; ITokenInterface tokenContract = ITokenInterface(_token); if (isEth) { _amount = _amount == uint256(-1) ? address(this).balance : _amount; _convertEthToWeth(isEth, tokenContract, _amount); } else { _amount = _amount == uint256(-1) ? tokenContract.balanceOf(address(this)) : _amount; } tokenContract.approve(address(aave), _amount); aave.deposit(_token, _amount, address(this), 0); if (!_getIsColl(aaveData, _token, address(this))) { aave.setUserUseReserveAsCollateral(_token, true); } } /** * @dev Borrow ETH/ERC20_Token. * @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) * @param _amount token amount to borrow. */ function borrow(address _asset, uint256 _amount) external payable override { IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool()); bool isEth = _asset == _getEthAddr(); address _token = isEth ? _getWethAddr() : _asset; aave.borrow(_token, _amount, 2, 0, address(this)); _convertWethToEth(isEth, ITokenInterface(_token), _amount); } /** * @dev Withdraw ETH/ERC20_Token. * @param _asset token address to withdraw. * @param _amount token amount to withdraw. */ function withdraw(address _asset, uint256 _amount) external payable override { IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool()); bool isEth = _asset == _getEthAddr(); address _token = isEth ? _getWethAddr() : _asset; ITokenInterface tokenContract = ITokenInterface(_token); uint256 initialBal = tokenContract.balanceOf(address(this)); aave.withdraw(_token, _amount, address(this)); uint256 finalBal = tokenContract.balanceOf(address(this)); _amount = finalBal.sub(initialBal); _convertWethToEth(isEth, tokenContract, _amount); } /** * @dev Payback borrowed ETH/ERC20_Token. * @param _asset token address to payback. * @param _amount token amount to payback. */ function payback(address _asset, uint256 _amount) external payable override { IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool()); AaveDataProviderInterface aaveData = _getAaveDataProvider(); bool isEth = _asset == _getEthAddr(); address _token = isEth ? _getWethAddr() : _asset; ITokenInterface tokenContract = ITokenInterface(_token); (, , uint256 variableDebt, , , , , , ) = aaveData.getUserReserveData(_token, address(this)); _amount = _amount == uint256(-1) ? variableDebt : _amount; if (isEth) _convertEthToWeth(isEth, tokenContract, _amount); tokenContract.approve(address(aave), _amount); aave.repay(_token, _amount, 2, address(this)); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { WadRayMath } from "./WadRayMath.sol"; library MathUtils { using SafeMath for uint256; using WadRayMath for uint256; /// @dev Ignoring leap years uint256 internal constant _SECONDS_PER_YEAR = 365 days; /** * @dev Function to calculate the interest accumulated using a linear interest rate formula * @param rate The interest rate, in ray * @param lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate linearly accumulated during the timeDelta, in ray **/ function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) { //solhint-disable-next-line uint256 timeDifference = block.timestamp.sub(uint256(lastUpdateTimestamp)); return (rate.mul(timeDifference) / _SECONDS_PER_YEAR).add(WadRayMath.ray()); } /** * @dev Function to calculate the interest using a compounded interest rate formula * To avoid expensive exponentiation, the calculation is performed using a binomial approximation: * * (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3... * * The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions * The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods * * @param rate The interest rate, in ray * @param lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate compounded during the timeDelta, in ray **/ function calculateCompoundedInterest( uint256 rate, uint40 lastUpdateTimestamp, uint256 currentTimestamp ) internal pure returns (uint256) { //solhint-disable-next-line uint256 exp = currentTimestamp.sub(uint256(lastUpdateTimestamp)); if (exp == 0) { return WadRayMath.ray(); } uint256 expMinusOne = exp - 1; uint256 expMinusTwo = exp > 2 ? exp - 2 : 0; uint256 ratePerSecond = rate / _SECONDS_PER_YEAR; uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond); uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond); uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2; uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6; return WadRayMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm); } /** * @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp * @param rate The interest rate (in ray) * @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated **/ function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp) internal view returns (uint256) { //solhint-disable-next-line return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp); } } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.6.12; import { Errors } from "./Errors.sol"; /** * @title WadRayMath library * @author Aave * @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits) **/ library WadRayMath { uint256 internal constant _WAD = 1e18; uint256 internal constant _HALF_WAD = _WAD / 2; uint256 internal constant _RAY = 1e27; uint256 internal constant _HALF_RAY = _RAY / 2; uint256 internal constant _WAD_RAY_RATIO = 1e9; /** * @return One ray, 1e27 **/ function ray() internal pure returns (uint256) { return _RAY; } /** * @return One wad, 1e18 **/ function wad() internal pure returns (uint256) { return _WAD; } /** * @return Half ray, 1e27/2 **/ function halfRay() internal pure returns (uint256) { return _HALF_RAY; } /** * @return Half ray, 1e18/2 **/ function halfWad() internal pure returns (uint256) { return _HALF_WAD; } /** * @dev Multiplies two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a*b, in wad **/ function wadMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - _HALF_WAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + _HALF_WAD) / _WAD; } /** * @dev Divides two wad, rounding half up to the nearest wad * @param a Wad * @param b Wad * @return The result of a/b, in wad **/ function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / _WAD, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * _WAD + halfB) / b; } /** * @dev Multiplies two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a*b, in ray **/ function rayMul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } require(a <= (type(uint256).max - _HALF_RAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * b + _HALF_RAY) / _RAY; } /** * @dev Divides two ray, rounding half up to the nearest ray * @param a Ray * @param b Ray * @return The result of a/b, in ray **/ function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, Errors.MATH_DIVISION_BY_ZERO); uint256 halfB = b / 2; require(a <= (type(uint256).max - halfB) / _RAY, Errors.MATH_MULTIPLICATION_OVERFLOW); return (a * _RAY + halfB) / b; } /** * @dev Casts ray down to wad * @param a Ray * @return a casted to wad, rounded half up to the nearest wad **/ function rayToWad(uint256 a) internal pure returns (uint256) { uint256 halfRatio = _WAD_RAY_RATIO / 2; uint256 result = halfRatio + a; require(result >= halfRatio, Errors.MATH_ADDITION_OVERFLOW); return result / _WAD_RAY_RATIO; } /** * @dev Converts wad up to ray * @param a Wad * @return a converted in ray **/ function wadToRay(uint256 a) internal pure returns (uint256) { uint256 result = a * _WAD_RAY_RATIO; require(result / _WAD_RAY_RATIO == a, Errors.MATH_MULTIPLICATION_OVERFLOW); return result; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; pragma experimental ABIEncoderV2; import { IFujiERC1155 } from "./IFujiERC1155.sol"; import { FujiBaseERC1155 } from "./FujiBaseERC1155.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { WadRayMath } from "../Libraries/WadRayMath.sol"; import { MathUtils } from "../Libraries/MathUtils.sol"; import { Errors } from "../Libraries/Errors.sol"; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; contract F1155Manager is Ownable { using Address for address; // Controls for Mint-Burn Operations mapping(address => bool) public addrPermit; modifier onlyPermit() { require(addrPermit[_msgSender()] || msg.sender == owner(), Errors.VL_NOT_AUTHORIZED); _; } function setPermit(address _address, bool _permit) public onlyOwner { require((_address).isContract(), Errors.VL_NOT_A_CONTRACT); addrPermit[_address] = _permit; } } contract FujiERC1155 is IFujiERC1155, FujiBaseERC1155, F1155Manager { using WadRayMath for uint256; //FujiERC1155 Asset ID Mapping //AssetType => asset reference address => ERC1155 Asset ID mapping(AssetType => mapping(address => uint256)) public assetIDs; //Control mapping that returns the AssetType of an AssetID mapping(uint256 => AssetType) public assetIDtype; uint64 public override qtyOfManagedAssets; //Asset ID Liquidity Index mapping //AssetId => Liquidity index for asset ID mapping(uint256 => uint256) public indexes; // Optimizer Fee expressed in Ray, where 1 ray = 100% APR //uint256 public optimizerFee; //uint256 public lastUpdateTimestamp; //uint256 public fujiIndex; /// @dev Ignoring leap years //uint256 internal constant SECONDS_PER_YEAR = 365 days; constructor() public { //fujiIndex = WadRayMath.ray(); //optimizerFee = 1e24; } /** * @dev Updates Index of AssetID * @param _assetID: ERC1155 ID of the asset which state will be updated. * @param newBalance: Amount **/ function updateState(uint256 _assetID, uint256 newBalance) external override onlyPermit { uint256 total = totalSupply(_assetID); if (newBalance > 0 && total > 0 && newBalance > total) { uint256 diff = newBalance.sub(total); uint256 amountToIndexRatio = (diff.wadToRay()).rayDiv(total.wadToRay()); uint256 result = amountToIndexRatio.add(WadRayMath.ray()); result = result.rayMul(indexes[_assetID]); require(result <= type(uint128).max, Errors.VL_INDEX_OVERFLOW); indexes[_assetID] = uint128(result); // TODO: calculate interest rate for a fujiOptimizer Fee. /* if(lastUpdateTimestamp==0){ lastUpdateTimestamp = block.timestamp; } uint256 accrued = _calculateCompoundedInterest( optimizerFee, lastUpdateTimestamp, block.timestamp ).rayMul(fujiIndex); fujiIndex = accrued; lastUpdateTimestamp = block.timestamp; */ } } /** * @dev Returns the total supply of Asset_ID with accrued interest. * @param _assetID: ERC1155 ID of the asset which state will be updated. **/ function totalSupply(uint256 _assetID) public view virtual override returns (uint256) { // TODO: include interest accrued by Fuji OptimizerFee return super.totalSupply(_assetID).rayMul(indexes[_assetID]); } /** * @dev Returns the scaled total supply of the token ID. Represents sum(token ID Principal /index) * @param _assetID: ERC1155 ID of the asset which state will be updated. **/ function scaledTotalSupply(uint256 _assetID) public view virtual returns (uint256) { return super.totalSupply(_assetID); } /** * @dev Returns the principal + accrued interest balance of the user * @param _account: address of the User * @param _assetID: ERC1155 ID of the asset which state will be updated. **/ function balanceOf(address _account, uint256 _assetID) public view override(FujiBaseERC1155, IFujiERC1155) returns (uint256) { uint256 scaledBalance = super.balanceOf(_account, _assetID); if (scaledBalance == 0) { return 0; } // TODO: include interest accrued by Fuji OptimizerFee return scaledBalance.rayMul(indexes[_assetID]); } /** * @dev Returns the balance of User, split into owed amounts to BaseProtocol and FujiProtocol * @param _account: address of the User * @param _assetID: ERC1155 ID of the asset which state will be updated. **/ /* function splitBalanceOf( address _account, uint256 _assetID ) public view override returns (uint256,uint256) { uint256 scaledBalance = super.balanceOf(_account, _assetID); if (scaledBalance == 0) { return (0,0); } else { TO DO COMPUTATION return (baseprotocol, fuji); } } */ /** * @dev Returns Scaled Balance of the user (e.g. balance/index) * @param _account: address of the User * @param _assetID: ERC1155 ID of the asset which state will be updated. **/ function scaledBalanceOf(address _account, uint256 _assetID) public view virtual returns (uint256) { return super.balanceOf(_account, _assetID); } /** * @dev Returns the sum of balance of the user for an AssetType. * This function is used for when AssetType have units of account of the same value (e.g stablecoins) * @param _account: address of the User * @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset **/ /* function balanceOfBatchType(address _account, AssetType _type) external view override returns (uint256 total) { uint256[] memory IDs = engagedIDsOf(_account, _type); for(uint i; i < IDs.length; i++ ){ total = total.add(balanceOf(_account, IDs[i])); } } */ /** * @dev Mints tokens for Collateral and Debt receipts for the Fuji Protocol * Emits a {TransferSingle} event. * Requirements: * - `_account` cannot be the zero address. * - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. * - `_amount` should be in WAD */ function mint( address _account, uint256 _id, uint256 _amount, bytes memory _data ) external override onlyPermit { require(_account != address(0), Errors.VL_ZERO_ADDR_1155); address operator = _msgSender(); uint256 accountBalance = _balances[_id][_account]; uint256 assetTotalBalance = _totalSupply[_id]; uint256 amountScaled = _amount.rayDiv(indexes[_id]); require(amountScaled != 0, Errors.VL_INVALID_MINT_AMOUNT); _balances[_id][_account] = accountBalance.add(amountScaled); _totalSupply[_id] = assetTotalBalance.add(amountScaled); emit TransferSingle(operator, address(0), _account, _id, _amount); _doSafeTransferAcceptanceCheck(operator, address(0), _account, _id, _amount, _data); } /** * @dev [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 ) external onlyPermit { require(_to != address(0), Errors.VL_ZERO_ADDR_1155); require(_ids.length == _amounts.length, Errors.VL_INPUT_ERROR); address operator = _msgSender(); uint256 accountBalance; uint256 assetTotalBalance; uint256 amountScaled; for (uint256 i = 0; i < _ids.length; i++) { accountBalance = _balances[_ids[i]][_to]; assetTotalBalance = _totalSupply[_ids[i]]; amountScaled = _amounts[i].rayDiv(indexes[_ids[i]]); require(amountScaled != 0, Errors.VL_INVALID_MINT_AMOUNT); _balances[_ids[i]][_to] = accountBalance.add(amountScaled); _totalSupply[_ids[i]] = assetTotalBalance.add(amountScaled); } emit TransferBatch(operator, address(0), _to, _ids, _amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), _to, _ids, _amounts, _data); } /** * @dev Destroys `_amount` receipt tokens of token type `_id` from `account` for the Fuji Protocol * Requirements: * - `account` cannot be the zero address. * - `account` must have at least `_amount` tokens of token type `_id`. * - `_amount` should be in WAD */ function burn( address _account, uint256 _id, uint256 _amount ) external override onlyPermit { require(_account != address(0), Errors.VL_ZERO_ADDR_1155); address operator = _msgSender(); uint256 accountBalance = _balances[_id][_account]; uint256 assetTotalBalance = _totalSupply[_id]; uint256 amountScaled = _amount.rayDiv(indexes[_id]); require(amountScaled != 0 && accountBalance >= amountScaled, Errors.VL_INVALID_BURN_AMOUNT); _balances[_id][_account] = accountBalance.sub(amountScaled); _totalSupply[_id] = assetTotalBalance.sub(amountScaled); emit TransferSingle(operator, _account, address(0), _id, _amount); } /** * @dev [Batched] version of {burn}. * Requirements: * - `_ids` and `_amounts` must have the same length. */ function burnBatch( address _account, uint256[] memory _ids, uint256[] memory _amounts ) external onlyPermit { require(_account != address(0), Errors.VL_ZERO_ADDR_1155); require(_ids.length == _amounts.length, Errors.VL_INPUT_ERROR); address operator = _msgSender(); uint256 accountBalance; uint256 assetTotalBalance; uint256 amountScaled; for (uint256 i = 0; i < _ids.length; i++) { uint256 amount = _amounts[i]; accountBalance = _balances[_ids[i]][_account]; assetTotalBalance = _totalSupply[_ids[i]]; amountScaled = _amounts[i].rayDiv(indexes[_ids[i]]); require(amountScaled != 0 && accountBalance >= amountScaled, Errors.VL_INVALID_BURN_AMOUNT); _balances[_ids[i]][_account] = accountBalance.sub(amount); _totalSupply[_ids[i]] = assetTotalBalance.sub(amount); } emit TransferBatch(operator, _account, address(0), _ids, _amounts); } //Getter Functions /** * @dev Getter Function for the Asset ID locally managed * @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset * @param _addr: Reference Address of the Asset */ function getAssetID(AssetType _type, address _addr) external view override returns (uint256 id) { id = assetIDs[_type][_addr]; require(id <= qtyOfManagedAssets, Errors.VL_INVALID_ASSETID_1155); } //Setter Functions /** * @dev Sets the FujiProtocol Fee to be charged * @param _fee; Fee in Ray(1e27) to charge users for optimizerFee (1 ray = 100% APR) */ /* function setoptimizerFee(uint256 _fee) public onlyOwner { require(_fee >= WadRayMath.ray(), Errors.VL_OPTIMIZER_FEE_SMALL); optimizerFee = _fee; } */ /** * @dev Sets a new URI for all token types, by relying on the token type ID */ function setURI(string memory _newUri) public onlyOwner { _uri = _newUri; } /** * @dev Adds and initializes liquidity index of a new asset in FujiERC1155 * @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset * @param _addr: Reference Address of the Asset */ function addInitializeAsset(AssetType _type, address _addr) external override onlyPermit returns (uint64) { require(assetIDs[_type][_addr] == 0, Errors.VL_ASSET_EXISTS); assetIDs[_type][_addr] = qtyOfManagedAssets; assetIDtype[qtyOfManagedAssets] = _type; //Initialize the liquidity Index indexes[qtyOfManagedAssets] = WadRayMath.ray(); qtyOfManagedAssets++; return qtyOfManagedAssets - 1; } /** * @dev Function to calculate the interest using a compounded interest rate formula * To avoid expensive exponentiation, the calculation is performed using a binomial approximation: * * (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3... * * The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions * The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods * * @param _rate The interest rate, in ray * @param _lastUpdateTimestamp The timestamp of the last update of the interest * @return The interest rate compounded during the timeDelta, in ray **/ /* function _calculateCompoundedInterest( uint256 _rate, uint256 _lastUpdateTimestamp, uint256 currentTimestamp ) internal pure returns (uint256) { //solium-disable-next-line uint256 exp = currentTimestamp.sub(uint256(_lastUpdateTimestamp)); if (exp == 0) { return WadRayMath.ray(); } uint256 expMinusOne = exp - 1; uint256 expMinusTwo = exp > 2 ? exp - 2 : 0; uint256 ratePerSecond = _rate / SECONDS_PER_YEAR; uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond); uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond); uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2; uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6; return WadRayMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm); } */ } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; pragma experimental ABIEncoderV2; import { IERC1155 } from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import { IERC1155Receiver } from "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol"; import { IERC1155MetadataURI } from "@openzeppelin/contracts/token/ERC1155/IERC1155MetadataURI.sol"; import { ERC165 } from "@openzeppelin/contracts/introspection/ERC165.sol"; import { IERC165 } from "@openzeppelin/contracts/introspection/IERC165.sol"; import { Address } from "@openzeppelin/contracts/utils/Address.sol"; import { Context } from "@openzeppelin/contracts/utils/Context.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { Errors } from "../Libraries/Errors.sol"; /** * * @dev Implementation of the Base ERC1155 multi-token standard functions * for Fuji Protocol control of User collaterals and borrow debt positions. * Originally based on Openzeppelin * */ contract FujiBaseERC1155 is IERC1155, ERC165, Context { using Address for address; using SafeMath for uint256; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) internal _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) internal _operatorApprovals; // Mapping from token ID to totalSupply mapping(uint256 => uint256) internal _totalSupply; //Fuji ERC1155 Transfer Control bool public transfersActive; modifier isTransferActive() { require(transfersActive, Errors.VL_NOT_AUTHORIZED); _; } //URI for all token types by relying on ID substitution //https://token.fujiDao.org/{id}.json string internal _uri; /** * @return The total supply of a token id **/ function totalSupply(uint256 id) public view virtual returns (uint256) { return _totalSupply[id]; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155).interfaceId || interfaceId == type(IERC1155MetadataURI).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual 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), Errors.VL_ZERO_ADDR_1155); 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 override returns (uint256[] memory) { require(accounts.length == ids.length, Errors.VL_INPUT_ERROR); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(_msgSender() != operator, Errors.VL_INPUT_ERROR); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override isTransferActive { require(to != address(0), Errors.VL_ZERO_ADDR_1155); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), Errors.VL_MISSING_ERC1155_APPROVAL ); address operator = _msgSender(); _beforeTokenTransfer( operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data ); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, Errors.VL_NO_ERC1155_BALANCE); _balances[id][from] = fromBalance.sub(amount); _balances[id][to] = uint256(_balances[id][to]).add(amount); emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, 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 isTransferActive { require(ids.length == amounts.length, Errors.VL_INPUT_ERROR); require(to != address(0), Errors.VL_ZERO_ADDR_1155); require( from == _msgSender() || isApprovedForAll(from, _msgSender()), Errors.VL_MISSING_ERC1155_APPROVAL ); 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, Errors.VL_NO_ERC1155_BALANCE); _balances[id][from] = fromBalance.sub(amount); _balances[id][to] = uint256(_balances[id][to]).add(amount); } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) internal { if (to.isContract()) { try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns ( bytes4 response ) { if (response != IERC1155Receiver(to).onERC1155Received.selector) { revert(Errors.VL_RECEIVER_REJECT_1155); } } catch Error(string memory reason) { revert(reason); } catch { revert(Errors.VL_RECEIVER_CONTRACT_NON_1155); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal { if (to.isContract()) { try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) { revert(Errors.VL_RECEIVER_REJECT_1155); } } catch Error(string memory reason) { revert(reason); } catch { revert(Errors.VL_RECEIVER_CONTRACT_NON_1155); } } } /** * @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 _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../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 pragma solidity >=0.6.0 <0.8.0; import "../../introspection/IERC165.sol"; /** * _Available since v3.1._ */ interface IERC1155Receiver is IERC165 { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @param from The address which previously owned the token @param id The ID of the token being transferred @param value The amount of tokens being transferred @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns(bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns(bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <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 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 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 { IVault } from "./Vaults/IVault.sol"; import { IFujiAdmin } from "./IFujiAdmin.sol"; import { IFujiERC1155 } from "./FujiERC1155/IFujiERC1155.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { Flasher } from "./Flashloans/Flasher.sol"; import { FlashLoan } from "./Flashloans/LibFlashLoan.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { Errors } from "./Libraries/Errors.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { UniERC20 } from "./Libraries/LibUniERC20.sol"; import { IUniswapV2Router02 } from "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; interface IVaultExt is IVault { //Asset Struct struct VaultAssets { address collateralAsset; address borrowAsset; uint64 collateralID; uint64 borrowID; } function vAssets() external view returns (VaultAssets memory); } contract Fliquidator is Ownable, ReentrancyGuard { using SafeMath for uint256; using UniERC20 for IERC20; struct Factor { uint64 a; uint64 b; } // Flash Close Fee Factor Factor public flashCloseF; IFujiAdmin private _fujiAdmin; IUniswapV2Router02 public swapper; // Log Liquidation event Liquidate( address indexed userAddr, address liquidator, address indexed asset, uint256 amount ); // Log FlashClose event FlashClose(address indexed userAddr, address indexed asset, uint256 amount); // Log Liquidation event FlashLiquidate(address userAddr, address liquidator, address indexed asset, uint256 amount); modifier isAuthorized() { require(msg.sender == owner(), Errors.VL_NOT_AUTHORIZED); _; } modifier onlyFlash() { require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED); _; } constructor() public { // 1.013 flashCloseF.a = 1013; flashCloseF.b = 1000; } receive() external payable {} // FLiquidator Core Functions /** * @dev Liquidate an undercollaterized debt and get bonus (bonusL in Vault) * @param _userAddr: Address of user whose position is liquidatable * @param _vault: Address of the vault in where liquidation will occur */ function liquidate(address _userAddr, address _vault) external { // Update Balances at FujiERC1155 IVault(_vault).updateF1155Balances(); // Create Instance of FujiERC1155 IFujiERC1155 f1155 = IFujiERC1155(IVault(_vault).fujiERC1155()); // Struct Instance to get Vault Asset IDs in f1155 IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets(); // Get user Collateral and Debt Balances uint256 userCollateral = f1155.balanceOf(_userAddr, vAssets.collateralID); uint256 userDebtBalance = f1155.balanceOf(_userAddr, vAssets.borrowID); // Compute Amount of Minimum Collateral Required including factors uint256 neededCollateral = IVault(_vault).getNeededCollateralFor(userDebtBalance, true); // Check if User is liquidatable require(userCollateral < neededCollateral, Errors.VL_USER_NOT_LIQUIDATABLE); // Check Liquidator Allowance require( IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= userDebtBalance, Errors.VL_MISSING_ERC20_ALLOWANCE ); // Transfer borrowAsset funds from the Liquidator to Here IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), userDebtBalance); // Transfer Amount to Vault IERC20(vAssets.borrowAsset).transfer(_vault, userDebtBalance); // TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt // Repay BaseProtocol debt IVault(_vault).payback(int256(userDebtBalance)); //TODO: Transfer corresponding Debt Amount to Fuji Treasury // Burn Debt f1155 tokens f1155.burn(_userAddr, vAssets.borrowID, userDebtBalance); // Compute the Liquidator Bonus bonusL uint256 bonus = IVault(_vault).getLiquidationBonusFor(userDebtBalance, false); // Compute how much collateral needs to be swapt uint256 collateralInPlay = _getCollateralInPlay(vAssets.borrowAsset, userDebtBalance.add(bonus)); // Burn Collateral f1155 tokens f1155.burn(_userAddr, vAssets.collateralID, collateralInPlay); // Withdraw collateral IVault(_vault).withdraw(int256(collateralInPlay)); // Swap Collateral _swap(vAssets.borrowAsset, userDebtBalance.add(bonus), collateralInPlay); // Transfer to Liquidator the debtBalance + bonus IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, userDebtBalance.add(bonus)); emit Liquidate(_userAddr, msg.sender, vAssets.borrowAsset, userDebtBalance); } /** * @dev Initiates a flashloan used to repay partially or fully the debt position of msg.sender * @param _amount: Pass -1 to fully close debt position, otherwise Amount to be repaid with a flashloan * @param _vault: The vault address where the debt position exist. * @param _flashnum: integer identifier of flashloan provider */ function flashClose( int256 _amount, address _vault, uint8 _flashnum ) external nonReentrant { Flasher flasher = Flasher(payable(_fujiAdmin.getFlasher())); // Update Balances at FujiERC1155 IVault(_vault).updateF1155Balances(); // Create Instance of FujiERC1155 IFujiERC1155 f1155 = IFujiERC1155(IVault(_vault).fujiERC1155()); // Struct Instance to get Vault Asset IDs in f1155 IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets(); // Get user Balances uint256 userCollateral = f1155.balanceOf(msg.sender, vAssets.collateralID); uint256 userDebtBalance = f1155.balanceOf(msg.sender, vAssets.borrowID); // Check Debt is > zero require(userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK); uint256 amount = _amount < 0 ? userDebtBalance : uint256(_amount); uint256 neededCollateral = IVault(_vault).getNeededCollateralFor(amount, false); require(userCollateral >= neededCollateral, Errors.VL_UNDERCOLLATERIZED_ERROR); FlashLoan.Info memory info = FlashLoan.Info({ callType: FlashLoan.CallType.Close, asset: vAssets.borrowAsset, amount: amount, vault: _vault, newProvider: address(0), user: msg.sender, userliquidator: address(0), fliquidator: address(this) }); flasher.initiateFlashloan(info, _flashnum); } /** * @dev Close user's debt position by using a flashloan * @param _userAddr: user addr to be liquidated * @param _vault: Vault address * @param _amount: amount received by Flashloan * @param _flashloanFee: amount extra charged by flashloan provider * Emits a {FlashClose} event. */ function executeFlashClose( address payable _userAddr, address _vault, uint256 _amount, uint256 _flashloanFee ) external onlyFlash { // Create Instance of FujiERC1155 IFujiERC1155 f1155 = IFujiERC1155(IVault(_vault).fujiERC1155()); // Struct Instance to get Vault Asset IDs in f1155 IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets(); // Get user Collateral and Debt Balances uint256 userCollateral = f1155.balanceOf(_userAddr, vAssets.collateralID); uint256 userDebtBalance = f1155.balanceOf(_userAddr, vAssets.borrowID); // Get user Collateral + Flash Close Fee to close posisition, for _amount passed uint256 userCollateralInPlay = IVault(_vault) .getNeededCollateralFor(_amount.add(_flashloanFee), false) .mul(flashCloseF.a) .div(flashCloseF.b); // TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt // Repay BaseProtocol debt IVault(_vault).payback(int256(_amount)); //TODO: Transfer corresponding Debt Amount to Fuji Treasury // Full close if (_amount == userDebtBalance) { f1155.burn(_userAddr, vAssets.collateralID, userCollateral); // Withdraw Full collateral IVault(_vault).withdraw(int256(userCollateral)); // Send unUsed Collateral to User _userAddr.transfer(userCollateral.sub(userCollateralInPlay)); } else { f1155.burn(_userAddr, vAssets.collateralID, userCollateralInPlay); // Withdraw Collateral in play Only IVault(_vault).withdraw(int256(userCollateralInPlay)); } // Swap Collateral for underlying to repay Flashloan uint256 remaining = _swap(vAssets.borrowAsset, _amount.add(_flashloanFee), userCollateralInPlay); // Send FlashClose Fee to FujiTreasury IERC20(vAssets.collateralAsset).uniTransfer(_fujiAdmin.getTreasury(), remaining); // Send flasher the underlying to repay Flashloan IERC20(vAssets.borrowAsset).uniTransfer( payable(_fujiAdmin.getFlasher()), _amount.add(_flashloanFee) ); // Burn Debt f1155 tokens f1155.burn(_userAddr, vAssets.borrowID, _amount); emit FlashClose(_userAddr, vAssets.borrowAsset, userDebtBalance); } /** * @dev Initiates a flashloan to liquidate an undercollaterized debt position, * gets bonus (bonusFlashL in Vault) * @param _userAddr: Address of user whose position is liquidatable * @param _vault: The vault address where the debt position exist. * @param _flashnum: integer identifier of flashloan provider */ function flashLiquidate( address _userAddr, address _vault, uint8 _flashnum ) external nonReentrant { // Update Balances at FujiERC1155 IVault(_vault).updateF1155Balances(); // Create Instance of FujiERC1155 IFujiERC1155 f1155 = IFujiERC1155(IVault(_vault).fujiERC1155()); // Struct Instance to get Vault Asset IDs in f1155 IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets(); // Get user Collateral and Debt Balances uint256 userCollateral = f1155.balanceOf(_userAddr, vAssets.collateralID); uint256 userDebtBalance = f1155.balanceOf(_userAddr, vAssets.borrowID); // Compute Amount of Minimum Collateral Required including factors uint256 neededCollateral = IVault(_vault).getNeededCollateralFor(userDebtBalance, true); // Check if User is liquidatable require(userCollateral < neededCollateral, Errors.VL_USER_NOT_LIQUIDATABLE); Flasher flasher = Flasher(payable(_fujiAdmin.getFlasher())); FlashLoan.Info memory info = FlashLoan.Info({ callType: FlashLoan.CallType.Liquidate, asset: vAssets.borrowAsset, amount: userDebtBalance, vault: _vault, newProvider: address(0), user: _userAddr, userliquidator: msg.sender, fliquidator: address(this) }); flasher.initiateFlashloan(info, _flashnum); } /** * @dev Liquidate a debt position by using a flashloan * @param _userAddr: user addr to be liquidated * @param _liquidatorAddr: liquidator address * @param _vault: Vault address * @param _amount: amount of debt to be repaid * @param _flashloanFee: amount extra charged by flashloan provider * Emits a {FlashLiquidate} event. */ function executeFlashLiquidation( address _userAddr, address _liquidatorAddr, address _vault, uint256 _amount, uint256 _flashloanFee ) external onlyFlash { // Create Instance of FujiERC1155 IFujiERC1155 f1155 = IFujiERC1155(IVault(_vault).fujiERC1155()); // Struct Instance to get Vault Asset IDs in f1155 IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets(); // Get user Collateral and Debt Balances uint256 userCollateral = f1155.balanceOf(_userAddr, vAssets.collateralID); uint256 userDebtBalance = f1155.balanceOf(_userAddr, vAssets.borrowID); // TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt //TODO: Transfer corresponding Debt Amount to Fuji Treasury // Repay BaseProtocol debt to release collateral IVault(_vault).payback(int256(_amount)); // Compute the Liquidator Bonus bonusFlashL uint256 bonus = IVault(_vault).getLiquidationBonusFor(userDebtBalance, true); // Compute how much collateral needs to be swapt uint256 collateralInPlay = _getCollateralInPlay(vAssets.borrowAsset, userDebtBalance.add(_flashloanFee).add(bonus)); // Burn Collateral f1155 tokens f1155.burn(_userAddr, vAssets.collateralID, collateralInPlay); // Withdraw collateral IVault(_vault).withdraw(int256(userCollateral)); _swap(vAssets.borrowAsset, _amount.add(_flashloanFee).add(bonus), collateralInPlay); // Send flasher the underlying to repay Flashloan IERC20(vAssets.borrowAsset).uniTransfer( payable(_fujiAdmin.getFlasher()), _amount.add(_flashloanFee) ); // Transfer Bonus bonusFlashL to liquidator IERC20(vAssets.borrowAsset).uniTransfer(payable(_liquidatorAddr), bonus); // Burn Debt f1155 tokens f1155.burn(_userAddr, vAssets.borrowID, userDebtBalance); emit FlashLiquidate(_userAddr, _liquidatorAddr, vAssets.borrowAsset, userDebtBalance); } /** * @dev Swap an amount of underlying * @param _borrowAsset: Address of vault borrowAsset * @param _amountToReceive: amount of underlying to receive * @param _collateralAmount: collateral Amount sent for swap */ function _swap( address _borrowAsset, uint256 _amountToReceive, uint256 _collateralAmount ) internal returns (uint256) { // Swap Collateral Asset to Borrow Asset address[] memory path = new address[](2); path[0] = swapper.WETH(); path[1] = _borrowAsset; uint256[] memory swapperAmounts = swapper.swapETHForExactTokens{ value: _collateralAmount }( _amountToReceive, path, address(this), // solhint-disable-next-line block.timestamp ); return _collateralAmount.sub(swapperAmounts[0]); } /** * @dev Get exact amount of collateral to be swapt * @param _borrowAsset: Address of vault borrowAsset * @param _amountToReceive: amount of underlying to receive */ function _getCollateralInPlay(address _borrowAsset, uint256 _amountToReceive) internal view returns (uint256) { address[] memory path = new address[](2); path[0] = swapper.WETH(); path[1] = _borrowAsset; uint256[] memory amounts = swapper.getAmountsIn(_amountToReceive, path); return amounts[0]; } // Administrative functions /** * @dev Set Factors "a" and "b" for a Struct Factor flashcloseF * For flashCloseF; should be > 1, a/b * @param _newFactorA: A number * @param _newFactorB: A number */ function setFlashCloseFee(uint64 _newFactorA, uint64 _newFactorB) external isAuthorized { flashCloseF.a = _newFactorA; flashCloseF.b = _newFactorB; } /** * @dev Sets the fujiAdmin Address * @param _newFujiAdmin: FujiAdmin Contract Address */ function setFujiAdmin(address _newFujiAdmin) external isAuthorized { _fujiAdmin = IFujiAdmin(_newFujiAdmin); } /** * @dev Changes the Swapper contract address * @param _newSwapper: address of new swapper contract */ function setSwapper(address _newSwapper) external isAuthorized { swapper = IUniswapV2Router02(_newSwapper); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12 <0.8.0; pragma experimental ABIEncoderV2; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { UniERC20 } from "../Libraries/LibUniERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IFujiAdmin } from "../IFujiAdmin.sol"; import { Errors } from '../Libraries/Errors.sol'; import { ILendingPool, IFlashLoanReceiver } from "./AaveFlashLoans.sol"; import { Actions, Account, DyDxFlashloanBase, ICallee, ISoloMargin } from "./DyDxFlashLoans.sol"; import { FlashLoan } from "./LibFlashLoan.sol"; import { IVault } from "../Vaults/IVault.sol"; interface IFliquidator { function executeFlashClose(address _userAddr, address vault, uint256 _Amount, uint256 flashloanfee) external; function executeFlashLiquidation(address _userAddr,address _liquidatorAddr, address vault, uint256 _debtAmount, uint256 flashloanfee) external; } contract Flasher is DyDxFlashloanBase, IFlashLoanReceiver, ICallee, Ownable { using SafeMath for uint256; using UniERC20 for IERC20; IFujiAdmin private _fujiAdmin; address public aave_lending_pool; address public dydx_solo_margin; receive() external payable {} constructor() public { aave_lending_pool = 0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9; dydx_solo_margin = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e; } modifier isAuthorized() { require( msg.sender == _fujiAdmin.getController() || msg.sender == _fujiAdmin.getFliquidator() || msg.sender == owner(), Errors.VL_NOT_AUTHORIZED ); _; } modifier isAuthorizedExternal() { require( msg.sender == dydx_solo_margin || msg.sender == aave_lending_pool, Errors.VL_NOT_AUTHORIZED ); _; } /** * @dev Sets the fujiAdmin Address * @param _newFujiAdmin: FujiAdmin Contract Address */ function setFujiAdmin(address _newFujiAdmin) public onlyOwner { _fujiAdmin = IFujiAdmin(_newFujiAdmin); } /** * @dev Routing Function for Flashloan Provider * @param info: struct information for flashLoan * @param _flashnum: integer identifier of flashloan provider */ function initiateFlashloan(FlashLoan.Info memory info, uint8 _flashnum) public isAuthorized { if(_flashnum==0) { initiateAaveFlashLoan(info); } else if(_flashnum==1) { initiateDyDxFlashLoan(info); } } // ===================== DyDx FlashLoan =================================== /** * @dev Initiates a DyDx flashloan. * @param info: data to be passed between functions executing flashloan logic */ function initiateDyDxFlashLoan( FlashLoan.Info memory info ) internal { ISoloMargin solo = ISoloMargin(dydx_solo_margin); // Get marketId from token address uint256 marketId = _getMarketIdFromTokenAddress(solo, info.asset); // 1. Withdraw $ // 2. Call callFunction(...) // 3. Deposit back $ Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, info.amount); // Encode FlashLoan.Info for callFunction operations[1] = _getCallAction(abi.encode(info)); // add fee of 2 wei operations[2] = _getDepositAction(marketId, info.amount.add(2)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(address(this)); solo.operate(accountInfos, operations); } /** * @dev Executes DyDx Flashloan, this operation is required * and called by Solo when sending loaned amount * @param sender: Not used * @param account: Not used */ function callFunction( address sender, Account.Info memory account, bytes memory data ) external override isAuthorizedExternal { sender; account; FlashLoan.Info memory info = abi.decode(data, (FlashLoan.Info)); //Estimate flashloan payback + premium fee of 2 wei, uint amountOwing = info.amount.add(2); // Transfer to Vault the flashloan Amount IERC20(info.asset).uniTransfer(payable(info.vault), info.amount); if (info.callType == FlashLoan.CallType.Switch) { IVault(info.vault) .executeSwitch(info.newProvider, info.amount, 2); } else if (info.callType == FlashLoan.CallType.Close) { IFliquidator(info.fliquidator) .executeFlashClose(info.user, info.vault, info.amount, 2); } else { IFliquidator(info.fliquidator) .executeFlashLiquidation(info.user, info.userliquidator, info.vault, info.amount, 2); } //Approve DYDXSolo to spend to repay flashloan IERC20(info.asset).approve(dydx_solo_margin, amountOwing); } // ===================== Aave FlashLoan =================================== /** * @dev Initiates an Aave flashloan. * @param info: data to be passed between functions executing flashloan logic */ function initiateAaveFlashLoan( FlashLoan.Info memory info ) internal { //Initialize Instance of Aave Lending Pool ILendingPool aaveLp = ILendingPool(aave_lending_pool); //Passing arguments to construct Aave flashloan -limited to 1 asset type for now. address receiverAddress = address(this); address[] memory assets = new address[](1); assets[0] = address(info.asset); uint256[] memory amounts = new uint256[](1); amounts[0] = info.amount; // 0 = no debt, 1 = stable, 2 = variable uint256[] memory modes = new uint256[](1); modes[0] = 0; address onBehalfOf = address(this); bytes memory params = abi.encode(info); uint16 referralCode = 0; //Aave Flashloan initiated. aaveLp.flashLoan( receiverAddress, assets, amounts, modes, onBehalfOf, params, referralCode ); } /** * @dev Executes Aave Flashloan, this operation is required * and called by Aaveflashloan when sending loaned amount */ function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external override isAuthorizedExternal returns (bool) { initiator; FlashLoan.Info memory info = abi.decode(params, (FlashLoan.Info)); //Estimate flashloan payback + premium fee, uint amountOwing = amounts[0].add(premiums[0]); // Transfer to the vault ERC20 IERC20(assets[0]).uniTransfer(payable(info.vault), amounts[0]); if (info.callType == FlashLoan.CallType.Switch) { IVault(info.vault) .executeSwitch(info.newProvider, amounts[0], premiums[0]); } else if (info.callType == FlashLoan.CallType.Close) { IFliquidator(info.fliquidator) .executeFlashClose(info.user, info.vault, amounts[0], premiums[0]); } else { IFliquidator(info.fliquidator) .executeFlashLiquidation(info.user, info.userliquidator, info.vault, amounts[0],premiums[0]); } //Approve aaveLP to spend to repay flashloan IERC20(assets[0]).uniApprove(payable(aave_lending_pool), amountOwing); return true; } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.5; library FlashLoan { /** * @dev Used to determine which vault's function to call post-flashloan: * - Switch for executeSwitch(...) * - Close for executeFlashClose(...) * - Liquidate for executeFlashLiquidation(...) */ enum CallType { Switch, Close, Liquidate } /** * @dev Struct of params to be passed between functions executing flashloan logic * @param asset: Address of asset to be borrowed with flashloan * @param amount: Amount of asset to be borrowed with flashloan * @param vault: Vault's address on which the flashloan logic to be executed * @param newProvider: New provider's address. Used when callType is Switch * @param user: User's address. Used when callType is Close or Liquidate * @param userliquidator: The user's address who is performing liquidation. Used when callType is Liquidate * @param fliquidator: Fujis Liquidator's address. */ struct Info { CallType callType; address asset; uint256 amount; address vault; address newProvider; address user; address userliquidator; address fliquidator; } } 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.4.25 <0.7.5; interface IFlashLoanReceiver { function executeOperation( address[] calldata assets, uint256[] calldata amounts, uint256[] calldata premiums, address initiator, bytes calldata params ) external returns (bool); } interface ILendingPool { function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.4.25 <0.7.5; pragma experimental ABIEncoderV2; library Account { enum Status {Normal, Liquid, Vapor} struct Info { address owner; // The address that owns the account uint256 number; // A nonce that allows a single address to control many accounts } } library Actions { enum ActionType { Deposit, // supply tokens Withdraw, // borrow tokens Transfer, // transfer balance between accounts Buy, // buy an amount of some token (publicly) Sell, // sell an amount of some token (publicly) Trade, // trade tokens against another account Liquidate, // liquidate an undercollateralized or expiring account Vaporize, // use excess tokens to zero-out a completely negative account Call // send arbitrary data to an address } struct ActionArgs { ActionType actionType; uint256 accountId; Types.AssetAmount amount; uint256 primaryMarketId; uint256 secondaryMarketId; address otherAddress; uint256 otherAccountId; bytes data; } } library Types { enum AssetDenomination { Wei, // the amount is denominated in wei Par // the amount is denominated in par } enum AssetReference { Delta, // the amount is given as a delta from the current value Target // the amount is given as an exact number to end up at } struct AssetAmount { bool sign; // true if positive AssetDenomination denomination; AssetReference ref; uint256 value; } } /** * @title ICallee * @author dYdX * * Interface that Callees for Solo must implement in order to ingest data. */ interface ICallee { /** * Allows users to send this contract arbitrary data. * * @param sender The msg.sender to Solo * @param accountInfo The account from which the data is being sent * @param data Arbitrary data given by the sender */ function callFunction( address sender, Account.Info memory accountInfo, bytes memory data ) external; } interface ISoloMargin { function getNumMarkets() external view returns (uint256); function getMarketTokenAddress(uint256 marketId) external view returns (address); function operate( Account.Info[] memory accounts, Actions.ActionArgs[] memory actions ) external; } contract DyDxFlashloanBase { // -- Internal Helper functions -- // function _getMarketIdFromTokenAddress( ISoloMargin solo, address token ) internal view returns (uint256) { uint256 numMarkets = solo.getNumMarkets(); address curToken; for (uint256 i = 0; i < numMarkets; i++) { curToken = solo.getMarketTokenAddress(i); if (curToken == token) { return i; } } revert("No marketId found for provided token"); } function _getAccountInfo( address receiver ) internal pure returns (Account.Info memory) { return Account.Info({ owner: receiver, number: 1 }); } function _getWithdrawAction( uint marketId, uint256 amount ) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Withdraw, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } function _getCallAction( bytes memory data ) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Call, accountId: 0, amount: Types.AssetAmount({ sign: false, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: 0 }), primaryMarketId: 0, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: data }); } function _getDepositAction( uint marketId, uint256 amount ) internal view returns (Actions.ActionArgs memory) { return Actions.ActionArgs({ actionType: Actions.ActionType.Deposit, accountId: 0, amount: Types.AssetAmount({ sign: true, denomination: Types.AssetDenomination.Wei, ref: Types.AssetReference.Delta, value: amount }), primaryMarketId: marketId, secondaryMarketId: 0, otherAddress: address(this), otherAccountId: 0, data: "" }); } } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.12; pragma experimental ABIEncoderV2; import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol"; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { IVault } from "./Vaults/IVault.sol"; import { IProvider } from "./Providers/IProvider.sol"; import { Flasher } from "./Flashloans/Flasher.sol"; import { FlashLoan } from "./Flashloans/LibFlashLoan.sol"; import { IFujiAdmin } from "./IFujiAdmin.sol"; import { Errors } from "./Libraries/Errors.sol"; interface IVaultExt is IVault { //Asset Struct struct VaultAssets { address collateralAsset; address borrowAsset; uint64 collateralID; uint64 borrowID; } function vAssets() external view returns (VaultAssets memory); } contract Controller is Ownable { using SafeMath for uint256; IFujiAdmin private _fujiAdmin; /** * @dev Sets the fujiAdmin Address * @param _newFujiAdmin: FujiAdmin Contract Address */ function setFujiAdmin(address _newFujiAdmin) external onlyOwner { _fujiAdmin = IFujiAdmin(_newFujiAdmin); } /** * @dev Performs a forced refinancing routine * @param _vaultAddr: fuji Vault address * @param _newProvider: new provider address * @param _ratioA: ratio to determine how much of debtposition to move * @param _ratioB: _ratioA/_ratioB <= 1, and > 0 * @param _flashNum: integer identifier of flashloan provider */ function doRefinancing( address _vaultAddr, address _newProvider, uint256 _ratioA, uint256 _ratioB, uint8 _flashNum ) external onlyOwner { IVault vault = IVault(_vaultAddr); IVaultExt.VaultAssets memory vAssets = IVaultExt(_vaultAddr).vAssets(); vault.updateF1155Balances(); // Check Vault borrowbalance and apply ratio (consider compound or not) uint256 debtPosition = IProvider(vault.activeProvider()).getBorrowBalanceOf(vAssets.borrowAsset, _vaultAddr); uint256 applyRatiodebtPosition = debtPosition.mul(_ratioA).div(_ratioB); // Check Ratio Input and Vault Balance at ActiveProvider require( debtPosition >= applyRatiodebtPosition && applyRatiodebtPosition > 0, Errors.RF_INVALID_RATIO_VALUES ); //Initiate Flash Loan Struct FlashLoan.Info memory info = FlashLoan.Info({ callType: FlashLoan.CallType.Switch, asset: vAssets.borrowAsset, amount: applyRatiodebtPosition, vault: _vaultAddr, newProvider: _newProvider, user: address(0), userliquidator: address(0), fliquidator: address(0) }); Flasher(payable(_fujiAdmin.getFlasher())).initiateFlashloan(info, _flashNum); IVault(_vaultAddr).setActiveProvider(_newProvider); } }
* @dev Initiates a DyDx flashloan. @param info: data to be passed between functions executing flashloan logic/ Get marketId from token address 1. Withdraw $ 2. Call callFunction(...) 3. Deposit back $ Encode FlashLoan.Info for callFunction add fee of 2 wei
function initiateDyDxFlashLoan( FlashLoan.Info memory info ) internal { ISoloMargin solo = ISoloMargin(dydx_solo_margin); uint256 marketId = _getMarketIdFromTokenAddress(solo, info.asset); Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3); operations[0] = _getWithdrawAction(marketId, info.amount); operations[1] = _getCallAction(abi.encode(info)); operations[2] = _getDepositAction(marketId, info.amount.add(2)); Account.Info[] memory accountInfos = new Account.Info[](1); accountInfos[0] = _getAccountInfo(address(this)); solo.operate(accountInfos, operations); }
10,057,229
[ 1, 2570, 16020, 279, 463, 93, 40, 92, 9563, 383, 304, 18, 225, 1123, 30, 501, 358, 506, 2275, 3086, 4186, 11274, 9563, 383, 304, 4058, 19, 968, 13667, 548, 628, 1147, 1758, 404, 18, 3423, 9446, 271, 576, 18, 3049, 745, 2083, 5825, 13, 890, 18, 4019, 538, 305, 1473, 271, 6240, 15014, 1504, 304, 18, 966, 364, 745, 2083, 527, 14036, 434, 576, 732, 77, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 18711, 40, 93, 40, 92, 11353, 1504, 304, 12, 203, 565, 15014, 1504, 304, 18, 966, 3778, 1123, 203, 225, 262, 2713, 288, 203, 203, 565, 4437, 12854, 9524, 3704, 83, 273, 4437, 12854, 9524, 12, 15680, 13437, 67, 87, 12854, 67, 10107, 1769, 203, 203, 565, 2254, 5034, 13667, 548, 273, 389, 588, 3882, 278, 548, 1265, 1345, 1887, 12, 87, 12854, 16, 1123, 18, 9406, 1769, 203, 203, 565, 18765, 18, 1803, 2615, 8526, 3778, 5295, 273, 394, 18765, 18, 1803, 2615, 8526, 12, 23, 1769, 203, 203, 565, 5295, 63, 20, 65, 273, 389, 588, 1190, 9446, 1803, 12, 27151, 548, 16, 1123, 18, 8949, 1769, 203, 565, 5295, 63, 21, 65, 273, 389, 588, 1477, 1803, 12, 21457, 18, 3015, 12, 1376, 10019, 203, 565, 5295, 63, 22, 65, 273, 389, 588, 758, 1724, 1803, 12, 27151, 548, 16, 1123, 18, 8949, 18, 1289, 12, 22, 10019, 203, 203, 565, 6590, 18, 966, 8526, 3778, 2236, 7655, 273, 394, 6590, 18, 966, 8526, 12, 21, 1769, 203, 565, 2236, 7655, 63, 20, 65, 273, 389, 588, 3032, 966, 12, 2867, 12, 2211, 10019, 203, 203, 565, 3704, 83, 18, 4063, 340, 12, 4631, 7655, 16, 5295, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2022-02-12 */ // SPDX-License-Identifier: MIT pragma solidity =0.8.10; abstract contract IDFSRegistry { function getAddr(bytes4 _id) public view virtual returns (address); function addNewContract( bytes32 _id, address _contractAddr, uint256 _waitPeriod ) public virtual; function startContractChange(bytes32 _id, address _newContractAddr) public virtual; function approveContractChange(bytes32 _id) public virtual; function cancelContractChange(bytes32 _id) public virtual; function changeWaitPeriod(bytes32 _id, uint256 _newWaitPeriod) public virtual; } interface IERC20 { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint256 digits); function totalSupply() external view returns (uint256 supply); function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success); function transferFrom( address _from, address _to, uint256 _value ) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) external view returns (uint256 remaining); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } library Address { //insufficient balance error InsufficientBalance(uint256 available, uint256 required); //unable to send value, recipient may have reverted error SendingValueFail(); //insufficient balance for call error InsufficientBalanceForCall(uint256 available, uint256 required); //call to non-contract error NonContractCall(); 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); } function sendValue(address payable recipient, uint256 amount) internal { uint256 balance = address(this).balance; if (balance < amount){ revert InsufficientBalance(balance, amount); } // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); if (!(success)){ revert SendingValueFail(); } } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { uint256 balance = address(this).balance; if (balance < value){ revert InsufficientBalanceForCall(balance, value); } return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { if (!(isContract(target))){ revert NonContractCall(); } // 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); } } } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } 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 Edited so it always first approves 0 and then the value, because of non standard tokens function safeApprove( IERC20 token, address spender, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, 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, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance) ); } 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"); } } } contract MainnetAuthAddresses { address internal constant ADMIN_VAULT_ADDR = 0xCCf3d848e08b94478Ed8f46fFead3008faF581fD; address internal constant FACTORY_ADDRESS = 0x5a15566417e6C1c9546523066500bDDBc53F88C7; address internal constant ADMIN_ADDR = 0x25eFA336886C74eA8E282ac466BdCd0199f85BB9; // USED IN ADMIN VAULT CONSTRUCTOR } contract AuthHelper is MainnetAuthAddresses { } contract AdminVault is AuthHelper { address public owner; address public admin; error SenderNotAdmin(); constructor() { owner = msg.sender; admin = ADMIN_ADDR; } /// @notice Admin is able to change owner /// @param _owner Address of new owner function changeOwner(address _owner) public { if (admin != msg.sender){ revert SenderNotAdmin(); } owner = _owner; } /// @notice Admin is able to set new admin /// @param _admin Address of multisig that becomes new admin function changeAdmin(address _admin) public { if (admin != msg.sender){ revert SenderNotAdmin(); } admin = _admin; } } contract AdminAuth is AuthHelper { using SafeERC20 for IERC20; AdminVault public constant adminVault = AdminVault(ADMIN_VAULT_ADDR); error SenderNotOwner(); error SenderNotAdmin(); modifier onlyOwner() { if (adminVault.owner() != msg.sender){ revert SenderNotOwner(); } _; } modifier onlyAdmin() { if (adminVault.admin() != msg.sender){ revert SenderNotAdmin(); } _; } /// @notice withdraw stuck funds function withdrawStuckFunds(address _token, address _receiver, uint256 _amount) public onlyOwner { if (_token == 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) { payable(_receiver).transfer(_amount); } else { IERC20(_token).safeTransfer(_receiver, _amount); } } /// @notice Destroy the contract function kill() public onlyAdmin { selfdestruct(payable(msg.sender)); } } contract DFSRegistry is AdminAuth { error EntryAlreadyExistsError(bytes4); error EntryNonExistentError(bytes4); error EntryNotInChangeError(bytes4); error ChangeNotReadyError(uint256,uint256); error EmptyPrevAddrError(bytes4); error AlreadyInContractChangeError(bytes4); error AlreadyInWaitPeriodChangeError(bytes4); event AddNewContract(address,bytes4,address,uint256); event RevertToPreviousAddress(address,bytes4,address,address); event StartContractChange(address,bytes4,address,address); event ApproveContractChange(address,bytes4,address,address); event CancelContractChange(address,bytes4,address,address); event StartWaitPeriodChange(address,bytes4,uint256); event ApproveWaitPeriodChange(address,bytes4,uint256,uint256); event CancelWaitPeriodChange(address,bytes4,uint256,uint256); struct Entry { address contractAddr; uint256 waitPeriod; uint256 changeStartTime; bool inContractChange; bool inWaitPeriodChange; bool exists; } mapping(bytes4 => Entry) public entries; mapping(bytes4 => address) public previousAddresses; mapping(bytes4 => address) public pendingAddresses; mapping(bytes4 => uint256) public pendingWaitTimes; /// @notice Given an contract id returns the registered address /// @dev Id is keccak256 of the contract name /// @param _id Id of contract function getAddr(bytes4 _id) public view returns (address) { return entries[_id].contractAddr; } /// @notice Helper function to easily query if id is registered /// @param _id Id of contract function isRegistered(bytes4 _id) public view returns (bool) { return entries[_id].exists; } /////////////////////////// OWNER ONLY FUNCTIONS /////////////////////////// /// @notice Adds a new contract to the registry /// @param _id Id of contract /// @param _contractAddr Address of the contract /// @param _waitPeriod Amount of time to wait before a contract address can be changed function addNewContract( bytes4 _id, address _contractAddr, uint256 _waitPeriod ) public onlyOwner { if (entries[_id].exists){ revert EntryAlreadyExistsError(_id); } entries[_id] = Entry({ contractAddr: _contractAddr, waitPeriod: _waitPeriod, changeStartTime: 0, inContractChange: false, inWaitPeriodChange: false, exists: true }); emit AddNewContract(msg.sender, _id, _contractAddr, _waitPeriod); } /// @notice Reverts to the previous address immediately /// @dev In case the new version has a fault, a quick way to fallback to the old contract /// @param _id Id of contract function revertToPreviousAddress(bytes4 _id) public onlyOwner { if (!(entries[_id].exists)){ revert EntryNonExistentError(_id); } if (previousAddresses[_id] == address(0)){ revert EmptyPrevAddrError(_id); } address currentAddr = entries[_id].contractAddr; entries[_id].contractAddr = previousAddresses[_id]; emit RevertToPreviousAddress(msg.sender, _id, currentAddr, previousAddresses[_id]); } /// @notice Starts an address change for an existing entry /// @dev Can override a change that is currently in progress /// @param _id Id of contract /// @param _newContractAddr Address of the new contract function startContractChange(bytes4 _id, address _newContractAddr) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (entries[_id].inWaitPeriodChange){ revert AlreadyInWaitPeriodChangeError(_id); } entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inContractChange = true; pendingAddresses[_id] = _newContractAddr; emit StartContractChange(msg.sender, _id, entries[_id].contractAddr, _newContractAddr); } /// @notice Changes new contract address, correct time must have passed /// @param _id Id of contract function approveContractChange(bytes4 _id) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (!entries[_id].inContractChange){ revert EntryNotInChangeError(_id); } if (block.timestamp < (entries[_id].changeStartTime + entries[_id].waitPeriod)){// solhint-disable-line revert ChangeNotReadyError(block.timestamp, (entries[_id].changeStartTime + entries[_id].waitPeriod)); } address oldContractAddr = entries[_id].contractAddr; entries[_id].contractAddr = pendingAddresses[_id]; entries[_id].inContractChange = false; entries[_id].changeStartTime = 0; pendingAddresses[_id] = address(0); previousAddresses[_id] = oldContractAddr; emit ApproveContractChange(msg.sender, _id, oldContractAddr, entries[_id].contractAddr); } /// @notice Cancel pending change /// @param _id Id of contract function cancelContractChange(bytes4 _id) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (!entries[_id].inContractChange){ revert EntryNotInChangeError(_id); } address oldContractAddr = pendingAddresses[_id]; pendingAddresses[_id] = address(0); entries[_id].inContractChange = false; entries[_id].changeStartTime = 0; emit CancelContractChange(msg.sender, _id, oldContractAddr, entries[_id].contractAddr); } /// @notice Starts the change for waitPeriod /// @param _id Id of contract /// @param _newWaitPeriod New wait time function startWaitPeriodChange(bytes4 _id, uint256 _newWaitPeriod) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (entries[_id].inContractChange){ revert AlreadyInContractChangeError(_id); } pendingWaitTimes[_id] = _newWaitPeriod; entries[_id].changeStartTime = block.timestamp; // solhint-disable-line entries[_id].inWaitPeriodChange = true; emit StartWaitPeriodChange(msg.sender, _id, _newWaitPeriod); } /// @notice Changes new wait period, correct time must have passed /// @param _id Id of contract function approveWaitPeriodChange(bytes4 _id) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (!entries[_id].inWaitPeriodChange){ revert EntryNotInChangeError(_id); } if (block.timestamp < (entries[_id].changeStartTime + entries[_id].waitPeriod)){ // solhint-disable-line revert ChangeNotReadyError(block.timestamp, (entries[_id].changeStartTime + entries[_id].waitPeriod)); } uint256 oldWaitTime = entries[_id].waitPeriod; entries[_id].waitPeriod = pendingWaitTimes[_id]; entries[_id].inWaitPeriodChange = false; entries[_id].changeStartTime = 0; pendingWaitTimes[_id] = 0; emit ApproveWaitPeriodChange(msg.sender, _id, oldWaitTime, entries[_id].waitPeriod); } /// @notice Cancel wait period change /// @param _id Id of contract function cancelWaitPeriodChange(bytes4 _id) public onlyOwner { if (!entries[_id].exists){ revert EntryNonExistentError(_id); } if (!entries[_id].inWaitPeriodChange){ revert EntryNotInChangeError(_id); } uint256 oldWaitPeriod = pendingWaitTimes[_id]; pendingWaitTimes[_id] = 0; entries[_id].inWaitPeriodChange = false; entries[_id].changeStartTime = 0; emit CancelWaitPeriodChange(msg.sender, _id, oldWaitPeriod, entries[_id].waitPeriod); } } abstract contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view virtual returns (bool); } contract DSAuthEvents { event LogSetAuthority(address indexed authority); event LogSetOwner(address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; constructor() { owner = msg.sender; emit LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; emit LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; emit LogSetAuthority(address(authority)); } modifier auth { require(isAuthorized(msg.sender, msg.sig), "Not authorized"); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(address(0))) { return false; } else { return authority.canCall(src, address(this), sig); } } } contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint256 wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } emit LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } abstract contract DSProxy is DSAuth, DSNote { DSProxyCache public cache; // global cache for contracts constructor(address _cacheAddr) { if (!(setCache(_cacheAddr))){ require(isAuthorized(msg.sender, msg.sig), "Not authorized"); } } // solhint-disable-next-line no-empty-blocks receive() external payable {} // use the proxy to execute calldata _data on contract _code function execute(bytes memory _code, bytes memory _data) public payable virtual returns (address target, bytes32 response); function execute(address _target, bytes memory _data) public payable virtual returns (bytes32 response); //set new cache function setCache(address _cacheAddr) public payable virtual returns (bool); } contract DSProxyCache { mapping(bytes32 => address) cache; function read(bytes memory _code) public view returns (address) { bytes32 hash = keccak256(_code); return cache[hash]; } function write(bytes memory _code) public returns (address target) { assembly { target := create(0, add(_code, 0x20), mload(_code)) switch iszero(extcodesize(target)) case 1 { // throw if contract failed to deploy revert(0, 0) } } bytes32 hash = keccak256(_code); cache[hash] = target; } } contract DefisaverLogger { event RecipeEvent( address indexed caller, string indexed logName ); event ActionDirectEvent( address indexed caller, string indexed logName, bytes data ); function logRecipeEvent( string memory _logName ) public { emit RecipeEvent(msg.sender, _logName); } function logActionDirectEvent( string memory _logName, bytes memory _data ) public { emit ActionDirectEvent(msg.sender, _logName, _data); } } contract MainnetActionsUtilAddresses { address internal constant DFS_REG_CONTROLLER_ADDR = 0xF8f8B3C98Cf2E63Df3041b73f80F362a4cf3A576; address internal constant REGISTRY_ADDR = 0x287778F121F134C66212FB16c9b53eC991D32f5b; address internal constant DFS_LOGGER_ADDR = 0xcE7a977Cac4a481bc84AC06b2Da0df614e621cf3; } contract ActionsUtilHelper is MainnetActionsUtilAddresses { } abstract contract ActionBase is AdminAuth, ActionsUtilHelper { event ActionEvent( string indexed logName, bytes data ); DFSRegistry public constant registry = DFSRegistry(REGISTRY_ADDR); DefisaverLogger public constant logger = DefisaverLogger( DFS_LOGGER_ADDR ); //Wrong sub index value error SubIndexValueError(); //Wrong return index value error ReturnIndexValueError(); /// @dev Subscription params index range [128, 255] uint8 public constant SUB_MIN_INDEX_VALUE = 128; uint8 public constant SUB_MAX_INDEX_VALUE = 255; /// @dev Return params index range [1, 127] uint8 public constant RETURN_MIN_INDEX_VALUE = 1; uint8 public constant RETURN_MAX_INDEX_VALUE = 127; /// @dev If the input value should not be replaced uint8 public constant NO_PARAM_MAPPING = 0; /// @dev We need to parse Flash loan actions in a different way enum ActionType { FL_ACTION, STANDARD_ACTION, FEE_ACTION, CHECK_ACTION, CUSTOM_ACTION } /// @notice Parses inputs and runs the implemented action through a proxy /// @dev Is called by the RecipeExecutor chaining actions together /// @param _callData Array of input values each value encoded as bytes /// @param _subData Array of subscribed vales, replaces input values if specified /// @param _paramMapping Array that specifies how return and subscribed values are mapped in input /// @param _returnValues Returns values from actions before, which can be injected in inputs /// @return Returns a bytes32 value through DSProxy, each actions implements what that value is function executeAction( bytes memory _callData, bytes32[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual returns (bytes32); /// @notice Parses inputs and runs the single implemented action through a proxy /// @dev Used to save gas when executing a single action directly function executeActionDirect(bytes memory _callData) public virtual payable; /// @notice Returns the type of action we are implementing function actionType() public pure virtual returns (uint8); //////////////////////////// HELPER METHODS //////////////////////////// /// @notice Given an uint256 input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamUint( uint _param, uint8 _mapType, bytes32[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (uint) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = uint(_returnValues[getReturnIndex(_mapType)]); } else { _param = uint256(_subData[getSubIndex(_mapType)]); } } return _param; } /// @notice Given an addr input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamAddr( address _param, uint8 _mapType, bytes32[] memory _subData, bytes32[] memory _returnValues ) internal view returns (address) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = address(bytes20((_returnValues[getReturnIndex(_mapType)]))); } else { /// @dev The last two values are specially reserved for proxy addr and owner addr if (_mapType == 254) return address(this); //DSProxy address if (_mapType == 255) return DSProxy(payable(address(this))).owner(); // owner of DSProxy _param = address(uint160(uint256(_subData[getSubIndex(_mapType)]))); } } return _param; } /// @notice Given an bytes32 input, injects return/sub values if specified /// @param _param The original input value /// @param _mapType Indicated the type of the input in paramMapping /// @param _subData Array of subscription data we can replace the input value with /// @param _returnValues Array of subscription data we can replace the input value with function _parseParamABytes32( bytes32 _param, uint8 _mapType, bytes32[] memory _subData, bytes32[] memory _returnValues ) internal pure returns (bytes32) { if (isReplaceable(_mapType)) { if (isReturnInjection(_mapType)) { _param = (_returnValues[getReturnIndex(_mapType)]); } else { _param = _subData[getSubIndex(_mapType)]; } } return _param; } /// @notice Checks if the paramMapping value indicated that we need to inject values /// @param _type Indicated the type of the input function isReplaceable(uint8 _type) internal pure returns (bool) { return _type != NO_PARAM_MAPPING; } /// @notice Checks if the paramMapping value is in the return value range /// @param _type Indicated the type of the input function isReturnInjection(uint8 _type) internal pure returns (bool) { return (_type >= RETURN_MIN_INDEX_VALUE) && (_type <= RETURN_MAX_INDEX_VALUE); } /// @notice Transforms the paramMapping value to the index in return array value /// @param _type Indicated the type of the input function getReturnIndex(uint8 _type) internal pure returns (uint8) { if (!(isReturnInjection(_type))){ revert SubIndexValueError(); } return (_type - RETURN_MIN_INDEX_VALUE); } /// @notice Transforms the paramMapping value to the index in sub array value /// @param _type Indicated the type of the input function getSubIndex(uint8 _type) internal pure returns (uint8) { if (_type < SUB_MIN_INDEX_VALUE){ revert ReturnIndexValueError(); } return (_type - SUB_MIN_INDEX_VALUE); } } abstract contract IWETH { function allowance(address, address) public virtual view returns (uint256); function balanceOf(address) public virtual view returns (uint256); function approve(address, uint256) public virtual; function transfer(address, uint256) public virtual returns (bool); function transferFrom( address, address, uint256 ) public virtual returns (bool); function deposit() public payable virtual; function withdraw(uint256) public virtual; } library TokenUtils { using SafeERC20 for IERC20; address public constant WETH_ADDR = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; function approveToken( address _tokenAddr, address _to, uint256 _amount ) internal { if (_tokenAddr == ETH_ADDR) return; if (IERC20(_tokenAddr).allowance(address(this), _to) < _amount) { IERC20(_tokenAddr).safeApprove(_to, _amount); } } function pullTokensIfNeeded( address _token, address _from, uint256 _amount ) internal returns (uint256) { // handle max uint amount if (_amount == type(uint256).max) { _amount = getBalance(_token, _from); } if (_from != address(0) && _from != address(this) && _token != ETH_ADDR && _amount != 0) { IERC20(_token).safeTransferFrom(_from, address(this), _amount); } return _amount; } function withdrawTokens( address _token, address _to, uint256 _amount ) internal returns (uint256) { if (_amount == type(uint256).max) { _amount = getBalance(_token, address(this)); } if (_to != address(0) && _to != address(this) && _amount != 0) { if (_token != ETH_ADDR) { IERC20(_token).safeTransfer(_to, _amount); } else { payable(_to).transfer(_amount); } } return _amount; } function depositWeth(uint256 _amount) internal { IWETH(WETH_ADDR).deposit{value: _amount}(); } function withdrawWeth(uint256 _amount) internal { IWETH(WETH_ADDR).withdraw(_amount); } function getBalance(address _tokenAddr, address _acc) internal view returns (uint256) { if (_tokenAddr == ETH_ADDR) { return _acc.balance; } else { return IERC20(_tokenAddr).balanceOf(_acc); } } function getTokenDecimals(address _token) internal view returns (uint256) { if (_token == ETH_ADDR) return 18; return IERC20(_token).decimals(); } } contract MainnetUniV3Addresses { address internal constant POSITION_MANAGER_ADDR = 0xC36442b4a4522E871399CD717aBDD847Ab11FE88; } abstract contract IUniswapV3NonfungiblePositionManager{ struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; } function mint(MintParams calldata params) external virtual payable returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ); struct IncreaseLiquidityParams { uint256 tokenId; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } function increaseLiquidity(IncreaseLiquidityParams calldata params) external virtual payable returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ); struct DecreaseLiquidityParams { uint256 tokenId; uint128 liquidity; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } function decreaseLiquidity(DecreaseLiquidityParams calldata params) external virtual payable returns (uint256 amount0, uint256 amount1); struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } function collect(CollectParams calldata params) external virtual payable returns (uint256 amount0, uint256 amount1); function positions(uint256 tokenId) external virtual view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); function balanceOf(address owner) external virtual view returns (uint256 balance); function tokenOfOwnerByIndex(address owner, uint256 index) external virtual view returns (uint256 tokenId); function approve(address to, uint256 tokenId) public virtual; /// @notice Creates a new pool if it does not exist, then initializes if not initialized /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool /// @param token0 The contract address of token0 of the pool /// @param token1 The contract address of token1 of the pool /// @param fee The fee amount of the v3 pool for the specified token pair /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary function createAndInitializePoolIfNecessary( address token0, address token1, uint24 fee, uint160 sqrtPriceX96 ) external virtual payable returns (address pool); } contract UniV3Helper is MainnetUniV3Addresses { IUniswapV3NonfungiblePositionManager public constant positionManager = IUniswapV3NonfungiblePositionManager(POSITION_MANAGER_ADDR); } contract UniSupplyV3 is ActionBase, UniV3Helper{ using TokenUtils for address; /// @param tokenId - The ID of the token for which liquidity is being increased /// @param liquidity -The amount by which liquidity will be increased, /// @param amount0Desired - The desired amount of token0 that should be supplied, /// @param amount1Desired - The desired amount of token1 that should be supplied, /// @param amount0Min - The minimum amount of token0 that should be supplied, /// @param amount1Min - The minimum amount of token1 that should be supplied, /// @param deadline - The time by which the transaction must be included to effect the change /// @param from - account to take amounts from /// @param token0 - address of the first token /// @param token1 - address of the second token struct Params { uint256 tokenId; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; uint256 deadline; address from; address token0; address token1; } /// @inheritdoc ActionBase function executeAction( bytes memory _callData, bytes32[] memory _subData, uint8[] memory _paramMapping, bytes32[] memory _returnValues ) public payable virtual override returns (bytes32) { Params memory uniData = parseInputs(_callData); uniData.tokenId = _parseParamUint(uniData.tokenId, _paramMapping[0], _subData, _returnValues); uniData.amount0Desired = _parseParamUint(uniData.amount0Desired, _paramMapping[1], _subData, _returnValues); uniData.amount1Desired = _parseParamUint(uniData.amount1Desired, _paramMapping[2], _subData, _returnValues); (uint128 liquidity, bytes memory logData) = _uniSupplyPosition(uniData); emit ActionEvent("UniSupplyV3", logData); return bytes32(uint256(liquidity)); } /// @inheritdoc ActionBase function executeActionDirect(bytes memory _callData) public payable override { Params memory uniData = parseInputs(_callData); (, bytes memory logData) = _uniSupplyPosition(uniData); logger.logActionDirectEvent("UniSupplyV3", logData); } /// @inheritdoc ActionBase function actionType() public pure virtual override returns (uint8) { return uint8(ActionType.STANDARD_ACTION); } //////////////////////////// ACTION LOGIC //////////////////////////// function _uniSupplyPosition(Params memory _uniData) internal returns(uint128 liquidity, bytes memory logData) { // fetch tokens from address uint amount0Pulled = _uniData.token0.pullTokensIfNeeded(_uniData.from, _uniData.amount0Desired); uint amount1Pulled = _uniData.token1.pullTokensIfNeeded(_uniData.from, _uniData.amount1Desired); // approve positionManager so it can pull tokens _uniData.token0.approveToken(address(positionManager), amount0Pulled); _uniData.token1.approveToken(address(positionManager), amount1Pulled); _uniData.amount0Desired = amount0Pulled; _uniData.amount1Desired = amount1Pulled; uint256 amount0; uint256 amount1; (liquidity, amount0, amount1) = _uniSupply(_uniData); //send leftovers _uniData.token0.withdrawTokens(_uniData.from, _uniData.amount0Desired - amount0); _uniData.token1.withdrawTokens(_uniData.from, _uniData.amount1Desired - amount1); logData = abi.encode(_uniData, liquidity, amount0, amount1); } /// @dev increases liquidity by token amounts desired /// @return liquidity new liquidity amount function _uniSupply(Params memory _uniData) internal returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ) { IUniswapV3NonfungiblePositionManager.IncreaseLiquidityParams memory increaseLiquidityParams = IUniswapV3NonfungiblePositionManager.IncreaseLiquidityParams({ tokenId: _uniData.tokenId, amount0Desired: _uniData.amount0Desired, amount1Desired: _uniData.amount1Desired, amount0Min: _uniData.amount0Min, amount1Min: _uniData.amount1Min, deadline: _uniData.deadline }); (liquidity, amount0, amount1) = positionManager.increaseLiquidity(increaseLiquidityParams); } function parseInputs(bytes memory _callData) public pure returns ( Params memory uniData ) { uniData = abi.decode(_callData, (Params)); } }
@inheritdoc ActionBase
function executeActionDirect(bytes memory _callData) public payable override { Params memory uniData = parseInputs(_callData); (, bytes memory logData) = _uniSupplyPosition(uniData); logger.logActionDirectEvent("UniSupplyV3", logData); }
7,848,611
[ 1, 36, 10093, 4382, 2171, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1836, 1803, 5368, 12, 3890, 3778, 389, 1991, 751, 13, 1071, 8843, 429, 3849, 288, 203, 3639, 8861, 3778, 7738, 751, 273, 1109, 10059, 24899, 1991, 751, 1769, 203, 3639, 261, 16, 1731, 3778, 613, 751, 13, 273, 389, 318, 77, 3088, 1283, 2555, 12, 318, 77, 751, 1769, 203, 3639, 1194, 18, 1330, 1803, 5368, 1133, 2932, 984, 77, 3088, 1283, 58, 23, 3113, 613, 751, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity >0.4.0<=0.9.0; import "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol"; import "openzeppelin-solidity/contracts/token/ERC20/utils/SafeERC20.sol"; import "openzeppelin-solidity/contracts/security/ReentrancyGuard.sol"; import "openzeppelin-solidity/contracts/access/Ownable.sol"; import "openzeppelin-solidity/contracts/utils/math/Math.sol"; import "openzeppelin-solidity/contracts/utils/math/SafeMath.sol"; /** * @title TokenVesting */ contract TokenVesting is Ownable, ReentrancyGuard{ using SafeMath for uint256; using SafeERC20 for IERC20; struct VestingSchedule{ bool initialized; // beneficiary of tokens after they are released address beneficiary; // cliff period in seconds uint256 cliff; // start time of the vesting period uint256 start; // duration of the vesting period in seconds uint256 duration; // duration of a slice period for the vesting in seconds uint256 slicePeriodSeconds; // whether or not the vesting is revocable bool revocable; // total amount of tokens to be released at the end of the vesting uint256 amountTotal; // amount of tokens released uint256 released; // whether or not the vesting has been revoked bool revoked; } // address of the ERC20 token IERC20 immutable private _token; bytes32[] private vestingSchedulesIds; mapping(bytes32 => VestingSchedule) private vestingSchedules; uint256 private vestingSchedulesTotalAmount; mapping(address => uint256) private holdersVestingCount; event Released(uint256 amount); event Revoked(); /** * @dev Reverts if no vesting schedule matches the passed identifier. */ modifier onlyIfVestingScheduleExists(bytes32 vestingScheduleId) { require(vestingSchedules[vestingScheduleId].initialized == true); _; } /** * @dev Reverts if the vesting schedule does not exist or has been revoked. */ modifier onlyIfVestingScheduleNotRevoked(bytes32 vestingScheduleId) { require(vestingSchedules[vestingScheduleId].initialized == true); require(vestingSchedules[vestingScheduleId].revoked == false); _; } /** * @dev Creates a vesting contract. * @param token_ address of the ERC20 token contract */ constructor(address token_) { require(token_ != address(0x0)); _token = IERC20(token_); } }
SPDX-License-Identifier: Apache-2.0
pragma solidity >0.4.0<=0.9.0;
6,384,617
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 24840, 17, 22, 18, 20, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 683, 9454, 18035, 560, 405, 20, 18, 24, 18, 20, 32, 33, 20, 18, 29, 18, 20, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin/contracts/math/Math.sol pragma solidity 0.5.16; library Math { function MAX818(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a >= b ? a : b; } function MIN910(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return a < b ? a : b; } function AVERAGE710(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity 0.5.16; library SafeMath { function ADD553(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB354(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB354(a, b, "SafeMath: subtraction overflow"); } function SUB354(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL618(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV720(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV720(a, b, "SafeMath: division by zero"); } function DIV720(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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; } function MOD811(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD811(a, b, "SafeMath: modulo by zero"); } function MOD811(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity 0.5.16; contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _MSGSENDER101() internal view returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA729() internal view returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/ownership/Ownable.sol pragma solidity 0.5.16; contract Ownable is Context { address private _owner; event OWNERSHIPTRANSFERRED297(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { _owner = _MSGSENDER101(); emit OWNERSHIPTRANSFERRED297(address(0), _owner); } function OWNER579() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER471() { //inject NONSTANDARD NAMING require(ISOWNER602(), "Ownable: caller is not the owner"); _; } function ISOWNER602() public view returns (bool) { //inject NONSTANDARD NAMING return _MSGSENDER101() == _owner; } function RENOUNCEOWNERSHIP987() public ONLYOWNER471 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED297(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP49(address newOwner) public ONLYOWNER471 { //inject NONSTANDARD NAMING _TRANSFEROWNERSHIP728(newOwner); } function _TRANSFEROWNERSHIP728(address newOwner) internal { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED297(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity 0.5.16; interface IERC20 { function TOTALSUPPLY250() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF938(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER79(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function MINT2(address account, uint amount) external; //inject NONSTANDARD NAMING function ALLOWANCE644(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE576(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM482(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER160(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL369(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity 0.5.16; library Address { function ISCONTRACT625(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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. // 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 != 0x0 && codehash != accountHash); } function TOPAYABLE310(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING return address(uint160(account)); } function SENDVALUE700(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity 0.5.16; library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER546(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN509(token, abi.encodeWithSelector(token.TRANSFER79.selector, to, value)); } function SAFETRANSFERFROM6(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING CALLOPTIONALRETURN509(token, abi.encodeWithSelector(token.TRANSFERFROM482.selector, from, to, value)); } function SAFEAPPROVE811(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // 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.ALLOWANCE644(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); CALLOPTIONALRETURN509(token, abi.encodeWithSelector(token.APPROVE576.selector, spender, value)); } function SAFEINCREASEALLOWANCE917(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE644(address(this), spender).ADD553(value); CALLOPTIONALRETURN509(token, abi.encodeWithSelector(token.APPROVE576.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE400(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE644(address(this), spender).SUB354(value, "SafeERC20: decreased allowance below zero"); CALLOPTIONALRETURN509(token, abi.encodeWithSelector(token.APPROVE576.selector, spender, newAllowance)); } function CALLOPTIONALRETURN509(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // 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).ISCONTRACT625(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } pragma solidity 0.5.16; contract IRewardDistributionRecipient is Ownable { address rewardDistribution; function NOTIFYREWARDAMOUNT190(uint256 reward) external; //inject NONSTANDARD NAMING modifier ONLYREWARDDISTRIBUTION587() { //inject NONSTANDARD NAMING require(_MSGSENDER101() == rewardDistribution, "Caller is not reward distribution"); _; } function SETREWARDDISTRIBUTION306(address _rewardDistribution) //inject NONSTANDARD NAMING external ONLYOWNER471 { rewardDistribution = _rewardDistribution; } } pragma solidity 0.5.16; contract GOFTokenWrapper { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 public stakeToken = IERC20(0x514910771AF9Ca656af840dff83E8264EcF986CA); uint256 private _totalSupply; mapping(address => uint256) private _balances; function TOTALSUPPLY250() public view returns (uint256) { //inject NONSTANDARD NAMING return _totalSupply; } function BALANCEOF938(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return _balances[account]; } function STAKE102(uint256 amount) public { //inject NONSTANDARD NAMING _totalSupply = _totalSupply.ADD553(amount); _balances[msg.sender] = _balances[msg.sender].ADD553(amount); stakeToken.SAFETRANSFERFROM6(msg.sender, address(this), amount); } function WITHDRAW201(uint256 amount) public { //inject NONSTANDARD NAMING _totalSupply = _totalSupply.SUB354(amount); _balances[msg.sender] = _balances[msg.sender].SUB354(amount); stakeToken.SAFETRANSFER546(msg.sender, amount); } } pragma solidity 0.5.16; contract GOFLINKPool is GOFTokenWrapper, IRewardDistributionRecipient { IERC20 public gof = IERC20(0x488E0369f9BC5C40C002eA7c1fe4fd01A198801c); uint256 public constant duration144 = 7 days; //inject NONSTANDARD NAMING uint256 public constant starttime308 = 1599652800; //utc+8 2020-09-09 20:00:00 //inject NONSTANDARD NAMING uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored = 0; bool private open = true; uint256 private constant _gunit942 = 1e18; //inject NONSTANDARD NAMING mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; // Unclaimed rewards event REWARDADDED578(uint256 reward); //inject NONSTANDARD NAMING event STAKED569(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event WITHDRAWN869(address indexed user, uint256 amount); //inject NONSTANDARD NAMING event REWARDPAID604(address indexed user, uint256 reward); //inject NONSTANDARD NAMING event SETOPEN70(bool _open); //inject NONSTANDARD NAMING modifier UPDATEREWARD304(address account) { //inject NONSTANDARD NAMING rewardPerTokenStored = REWARDPERTOKEN70(); lastUpdateTime = LASTTIMEREWARDAPPLICABLE508(); if (account != address(0)) { rewards[account] = EARNED147(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } function LASTTIMEREWARDAPPLICABLE508() public view returns (uint256) { //inject NONSTANDARD NAMING return Math.MIN910(block.timestamp, periodFinish); } function REWARDPERTOKEN70() public view returns (uint256) { //inject NONSTANDARD NAMING if (TOTALSUPPLY250() == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.ADD553( LASTTIMEREWARDAPPLICABLE508() .SUB354(lastUpdateTime) .MUL618(rewardRate) .MUL618(_gunit942) .DIV720(TOTALSUPPLY250()) ); } function EARNED147(address account) public view returns (uint256) { //inject NONSTANDARD NAMING return BALANCEOF938(account) .MUL618(REWARDPERTOKEN70().SUB354(userRewardPerTokenPaid[account])) .DIV720(_gunit942) .ADD553(rewards[account]); } function STAKE102(uint256 amount) public CHECKOPEN514 CHECKSTART795 UPDATEREWARD304(msg.sender){ //inject NONSTANDARD NAMING require(amount > 0, "Golff-Link-POOL: Cannot stake 0"); super.STAKE102(amount); emit STAKED569(msg.sender, amount); } function WITHDRAW201(uint256 amount) public CHECKSTART795 UPDATEREWARD304(msg.sender){ //inject NONSTANDARD NAMING require(amount > 0, "Golff-Link-POOL: Cannot withdraw 0"); super.WITHDRAW201(amount); emit WITHDRAWN869(msg.sender, amount); } function EXIT662() external { //inject NONSTANDARD NAMING WITHDRAW201(BALANCEOF938(msg.sender)); GETREWARD668(); } function GETREWARD668() public CHECKSTART795 UPDATEREWARD304(msg.sender){ //inject NONSTANDARD NAMING uint256 reward = EARNED147(msg.sender); if (reward > 0) { rewards[msg.sender] = 0; gof.SAFETRANSFER546(msg.sender, reward); emit REWARDPAID604(msg.sender, reward); } } modifier CHECKSTART795(){ //inject NONSTANDARD NAMING require(block.timestamp > starttime308,"Golff-Link-POOL: Not start"); _; } modifier CHECKOPEN514() { //inject NONSTANDARD NAMING require(open, "Golff-Link-POOL: Pool is closed"); _; } function GETPERIODFINISH470() external view returns (uint256) { //inject NONSTANDARD NAMING return periodFinish; } function ISOPEN95() external view returns (bool) { //inject NONSTANDARD NAMING return open; } function SETOPEN315(bool _open) external ONLYOWNER471 { //inject NONSTANDARD NAMING open = _open; emit SETOPEN70(_open); } function NOTIFYREWARDAMOUNT190(uint256 reward) //inject NONSTANDARD NAMING external ONLYREWARDDISTRIBUTION587 CHECKOPEN514 UPDATEREWARD304(address(0)){ if (block.timestamp > starttime308){ if (block.timestamp >= periodFinish) { uint256 period = block.timestamp.SUB354(starttime308).DIV720(duration144).ADD553(1); periodFinish = starttime308.ADD553(period.MUL618(duration144)); rewardRate = reward.DIV720(periodFinish.SUB354(block.timestamp)); } else { uint256 remaining = periodFinish.SUB354(block.timestamp); uint256 leftover = remaining.MUL618(rewardRate); rewardRate = reward.ADD553(leftover).DIV720(remaining); } lastUpdateTime = block.timestamp; }else { rewardRate = reward.DIV720(duration144); periodFinish = starttime308.ADD553(duration144); lastUpdateTime = starttime308; } gof.MINT2(address(this),reward); emit REWARDADDED578(reward); // avoid overflow to lock assets _CHECKREWARDRATE734(); } function _CHECKREWARDRATE734() internal view returns (uint256) { //inject NONSTANDARD NAMING return duration144.MUL618(rewardRate).MUL618(_gunit942); } }
inject NONSTANDARD NAMING
function SAFETRANSFERFROM6(IERC20 token, address from, address to, uint256 value) internal {
5,362,674
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 348, 6799, 1584, 54, 17598, 11249, 26, 12, 45, 654, 39, 3462, 1147, 16, 1758, 628, 16, 1758, 358, 16, 2254, 5034, 460, 13, 2713, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; import './RevertHelper.sol'; library InvalidApp { bytes4 internal constant EMITS = bytes4(keccak256('Emit((bytes32[],bytes)[])')); bytes4 internal constant STORES = bytes4(keccak256('Store(bytes32[])')); bytes4 internal constant PAYS = bytes4(keccak256('Pay(bytes32[])')); // attempts to pay the storage contract function inv1() external view { RevertHelper.revertBytes(abi.encodeWithSelector( PAYS, uint(1), uint(5), address(this) )); } // does not change state function inv2() external pure { RevertHelper.revertBytes(abi.encodeWithSelector( EMITS, uint(0), STORES, uint(0), PAYS, uint(0) )); } }
does not change state
function inv2() external pure { RevertHelper.revertBytes(abi.encodeWithSelector( EMITS, uint(0), STORES, uint(0), PAYS, uint(0) )); }
13,033,287
[ 1, 20657, 486, 2549, 919, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 2198, 22, 1435, 3903, 16618, 288, 203, 565, 868, 1097, 2276, 18, 266, 1097, 2160, 12, 21457, 18, 3015, 1190, 4320, 12, 203, 1377, 512, 6068, 55, 16, 2254, 12, 20, 3631, 2347, 51, 7031, 16, 2254, 12, 20, 3631, 25095, 55, 16, 2254, 12, 20, 13, 203, 565, 262, 1769, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x27201232579491Ce9b116Ac6F37D354Cc723A2f3/sources/SimpleToken.sol
* @title Basic token @dev Basic version of StandardToken, with no allowances./
contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; } function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address account) public view returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } }
9,231,630
[ 1, 8252, 1147, 225, 7651, 1177, 434, 8263, 1345, 16, 598, 1158, 1699, 6872, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4232, 39, 3462, 353, 1772, 16, 467, 654, 39, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 203, 97, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 31, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 70, 26488, 63, 4631, 15533, 203, 565, 289, 203, 203, 565, 445, 7412, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 389, 13866, 24899, 3576, 12021, 9334, 8027, 16, 3844, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 389, 5965, 6872, 63, 8443, 6362, 87, 1302, 264, 15533, 203, 565, 289, 203, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 3844, 13, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 389, 12908, 537, 24899, 3576, 12021, 9334, 17571, 264, 16, 3844, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 565, 445, 7412, 1265, 12, 2867, 5793, 2 ]
./full_match/5/0x9ccDD0Bb22aA073Be7f4021D9bfa89fdD7BfAbdF/sources/project_/_pancakeswap/v3-periphery/contracts/base/SelfPermit.sol
@title Self Permit @notice Functionality to call permit on any EIP-2612-compliant token for use in the route @dev These functions are expected to be embedded in multicalls to allow EOAs to approve a contract and call a function that requires an approval in a single transaction.
abstract contract SelfPermit is ISelfPermit { function selfPermit( address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s pragma solidity >=0.5.0; ) public payable override { IERC20Permit(token).permit(msg.sender, address(this), value, deadline, v, r, s); } function selfPermitIfNecessary( address token, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external payable override { if (IERC20(token).allowance(msg.sender, address(this)) < value) selfPermit(token, value, deadline, v, r, s); } function selfPermitAllowed( address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public payable override { IERC20PermitAllowed(token).permit(msg.sender, address(this), nonce, expiry, true, v, r, s); } function selfPermitAllowedIfNecessary( address token, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external payable override { if (IERC20(token).allowance(msg.sender, address(this)) < type(uint256).max) selfPermitAllowed(token, nonce, expiry, v, r, s); } }
1,959,207
[ 1, 10084, 13813, 305, 225, 4284, 7919, 358, 745, 21447, 603, 1281, 512, 2579, 17, 5558, 2138, 17, 832, 18515, 1147, 364, 999, 316, 326, 1946, 225, 8646, 4186, 854, 2665, 358, 506, 7488, 316, 1778, 335, 454, 87, 358, 1699, 512, 51, 1463, 358, 6617, 537, 279, 6835, 471, 745, 279, 445, 716, 4991, 392, 23556, 316, 279, 2202, 2492, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 18954, 9123, 305, 353, 467, 10084, 9123, 305, 288, 203, 565, 445, 365, 9123, 305, 12, 203, 3639, 1758, 1147, 16, 203, 3639, 2254, 5034, 460, 16, 203, 3639, 2254, 5034, 14096, 16, 203, 3639, 2254, 28, 331, 16, 203, 3639, 1731, 1578, 436, 16, 203, 3639, 1731, 1578, 272, 203, 683, 9454, 18035, 560, 1545, 20, 18, 25, 18, 20, 31, 203, 565, 262, 1071, 8843, 429, 3849, 288, 203, 3639, 467, 654, 39, 3462, 9123, 305, 12, 2316, 2934, 457, 1938, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 460, 16, 14096, 16, 331, 16, 436, 16, 272, 1769, 203, 565, 289, 203, 203, 565, 445, 365, 9123, 305, 26034, 12, 203, 3639, 1758, 1147, 16, 203, 3639, 2254, 5034, 460, 16, 203, 3639, 2254, 5034, 14096, 16, 203, 3639, 2254, 28, 331, 16, 203, 3639, 1731, 1578, 436, 16, 203, 3639, 1731, 1578, 272, 203, 565, 262, 3903, 8843, 429, 3849, 288, 203, 3639, 309, 261, 45, 654, 39, 3462, 12, 2316, 2934, 5965, 1359, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3719, 411, 460, 13, 365, 9123, 305, 12, 2316, 16, 460, 16, 14096, 16, 331, 16, 436, 16, 272, 1769, 203, 565, 289, 203, 203, 565, 445, 365, 9123, 305, 5042, 12, 203, 3639, 1758, 1147, 16, 203, 3639, 2254, 5034, 7448, 16, 203, 3639, 2254, 5034, 10839, 16, 203, 3639, 2254, 28, 331, 16, 203, 3639, 1731, 1578, 436, 16, 203, 3639, 1731, 1578, 272, 203, 565, 262, 1071, 8843, 429, 3849, 288, 203, 2 ]
pragma solidity ^0.5.0; /** * @title DSMath * @author MakerDAO * @notice Safe math contracts from Maker. */ contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } /** * @title Owned * @author Gavin Wood? * @notice Primitive owner properties, modifiers and methods for a single * to own a particular contract. */ contract Owned { address public owner = msg.sender; modifier isOwner { assert(msg.sender == owner); _; } function changeOwner(address account) external isOwner { owner = account; } } /** * @title Pausable * @author MakerDAO? * @notice Primitive events, methods, properties for a contract which can be paused by a single owner. */ contract Pausable is Owned { event Pause(); event Unpause(); bool public paused; modifier pausable { assert(!paused); _; } function pause() external isOwner { paused = true; emit Pause(); } function unpause() external isOwner { paused = false; emit Unpause(); } } /** * @title BurnerAccount * @author UnityCoin Team * @notice Primitive events, methods, properties for a contract which has a special burner account that is Owned by a single account. */ contract BurnerAccount is Owned { address public burner; modifier isOwnerOrBurner { assert(msg.sender == burner || msg.sender == owner); _; } function changeBurner(address account) external isOwner { burner = account; } } /** * @title IntervalBased * @author UnityCoin Team * @notice Primitive events, methods, properties for a contract which has a * interval system, that can be changed in-flight. * * Here we create a system in which any valid unixtimestamp can reduce * down to a specific interval number, based on a start time, duration * and offset. * * Interval Derivation * number = offset + ((timestamp - start time) / intervalDuration) * * Note, when your changing the interval params in flight, we must * set the offset to the most current interval number, as to not * disrupt previously used interval numbers / mechanics */ contract IntervalBased is DSMath { // the start interval uint256 public intervalStartTimestamp; // interval duration (e.g. 1 days) uint256 public intervalDuration; // the max amount of intervals that can be processed for interest claim uint256 public intervalMaximum; // interval offset uint256 public intervalOffset; function changeDuration(uint256 duration) internal { // protect againt unecessary change of offset and starttimestamp if (duration == intervalDuration) { return; } // offset all previous intervals intervalOffset = intervalNumber(block.timestamp); // set new duration intervalDuration = duration; // restart timestamp to current intervalStartTimestamp = block.timestamp; } // get the interval number from start position // every timestamp should have an interval past the start timestamp.. function intervalNumber(uint256 timestamp) public view returns(uint256 number) { return add(intervalOffset, sub(timestamp, intervalStartTimestamp) / intervalDuration); } } /** * @title ERC20Events * @author EIP20 Authors * @notice Primitive events for the ERC20 event specification. */ contract ERC20Events { event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens); } /** * @title ERC20 * @author EIP/ERC20 Authors * @author BokkyPooBah / Bok Consulting Pty Ltd 2018. * @notice The ERC20 standard contract interface. */ contract ERC20 is ERC20Events { function totalSupply() external view returns (uint); function balanceOf(address tokenOwner) public view returns (uint); function allowance(address tokenOwner, address spender) external view returns (uint); function approve(address spender, uint amount) public returns (bool); function transfer(address to, uint amount) external returns (bool); function transferFrom( address from, address to, uint amount ) public returns (bool); } /** * @title ERC20Token * @author BokkyPooBah / Bok Consulting Pty Ltd 2018. * @author UnityCoin Team * @author MakerDAO * @notice An ERC20 Token implimentation based roughly off of MakerDAO's * version DSToken. */ contract ERC20Token is DSMath, ERC20 { // Standard EIP20 Name, Symbol, Decimals string public symbol = "USDC"; string public name = "UnityCoinTest"; string public version = "1.0.0"; uint8 public decimals = 18; // Balances for each account mapping(address => uint256) balances; // Owner of account approves the transfer of an amount to another account mapping(address => mapping (address => uint256)) approvals; // Standard EIP20: BalanceOf, Transfer, TransferFrom, Allow, Allowance methods.. // Get the token balance for account `tokenOwner` function balanceOf(address tokenOwner) public view returns (uint balance) { return balances[tokenOwner]; } // Transfer the balance from owner's account to another account function transfer(address to, uint256 tokens) external returns (bool success) { return transferFrom(msg.sender, to, tokens); } // Send `tokens` amount of tokens from address `from` to address `to` // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom(address from, address to, uint256 tokens) public returns (bool success) { if (from != msg.sender) { approvals[from][msg.sender] = sub(approvals[from][msg.sender], tokens); } balances[from] = sub(balances[from], tokens); balances[to] = add(balances[to], tokens); emit Transfer(from, to, tokens); return true; } // Allow `spender` to withdraw from your account, multiple times, up to the `tokens` amount. // If this function is called again it overwrites the current allowance with _value. function approve(address spender, uint256 tokens) public returns (bool success) { approvals[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, 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) external view returns (uint remaining) { return approvals[tokenOwner][spender]; } } /** * @title InterestRateBased * @author UnityCoin Team * @notice A compount interest module which allows for the recording of balance * events and interest rate changes. * * Compound Interest Aglo: * compound interest owed = (principle * ( 1 + Rate / 100 ) * N) – principle; * * This module uses the interval system IntervalBased. * The module is time based and thus we accept that miners can manipulate * time. * * Rate's are specified (as per DSMath imp.) in 10 pow 27 always. * Rates are recorded in an array `interestRates` and thus are indexed. * * Everytime a balance is recorded, we also make sure to set an updatable * pointer to the most recent InterestRate index `intervalToInterestIndex`. * * This module provides a way to calculate compound interest owed, * given the interest rates and balance records are recoded properly. */ contract InterestRateBased is IntervalBased { // Interest Rate Record struct InterestRate { uint256 interval; uint256 rate; // >= 10 ** 27 } // Interval to interest rate InterestRate[] public interestRates; // uint256(interval) => uint256(interest index) mapping(uint256 => uint256) public intervalToInterestIndex; // Balance Records struct BalanceRecord { uint256 interval; uint256 intervalOffset; uint256 balance; } // address(token holder) => uint256(interval) => BalanceChange mapping(address => BalanceRecord[]) public balanceRecords; // address(tokenOwner) => uint256(balance index) mapping(address => uint256) public lastClaimedBalanceIndex; // include balance of method, is ERC20 compliant for tokens function balanceOf(address tokenOwner) public view returns (uint); // VIEW: get current interest rate function latestInterestRate() external view returns (uint256 rateAsRay, uint256 asOfInterval) { uint256 latestRateIndex = interestRates.length > 0 ? sub(interestRates.length, 1) : 0; return (interestRates[latestRateIndex].rate, interestRates[latestRateIndex].interval); } // getters function numInterestRates() public view returns (uint256) { return interestRates.length; } // getters function numBalanceRecords(address tokenOwner) public view returns (uint256) { return balanceRecords[tokenOwner].length; } // interest owed function interestOwed(address tokenOwner) public view returns (uint256 amountOwed, uint256 balanceIndex, uint256 interval) { // check for no balance records.. if (balanceRecords[tokenOwner].length == 0) { return (0, 0, 0); } // balance index amountOwed = 0; balanceIndex = lastClaimedBalanceIndex[tokenOwner]; interval = balanceRecords[tokenOwner][balanceIndex].intervalOffset; // current principle and interest rate uint256 principle = 0; // current principle value uint256 interestRate = 0; // current interest rate // interval markers and interval offset uint256 nextBalanceInterval = interval; // set to starting interval for setup uint256 nextInterestInterval = interval; // set to starting interval for setup // enforce interval maximum, last claim offset difference with max assert(sub(intervalNumber(block.timestamp), intervalOffset) < intervalMaximum); // this for loop should only hit either interest or balance change records, and in theory process only // what is required to calculate compound interest with general computaitonal efficiency // yes, maybe in the future adding a MIN here would be good.. while (interval < intervalNumber(block.timestamp)) { // set interest rates for given interval if (interval == nextInterestInterval) { uint256 interestIndex = intervalToInterestIndex[interval]; // set rate with current interval interestRate = interestRates[interestIndex].rate; // check if look ahead next index is greater than rates length, if so, go to max interval, otherwise next up nextInterestInterval = add(interestIndex, 1) >= interestRates.length ? intervalNumber(block.timestamp) : interestRates[add(interestIndex, 1)].interval; } // setup principle with whats on record at given interval if (interval == nextBalanceInterval) { // get current principle at current balance index, add with amount previously owed in interest principle = add(balanceRecords[tokenOwner][balanceIndex].balance, amountOwed); // increase balance index ahead now that we have the balance balanceIndex = add(balanceIndex, 1); // check if the new blance index exceeds, set next interval to limit or next interval on record nextBalanceInterval = balanceIndex >= balanceRecords[tokenOwner].length ? intervalNumber(block.timestamp) : balanceRecords[tokenOwner][balanceIndex].interval; } // apply compound interest to principle, subtract original principle, add to amount owed amountOwed = add(amountOwed, sub(wmul(principle, rpow(interestRate, sub(min(nextBalanceInterval, nextInterestInterval), interval)) / 10 ** 9), principle)); // set interval to next nearest major balance or interest (or both) change interval = min(nextBalanceInterval, nextInterestInterval); } // return amount owed, adjusted balance index, and the last interval set / used return (amountOwed, (balanceIndex > 0 ? sub(balanceIndex, 1) : 0), interval); } // record users balance (max 2 writes additional per person per transfer) function recordBalance(address tokenOwner) internal { // todays current interval id uint256 todaysInterval = intervalNumber(block.timestamp); // last balance index uint256 latestBalanceIndex = balanceRecords[tokenOwner].length > 0 ? sub(balanceRecords[tokenOwner].length, 1) : 0; // always update the current record (i.e. todays interval) // record balance record (if latest record is for today, add to it, otherwise add a record) if (balanceRecords[tokenOwner].length > 0 && balanceRecords[tokenOwner][latestBalanceIndex].interval == todaysInterval) { balanceRecords[tokenOwner][latestBalanceIndex].balance = balanceOf(tokenOwner); } else { balanceRecords[tokenOwner].push(BalanceRecord({ interval: todaysInterval, intervalOffset: todaysInterval, balance: balanceOf(tokenOwner) })); } // if no interval to interest mapping exists, map it (should always be at least a length of one) if (intervalToInterestIndex[todaysInterval] <= 0) { intervalToInterestIndex[todaysInterval] = sub(interestRates.length, 1); } } // record a new intrest rate change function recordInterestRate(uint256 rate) internal { // min number precision for rate.. might need to add a max here. assert(rate >= RAY); // todays current interval id uint256 todaysInterval = intervalNumber(block.timestamp); // last balance index uint256 latestRateIndex = interestRates.length > 0 ? sub(interestRates.length, 1) : 0; // always update todays interval // record balance record (if latest record is for today, add to it, otherwise add a record) if (interestRates.length > 0 && interestRates[latestRateIndex].interval == todaysInterval) { interestRates[latestRateIndex].rate = rate; } else { interestRates.push(InterestRate({ interval: todaysInterval, rate: rate })); } // map the interval to interest index always intervalToInterestIndex[todaysInterval] = sub(interestRates.length, 1); } } /** * @title PausableCompoundInterestERC20 * @author UnityCoin Team * @notice An implimentation of a mintable, pausable, burnable, compound interest based * ERC20 token. * * The token has a few *special* properties. * - a special burner account (which can burn tokens in its account) * - a special supply tracking pool account / mechanism * - a special interest pool account which interest payments are drawn from * - you cannot transfer from / to any pool (supply or interest) * - you cannot claim interest on the interest pool account * - by all accounts the interest and supply accounts dont really exist * and are used for internal accounting purposes. * * Minting / burning / pausing style is based roughly on DSToken from maker. * * Whenever we burn, mint, change rates we update the supply pool, * which intern updates the totalSupply return. * * The TotalSupply of this token should be as follows: * total supply = supply issued + total interest accued up to current interval * * The special `burner` account can only burn tokens sent to it's account. * You can think of it as a HOT burn account. * The provider can ultimatly burn any account. */ contract PausableCompoundInterestERC20 is Pausable, BurnerAccount, InterestRateBased, ERC20Token { // Non EIP20 Standard Constants, Variables and Events event Mint(address indexed to, uint256 tokens); event Burn(uint256 tokens); event InterestRateChange(uint256 intervalDuration, uint256 intervalExpiry, uint256 indexed interestRateIndex); event InterestClaimed(address indexed tokenOwner, uint256 amountOwed); // the interest pool account address, that wont be included in total supply // hex generated with linux system entropy + dice + keys (private key thrown out) address public constant interestPool = address(0xd365131390302b58A61E265744288097Bd53532e); // this is the based supply pool address, which is used to calculate total supply with interest accured // hex generated with linux system entropy + dice + keys (private key thrown out) address public constant supplyPool = address(0x85c05851ef3175aeFBC74EcA16F174E22b5acF28); // is not a pool account modifier isNotPool(address tokenOwner) { assert(tokenOwner != supplyPool && tokenOwner != interestPool); _; } // total supply with amount owed function totalSupply() external view returns (uint256 supplyWithAccruedInterest) { (uint256 amountOwed,,) = interestOwed(supplyPool); return add(balanceOf(supplyPool), amountOwed); } // Dai/Maker style minting function mint(address to, uint256 amount) public isOwner pausable isNotPool(to) { // any time the supply pool changes, we need to update it's interest owed claimInterestOwed(supplyPool); balances[supplyPool] = add(balances[supplyPool], amount); balances[to] = add(balances[to], amount); recordBalance(supplyPool); recordBalance(to); emit Mint(to, amount); } // the burner can only burn tokens in the burn account function burn(address account) external isOwnerOrBurner pausable isNotPool(account) { // target burn address address target = msg.sender == burner ? burner : account; // any time the supply pool changes, we need to update it's interest owed claimInterestOwed(supplyPool); emit Burn(balances[target]); balances[supplyPool] = sub(balances[supplyPool], balances[target]); balances[target] = 0; // technially the burner account can claim interest, not that it should matter recordBalance(supplyPool); recordBalance(target); } // change interest rates function changeInterestRate( uint256 duration, uint256 maximum, uint256 interestRate, uint256 increasePool, uint256 decreasePool) public isOwner pausable { // claim up supply pool amount if (interestRates.length > 0) { claimInterestOwed(supplyPool); } // set duration and maximum changeDuration(duration); // set interval maximum intervalMaximum = maximum; // record interest rate.. recordInterestRate(interestRate); // set interest pool, no balance needs to be recorded here as this is the interest pool balances[interestPool] = sub(add(balances[interestPool], increasePool), decreasePool); } // hard token set for interest pool function setInterestPool(uint256 tokens) external isOwner pausable { balances[interestPool] = tokens; // no need to record balance as this is the interest pool account.. } // claim interest owed function claimInterestOwed(address tokenOwner) public pausable { // cant claim interest on the interest pool assert(tokenOwner != interestPool); // calculate interest balances and new record indexes (uint256 amountOwed, uint256 balanceIndex, uint256 interval) = interestOwed(tokenOwner); // set last balance index used (it's always one ahead so subtract one) lastClaimedBalanceIndex[tokenOwner] = balanceIndex; // set interval offset if (balanceRecords[tokenOwner].length > 0) { balanceRecords[tokenOwner][balanceIndex].intervalOffset = interval; } // increase the balance of the account, reduce interest pool if (tokenOwner != supplyPool) { balances[interestPool] = sub(balances[interestPool], amountOwed); } // set new token owner balance, record balance event balances[tokenOwner] = add(balances[tokenOwner], amountOwed); recordBalance(tokenOwner); // fire the interest claimed event emit InterestClaimed(tokenOwner, amountOwed); } function transferFrom(address from, address to, uint256 tokens) public pausable isNotPool(from) isNotPool(to) returns (bool success) { super.transferFrom(from, to, tokens); recordBalance(from); recordBalance(to); return true; } // Allow `spender` to withdraw from your account, multiple times, up to the `tokens` amount. // If this function is called again it overwrites the current allowance with _value. function approve(address spender, uint256 tokens) public pausable isNotPool(spender) returns (bool success) { return super.approve(spender, tokens); } } /** * @title SignableCompoundInterestERC20 * @author UnityCoin Team * @notice A meta-transaction enabled version of the PausableCompoundInterestERC20 * this allows you to do a signed transfer or claim using EIP712 signature format. * * We also impliment a constructor here. * * A sender can essentially build EIP712 Claim to specific funds, whereby * someone else (the `feeRecipient`) can recieve a pre-specified fee for * sending the transaction on-behalf of the sender. * * At anytime the sender can invalide the transfer / claim release hash of * a claim / transfer they have signed. * * Written claims also have nonce's to make them unique, and expiries * to remove the change of holding attacks. */ contract SignableCompoundInterestERC20 is PausableCompoundInterestERC20 { // EIP712 Hashes and Seporators bytes32 constant public EIP712_DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract,bytes32 salt)"); bytes32 constant public SIGNEDTRANSFER_TYPEHASH = keccak256("SignedTransfer(address to,uint256 tokens,address feeRecipient,uint256 fee,uint256 expiry,bytes32 nonce)"); bytes32 constant public SIGNEDINTERESTCLAIM_TYPEHASH = keccak256("SignedInterestClaim(address feeRecipient,uint256 fee,uint256 expiry,bytes32 nonce)"); bytes32 public DOMAIN_SEPARATOR = keccak256(abi.encode( EIP712_DOMAIN_TYPEHASH, // EIP712 keccak256("UnityCoin"), // app name keccak256("1"), // app version uint256(1), // chain id address(this), // verifying contract bytes32(0x111857f4a3edcb7462eabc03bfe733db1e3f6cdc2b7971ee739626c98268ae12) // salt )); // address(tokenOwner signer) => bytes32(releaseHash) => bool(was release hash used) mapping(address => mapping(bytes32 => bool)) public releaseHashes; event SignedTransfer(address indexed from, address indexed to, uint256 tokens, bytes32 releaseHash); event SignedInterestClaim(address indexed from, bytes32 releaseHash); // constructor for the entire token constructor( address tokenOwner, // main token controller address tokenBurner, // burner account uint256 initialSupply, // total supply amount uint256 interestIntervalStartTimestamp, // start time uint256 interestIntervalDurationSeconds, // interval duration uint256 interestIntervalMaximum, // interest expiry uint256 interestPoolSize, // total interest pool size uint256 interestRate) public { // setup the burner account burner = tokenBurner; // setup the interest mechnics intervalStartTimestamp = interestIntervalStartTimestamp; // set duration intervalDuration = interestIntervalDurationSeconds; // set interest rates changeInterestRate(interestIntervalDurationSeconds, interestIntervalMaximum, interestRate, interestPoolSize, 0); // mint to the token owner the initial supply mint(tokenOwner, initialSupply); // set the provider owner = tokenOwner; } // allow someone else to pay the gas fee for this token, by taking a fee within the token itself. function signedTransfer(address to, uint256 tokens, address feeRecipient, uint256 fee, uint256 expiry, bytes32 nonce, uint8 v, bytes32 r, bytes32 s) external returns (bool success) { bytes32 releaseHash = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(SIGNEDTRANSFER_TYPEHASH, to, tokens, feeRecipient, fee, expiry, nonce)) )); address from = ecrecover(releaseHash, v, r, s); // check expiry, release hash and balances assert(block.timestamp < expiry); assert(releaseHashes[from][releaseHash] == false); // waste out release hash releaseHashes[from][releaseHash] = true; // allow funds to be transfered. approvals[from][msg.sender] = add(tokens, fee); // transfer funds transferFrom(from, to, tokens); transferFrom(from, feeRecipient, fee); emit SignedTransfer(from, to, tokens, releaseHash); return true; } // allow someone else to fire the claim interest owed method, and get paid a fee in the token to do so function signedInterestClaim( address feeRecipient, uint256 fee, uint256 expiry, bytes32 nonce, uint8 v, bytes32 r, bytes32 s) external returns (bool success) { bytes32 releaseHash = keccak256(abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256(abi.encode(SIGNEDINTERESTCLAIM_TYPEHASH, feeRecipient, fee, expiry, nonce)) )); address from = ecrecover(releaseHash, v, r, s); // check expiry, release hash and balances assert(block.timestamp < expiry); assert(releaseHashes[from][releaseHash] == false); // waste out release hash releaseHashes[from][releaseHash] = true; // claim interest owed claimInterestOwed(from); // allow funds to be transfered. approvals[from][msg.sender] = fee; // transfer funds transferFrom(from, feeRecipient, fee); emit SignedInterestClaim(from, releaseHash); return true; } // this allows a token user to invalidate approved release hashes at anytime.. function invalidateHash(bytes32 releaseHash) external pausable { releaseHashes[msg.sender][releaseHash] = true; } }
Allow `spender` to withdraw from your account, multiple times, up to the `tokens` amount. If this function is called again it overwrites the current allowance with _value.
function approve(address spender, uint256 tokens) public pausable isNotPool(spender) returns (bool success) { return super.approve(spender, tokens); }
15,864,348
[ 1, 7009, 1375, 87, 1302, 264, 68, 358, 598, 9446, 628, 3433, 2236, 16, 3229, 4124, 16, 731, 358, 326, 1375, 7860, 68, 3844, 18, 971, 333, 445, 353, 2566, 3382, 518, 28151, 326, 783, 1699, 1359, 598, 389, 1132, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 2430, 13, 1071, 6790, 16665, 8827, 2864, 12, 87, 1302, 264, 13, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 327, 2240, 18, 12908, 537, 12, 87, 1302, 264, 16, 2430, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/43113/0x1B88Cc23C1AF34C7A3d79C3e6C42b0443Ffe43bA/sources/contracts/TDGStakingPool.sol
RUGPULL public rugpull; ERC721 public dtDoaNFT;
contract TDGStakingPool is IERC721Receiver, Ownable { string public name = "The Detectives Guild Staking"; address public tdgowner; IERC20 public detectivesGuild; address[] public stakedNFTS; uint256[] public stakeTokenIds; string[] public stakeIds; string[] public stakeUris; address[] public stakers; mapping(string => address) public nfts; mapping(address => uint256) public stakingBalance; mapping(address => bool) public hasStaked; mapping(address => bool) public isStaking; mapping(address => uint256) public startTime; mapping(address => uint256) public dappBalance; uint256 annualEmmissions = 1000000000000000000000000000; uint256 rewardPerSecond = 3170979198376459000; event Stake(address _user, uint256 _tokenID); event Unstake(address _user, uint256 _tokenID); event Claimed(address _user); pragma solidity >=0.4.22 <0.9.0; struct MyStakedNFTS { uint256 id; address nft; string uri; } constructor(IERC20 _tdg) public { detectivesGuild = _tdg; tdgowner = msg.sender; } function onERC721Received(address, address, uint256, bytes memory) public virtual override returns (bytes4) { return this.onERC721Received.selector; } function stakeNFT(uint256 nftTOKENID, address dtDaoNft, string memory stakeId, string memory uri) public returns(uint256 _tokenID){ if(isStaking[msg.sender]){ uint256 toTransfer = calculateRewardTotal(msg.sender); dappBalance[msg.sender] += toTransfer; dappBalance[msg.sender] = 0; stakers.push(msg.sender); } if(!hasStaked[msg.sender]) { stakingBalance[msg.sender] = 1; stakingBalance[msg.sender] = stakingBalance[msg.sender] + 1; } isStaking[msg.sender] = true; hasStaked[msg.sender] = true; stakedNFTS.push(dtDaoNft); stakeTokenIds.push(nftTOKENID); stakeIds.push(stakeId); stakeUris.push(uri); nfts[stakeId] = msg.sender; emit Stake(msg.sender, nftTOKENID); return (nftTOKENID); } function stakeNFT(uint256 nftTOKENID, address dtDaoNft, string memory stakeId, string memory uri) public returns(uint256 _tokenID){ if(isStaking[msg.sender]){ uint256 toTransfer = calculateRewardTotal(msg.sender); dappBalance[msg.sender] += toTransfer; dappBalance[msg.sender] = 0; stakers.push(msg.sender); } if(!hasStaked[msg.sender]) { stakingBalance[msg.sender] = 1; stakingBalance[msg.sender] = stakingBalance[msg.sender] + 1; } isStaking[msg.sender] = true; hasStaked[msg.sender] = true; stakedNFTS.push(dtDaoNft); stakeTokenIds.push(nftTOKENID); stakeIds.push(stakeId); stakeUris.push(uri); nfts[stakeId] = msg.sender; emit Stake(msg.sender, nftTOKENID); return (nftTOKENID); } } else { function stakeNFT(uint256 nftTOKENID, address dtDaoNft, string memory stakeId, string memory uri) public returns(uint256 _tokenID){ if(isStaking[msg.sender]){ uint256 toTransfer = calculateRewardTotal(msg.sender); dappBalance[msg.sender] += toTransfer; dappBalance[msg.sender] = 0; stakers.push(msg.sender); } if(!hasStaked[msg.sender]) { stakingBalance[msg.sender] = 1; stakingBalance[msg.sender] = stakingBalance[msg.sender] + 1; } isStaking[msg.sender] = true; hasStaked[msg.sender] = true; stakedNFTS.push(dtDaoNft); stakeTokenIds.push(nftTOKENID); stakeIds.push(stakeId); stakeUris.push(uri); nfts[stakeId] = msg.sender; emit Stake(msg.sender, nftTOKENID); return (nftTOKENID); } } else { startTime[msg.sender] = block.timestamp; function transferOut(address _token, address _to, uint256 _nftTOKENID) internal { IERC721 dtDaoNft = IERC721(_token); dtDaoNft.safeTransferFrom(address(this), _to, _nftTOKENID); } function emergencyWithdraw() public onlyOwner(){ for (uint256 i = stakedNFTS.length - 1; i >= 0 ; i--){ transferOut(stakedNFTS[i], stakers[i], stakeTokenIds[i]); dappBalance[stakers[i]] = 0; isStaking[stakers[i]] = false; hasStaked[stakers[i]] = false; delete stakedNFTS[i]; delete stakeIds[i]; delete stakeTokenIds[i]; delete stakeUris[i]; delete stakers[i]; } } function emergencyWithdraw() public onlyOwner(){ for (uint256 i = stakedNFTS.length - 1; i >= 0 ; i--){ transferOut(stakedNFTS[i], stakers[i], stakeTokenIds[i]); dappBalance[stakers[i]] = 0; isStaking[stakers[i]] = false; hasStaked[stakers[i]] = false; delete stakedNFTS[i]; delete stakeIds[i]; delete stakeTokenIds[i]; delete stakeUris[i]; delete stakers[i]; } } function unstakeNFT(uint256 nftTOKENID, address dtDaoNft, string memory stakeId) public { uint balance = stakingBalance[msg.sender]; require(balance > 0, "There are no NFT's to unStake"); uint256 rewardAmount = calculateRewardforTokenValue(msg.sender, 1); dappBalance[msg.sender] += rewardAmount; transferOut(dtDaoNft, msg.sender, nftTOKENID); stakingBalance[msg.sender] = balance - 1; if (stakingBalance[msg.sender] == 0){ isStaking[msg.sender] = false; } uint256[] memory alist = new uint256[](stakedNFTS.length-1); address[] memory blist = new address[](stakedNFTS.length-1); string[] memory clist = new string[](stakedNFTS.length-1); string[] memory dlist = new string[](stakedNFTS.length-1); for (uint256 i = 0; i < stakedNFTS.length - 1; i++){ if(keccak256(bytes(stakeIds[i])) == keccak256(bytes(stakeId))){ dlist[i] = stakeUris[stakedNFTS.length - 1]; clist[i] = stakeIds[stakedNFTS.length - 1]; blist[i] = stakedNFTS[stakeIds.length - 1]; alist[i] = stakeTokenIds[stakeIds.length - 1]; delete stakedNFTS[stakedNFTS.length - 1]; delete stakeIds[stakedNFTS.length - 1]; delete stakeTokenIds[stakedNFTS.length - 1]; delete stakeUris[stakedNFTS.length - 1]; blist[i] = stakedNFTS[i]; clist[i] = stakeIds[i]; dlist[i] = stakeUris[i]; alist[i] = stakeTokenIds[i]; } stakedNFTS = blist; stakeIds = clist; stakeUris = dlist; stakeTokenIds = alist; } emit Unstake(msg.sender, nftTOKENID); } function unstakeNFT(uint256 nftTOKENID, address dtDaoNft, string memory stakeId) public { uint balance = stakingBalance[msg.sender]; require(balance > 0, "There are no NFT's to unStake"); uint256 rewardAmount = calculateRewardforTokenValue(msg.sender, 1); dappBalance[msg.sender] += rewardAmount; transferOut(dtDaoNft, msg.sender, nftTOKENID); stakingBalance[msg.sender] = balance - 1; if (stakingBalance[msg.sender] == 0){ isStaking[msg.sender] = false; } uint256[] memory alist = new uint256[](stakedNFTS.length-1); address[] memory blist = new address[](stakedNFTS.length-1); string[] memory clist = new string[](stakedNFTS.length-1); string[] memory dlist = new string[](stakedNFTS.length-1); for (uint256 i = 0; i < stakedNFTS.length - 1; i++){ if(keccak256(bytes(stakeIds[i])) == keccak256(bytes(stakeId))){ dlist[i] = stakeUris[stakedNFTS.length - 1]; clist[i] = stakeIds[stakedNFTS.length - 1]; blist[i] = stakedNFTS[stakeIds.length - 1]; alist[i] = stakeTokenIds[stakeIds.length - 1]; delete stakedNFTS[stakedNFTS.length - 1]; delete stakeIds[stakedNFTS.length - 1]; delete stakeTokenIds[stakedNFTS.length - 1]; delete stakeUris[stakedNFTS.length - 1]; blist[i] = stakedNFTS[i]; clist[i] = stakeIds[i]; dlist[i] = stakeUris[i]; alist[i] = stakeTokenIds[i]; } stakedNFTS = blist; stakeIds = clist; stakeUris = dlist; stakeTokenIds = alist; } emit Unstake(msg.sender, nftTOKENID); } function unstakeNFT(uint256 nftTOKENID, address dtDaoNft, string memory stakeId) public { uint balance = stakingBalance[msg.sender]; require(balance > 0, "There are no NFT's to unStake"); uint256 rewardAmount = calculateRewardforTokenValue(msg.sender, 1); dappBalance[msg.sender] += rewardAmount; transferOut(dtDaoNft, msg.sender, nftTOKENID); stakingBalance[msg.sender] = balance - 1; if (stakingBalance[msg.sender] == 0){ isStaking[msg.sender] = false; } uint256[] memory alist = new uint256[](stakedNFTS.length-1); address[] memory blist = new address[](stakedNFTS.length-1); string[] memory clist = new string[](stakedNFTS.length-1); string[] memory dlist = new string[](stakedNFTS.length-1); for (uint256 i = 0; i < stakedNFTS.length - 1; i++){ if(keccak256(bytes(stakeIds[i])) == keccak256(bytes(stakeId))){ dlist[i] = stakeUris[stakedNFTS.length - 1]; clist[i] = stakeIds[stakedNFTS.length - 1]; blist[i] = stakedNFTS[stakeIds.length - 1]; alist[i] = stakeTokenIds[stakeIds.length - 1]; delete stakedNFTS[stakedNFTS.length - 1]; delete stakeIds[stakedNFTS.length - 1]; delete stakeTokenIds[stakedNFTS.length - 1]; delete stakeUris[stakedNFTS.length - 1]; blist[i] = stakedNFTS[i]; clist[i] = stakeIds[i]; dlist[i] = stakeUris[i]; alist[i] = stakeTokenIds[i]; } stakedNFTS = blist; stakeIds = clist; stakeUris = dlist; stakeTokenIds = alist; } emit Unstake(msg.sender, nftTOKENID); } function unstakeNFT(uint256 nftTOKENID, address dtDaoNft, string memory stakeId) public { uint balance = stakingBalance[msg.sender]; require(balance > 0, "There are no NFT's to unStake"); uint256 rewardAmount = calculateRewardforTokenValue(msg.sender, 1); dappBalance[msg.sender] += rewardAmount; transferOut(dtDaoNft, msg.sender, nftTOKENID); stakingBalance[msg.sender] = balance - 1; if (stakingBalance[msg.sender] == 0){ isStaking[msg.sender] = false; } uint256[] memory alist = new uint256[](stakedNFTS.length-1); address[] memory blist = new address[](stakedNFTS.length-1); string[] memory clist = new string[](stakedNFTS.length-1); string[] memory dlist = new string[](stakedNFTS.length-1); for (uint256 i = 0; i < stakedNFTS.length - 1; i++){ if(keccak256(bytes(stakeIds[i])) == keccak256(bytes(stakeId))){ dlist[i] = stakeUris[stakedNFTS.length - 1]; clist[i] = stakeIds[stakedNFTS.length - 1]; blist[i] = stakedNFTS[stakeIds.length - 1]; alist[i] = stakeTokenIds[stakeIds.length - 1]; delete stakedNFTS[stakedNFTS.length - 1]; delete stakeIds[stakedNFTS.length - 1]; delete stakeTokenIds[stakedNFTS.length - 1]; delete stakeUris[stakedNFTS.length - 1]; blist[i] = stakedNFTS[i]; clist[i] = stakeIds[i]; dlist[i] = stakeUris[i]; alist[i] = stakeTokenIds[i]; } stakedNFTS = blist; stakeIds = clist; stakeUris = dlist; stakeTokenIds = alist; } emit Unstake(msg.sender, nftTOKENID); } } else { function claimDappTokens(address user) public returns (uint256){ uint256 rewardAmount = calculateRewardTotal(user); dappBalance[user]+=rewardAmount; detectivesGuild.transfer(user,dappBalance[user]); uint256 totalClaimed = dappBalance[user]; dappBalance[user]=0; startTime[msg.sender] = block.timestamp; emit Claimed(user); return totalClaimed; } function calculateRewardTime(address user) public view returns(uint256){ uint256 end = block.timestamp; uint256 totalTime = end - startTime[user]; return totalTime; } function calculateRewardTotal(address user) public view returns(uint256) { uint256 totalStaked = getTotalStaked(); uint256 totalTime = calculateRewardTime(user); uint256 stakePerToken = (totalTime * rewardPerSecond) / totalStaked; uint256 reward = stakingBalance[user] * stakePerToken; return reward; } function calculateRewardforTokenValue(address user, uint256 amount) public view returns(uint256) { uint256 totalStaked = getTotalStaked(); uint256 totalTime = calculateRewardTime(user); uint256 stakePerToken = (totalTime * rewardPerSecond) / totalStaked; uint256 reward = (amount / 10**18) * stakePerToken; return reward; } function getStakedNFTs() public view returns(MyStakedNFTS[] memory tokenlist){ uint256 count = 0; for (uint256 i = 0; i < stakeIds.length; i++) { if(nfts[stakeIds[i]] == msg.sender){ count++; } } MyStakedNFTS[] memory myList = new MyStakedNFTS[](count); uint256 countNFTS = 0; for (uint256 i = 0; i < stakeIds.length; i++) { if(nfts[stakeIds[i]] == msg.sender){ myList[countNFTS] = MyStakedNFTS(stakeTokenIds[i], stakedNFTS[i], stakeUris[i]); countNFTS++; } } return myList; } function getStakedNFTs() public view returns(MyStakedNFTS[] memory tokenlist){ uint256 count = 0; for (uint256 i = 0; i < stakeIds.length; i++) { if(nfts[stakeIds[i]] == msg.sender){ count++; } } MyStakedNFTS[] memory myList = new MyStakedNFTS[](count); uint256 countNFTS = 0; for (uint256 i = 0; i < stakeIds.length; i++) { if(nfts[stakeIds[i]] == msg.sender){ myList[countNFTS] = MyStakedNFTS(stakeTokenIds[i], stakedNFTS[i], stakeUris[i]); countNFTS++; } } return myList; } function getStakedNFTs() public view returns(MyStakedNFTS[] memory tokenlist){ uint256 count = 0; for (uint256 i = 0; i < stakeIds.length; i++) { if(nfts[stakeIds[i]] == msg.sender){ count++; } } MyStakedNFTS[] memory myList = new MyStakedNFTS[](count); uint256 countNFTS = 0; for (uint256 i = 0; i < stakeIds.length; i++) { if(nfts[stakeIds[i]] == msg.sender){ myList[countNFTS] = MyStakedNFTS(stakeTokenIds[i], stakedNFTS[i], stakeUris[i]); countNFTS++; } } return myList; } function getStakedNFTs() public view returns(MyStakedNFTS[] memory tokenlist){ uint256 count = 0; for (uint256 i = 0; i < stakeIds.length; i++) { if(nfts[stakeIds[i]] == msg.sender){ count++; } } MyStakedNFTS[] memory myList = new MyStakedNFTS[](count); uint256 countNFTS = 0; for (uint256 i = 0; i < stakeIds.length; i++) { if(nfts[stakeIds[i]] == msg.sender){ myList[countNFTS] = MyStakedNFTS(stakeTokenIds[i], stakedNFTS[i], stakeUris[i]); countNFTS++; } } return myList; } function getStakedNFTs() public view returns(MyStakedNFTS[] memory tokenlist){ uint256 count = 0; for (uint256 i = 0; i < stakeIds.length; i++) { if(nfts[stakeIds[i]] == msg.sender){ count++; } } MyStakedNFTS[] memory myList = new MyStakedNFTS[](count); uint256 countNFTS = 0; for (uint256 i = 0; i < stakeIds.length; i++) { if(nfts[stakeIds[i]] == msg.sender){ myList[countNFTS] = MyStakedNFTS(stakeTokenIds[i], stakedNFTS[i], stakeUris[i]); countNFTS++; } } return myList; } function getTotalStaked() public view returns(uint256){ uint256 totalStaked = stakedNFTS.length; return totalStaked; } function getWeeklyEmmissions() public view returns(uint256){ uint256 weeklyEmmissions = annualEmmissions / 52; return weeklyEmmissions; } function getDailyEmmissions() public view returns(uint256){ uint256 dailyEmmissions = annualEmmissions / 365; return dailyEmmissions; } function getDappBalance(address user) public view returns(uint256){ return dappBalance[user]; } function getStakeTime(address user) public view returns(uint256){ return startTime[user]; } function getRewardPerSecond() public view returns(uint256){ return (getDailyEmmissions() / 86400); } }
7,181,695
[ 1, 19866, 9681, 2705, 1071, 436, 637, 13469, 31, 4232, 39, 27, 5340, 1071, 3681, 3244, 6491, 4464, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 29763, 43, 510, 6159, 2864, 353, 467, 654, 39, 27, 5340, 12952, 16, 14223, 6914, 288, 1082, 203, 202, 1080, 1071, 508, 273, 315, 1986, 13796, 3606, 24521, 934, 6159, 14432, 203, 202, 2867, 1071, 6655, 75, 8443, 31, 203, 202, 45, 654, 39, 3462, 1071, 5966, 3606, 43, 680, 31, 203, 203, 202, 2867, 8526, 1071, 384, 9477, 50, 4464, 55, 31, 203, 202, 11890, 5034, 8526, 225, 1071, 384, 911, 1345, 2673, 31, 203, 202, 1080, 8526, 225, 1071, 384, 911, 2673, 31, 203, 202, 1080, 8526, 225, 1071, 384, 911, 23900, 31, 203, 202, 2867, 8526, 1071, 384, 581, 414, 31, 203, 202, 6770, 12, 1080, 516, 1758, 13, 1071, 290, 1222, 87, 31, 203, 202, 6770, 12, 2867, 516, 2254, 5034, 13, 1071, 384, 6159, 13937, 31, 203, 202, 6770, 12, 2867, 516, 1426, 13, 1071, 711, 510, 9477, 31, 203, 202, 6770, 12, 2867, 516, 1426, 13, 1071, 353, 510, 6159, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 8657, 31, 203, 202, 6770, 12, 2867, 516, 2254, 5034, 13, 1071, 302, 2910, 13937, 31, 203, 203, 202, 11890, 5034, 8226, 1462, 1514, 7300, 273, 2130, 12648, 12648, 2787, 11706, 31, 203, 202, 11890, 5034, 19890, 2173, 8211, 273, 890, 4033, 5908, 7235, 30234, 6418, 1105, 6162, 3784, 31, 203, 202, 2575, 934, 911, 12, 2867, 389, 1355, 16, 2254, 5034, 389, 2316, 734, 1769, 6862, 1082, 7010, 202, 2575, 1351, 334, 911, 12, 2867, 389, 1355, 16, 2254, 5034, 389, 2316, 734, 1769, 202, 2 ]
./partial_match/1/0x0dbF49E8Da09b6A44AF55D8D65575b795F6982cf/sources/Aozora.sol
Buy FeeSell FeeOriginal Fee
contract Aozora is Context, IERC20, Ownable { using SafeMath for uint256; string private constant _name = "Aozora"; string private constant _symbol = unicode"青空"; uint8 private constant _decimals = 9; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 public launchBlock; uint256 private _redisFeeOnBuy = 0; uint256 private _taxFeeOnBuy = 0; uint256 private _redisFeeOnSell = 0; uint256 private _taxFeeOnSell = 9; uint256 private _redisFee = _redisFeeOnSell; uint256 private _taxFee = _taxFeeOnSell; uint256 private _previousredisFee = _redisFee; uint256 private _previoustaxFee = _taxFee; mapping(address => bool) public bots; mapping(address => uint256) private cooldown; address payable private _developmentAddress = payable(0x82fC69fFCFE50e96537E5B5E5858c8E8133DBF15); address payable private _marketingAddress = payable(0x82fC69fFCFE50e96537E5B5E5858c8E8133DBF15); IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = true; uint256 public _maxTxAmount = 10000000000 * 10**9; uint256 public _maxWalletSize = 10000000000 * 10**9; uint256 public _swapTokensAtAmount = 10000000 * 10**9; event MaxTxAmountUpdated(uint256 _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor() { _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_developmentAddress] = true; _isExcludedFromFee[_marketingAddress] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function tokenFromReflection(uint256 rAmount) private view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function removeAllFee() private { if (_redisFee == 0 && _taxFee == 0) return; _previousredisFee = _redisFee; _previoustaxFee = _taxFee; _redisFee = 0; _taxFee = 0; } function restoreAllFee() private { _redisFee = _previousredisFee; _taxFee = _previoustaxFee; } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } } else { function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) { if (!tradingOpen) { require(from == owner(), "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _developmentAddress.transfer(amount.mul(50).div(100)); _marketingAddress.transfer(amount.mul(50).div(100)); } function setTrading(bool _tradingOpen) public onlyOwner { tradingOpen = _tradingOpen; } function manualswap() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _developmentAddress || _msgSender() == _marketingAddress); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function blockBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function blockBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function unblockBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); _transferStandard(sender, recipient, amount); if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _redisFee, _taxFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues( uint256 tAmount, uint256 redisFee, uint256 taxFee ) private pure returns ( uint256, uint256, uint256 ) { uint256 tFee = tAmount.mul(redisFee).div(100); uint256 tTeam = tAmount.mul(taxFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner { _redisFeeOnBuy = redisFeeOnBuy; _redisFeeOnSell = redisFeeOnSell; _taxFeeOnBuy = taxFeeOnBuy; _taxFeeOnSell = taxFeeOnSell; } function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner { _swapTokensAtAmount = swapTokensAtAmount; } function toggleSwap(bool _swapEnabled) public onlyOwner { swapEnabled = _swapEnabled; } function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner { _maxTxAmount = maxTxAmount; } function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner { _maxWalletSize = maxWalletSize; } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFee[accounts[i]] = excluded; } } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFee[accounts[i]] = excluded; } } }
4,145,538
[ 1, 38, 9835, 30174, 55, 1165, 30174, 8176, 30174, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 432, 11142, 10610, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 7010, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 7010, 565, 533, 3238, 5381, 389, 529, 273, 315, 37, 11142, 10610, 14432, 203, 565, 533, 3238, 5381, 389, 7175, 273, 5252, 6, 170, 256, 245, 168, 107, 123, 14432, 203, 565, 2254, 28, 3238, 5381, 389, 31734, 273, 2468, 31, 203, 7010, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 86, 5460, 329, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 88, 5460, 329, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 14667, 31, 203, 565, 2254, 5034, 3238, 5381, 4552, 273, 4871, 11890, 5034, 12, 20, 1769, 203, 565, 2254, 5034, 3238, 5381, 389, 88, 5269, 273, 15088, 9449, 380, 1728, 636, 29, 31, 203, 565, 2254, 5034, 3238, 389, 86, 5269, 273, 261, 6694, 300, 261, 6694, 738, 389, 88, 5269, 10019, 203, 565, 2254, 5034, 3238, 389, 88, 14667, 5269, 31, 203, 565, 2254, 5034, 1071, 8037, 1768, 31, 203, 7010, 565, 2254, 5034, 3238, 389, 12311, 14667, 1398, 38, 9835, 273, 374, 31, 203, 565, 2254, 5034, 3238, 389, 8066, 14667, 1398, 38, 9835, 273, 374, 31, 203, 7010, 565, 2254, 5034, 3238, 389, 12311, 14667, 1398, 55, 1165, 273, 374, 31, 203, 565, 2254, 5034, 3238, 389, 8066, 14667, 1398, 55, 1165, 2 ]
// SPDX-License-Identifier: BUSL-1.1 // // 8888888888 888 // 888 888 // 888 888 // 8888888 8888b. .d8888b 888888 .d88b. 888d888 888 888 // 888 "88b d88P" 888 d88""88b 888P" 888 888 // 888 .d888888 888 888 888 888 888 888 888 // 888 888 888 Y88b. Y88b. Y88..88P 888 Y88b 888 // 888 "Y888888 "Y8888P "Y888 "Y88P" 888 "Y88888 // 888 // Y8b d88P // "Y88P" pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/proxy/ClonesUpgradeable.sol"; import "./Archetype.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; contract Factory is OwnableUpgradeable { event CollectionAdded(address indexed sender, address indexed receiver, address collection); address public archetype; function initialize(address archetype_) public initializer { archetype = archetype_; __Ownable_init(); } /// @notice config is a struct in the shape of {string placeholder; string base; uint64 supply; bool permanent;} function createCollection( address _receiver, string memory name, string memory symbol, Archetype.Config calldata config ) external payable returns (address) { address clone = ClonesUpgradeable.clone(archetype); Archetype token = Archetype(clone); token.initialize(name, symbol, config); token.transferOwnership(_receiver); if (msg.value > 0) { (bool sent, ) = payable(_receiver).call{ value: msg.value }(""); require(sent, "1"); } emit CollectionAdded(_msgSender(), _receiver, clone); return clone; } function setArchetype(address archetype_) public onlyOwner { archetype = archetype_; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/Clones.sol) pragma solidity ^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 ClonesUpgradeable { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } } // SPDX-License-Identifier: MIT // Archetype v0.2.0 // // d8888 888 888 // d88888 888 888 // d88P888 888 888 // d88P 888 888d888 .d8888b 88888b. .d88b. 888888 888 888 88888b. .d88b. // d88P 888 888P" d88P" 888 "88b d8P Y8b 888 888 888 888 "88b d8P Y8b // d88P 888 888 888 888 888 88888888 888 888 888 888 888 88888888 // d8888888888 888 Y88b. 888 888 Y8b. Y88b. Y88b 888 888 d88P Y8b. // d88P 888 888 "Y8888P 888 888 "Y8888 "Y888 "Y88888 88888P" "Y8888 // 888 888 // Y8b d88P 888 // "Y88P" 888 pragma solidity ^0.8.4; import "./ERC721A-Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; error InvalidConfig(); error MintNotYetStarted(); error WalletUnauthorizedToMint(); error InsufficientEthSent(); error ExcessiveEthSent(); error MaxSupplyExceeded(); error NumberOfMintsExceeded(); error MintingPaused(); error InvalidReferral(); error InvalidSignature(); error BalanceEmpty(); error TransferFailed(); error MaxBatchSizeExceeded(); error WrongPassword(); error LockedForever(); contract Archetype is Initializable, ERC721AUpgradeable, OwnableUpgradeable { // // EVENTS // event Invited(bytes32 indexed key, bytes32 indexed cid); event Referral(address indexed affiliate, uint128 wad); event Withdrawal(address indexed src, uint128 wad); // // STRUCTS // struct Auth { bytes32 key; bytes32[] proof; } struct Config { string unrevealedUri; string baseUri; address affiliateSigner; uint32 maxSupply; uint32 maxBatchSize; uint32 affiliateFee; uint32 platformFee; } struct Invite { uint128 price; uint64 start; uint64 limit; } struct Invitelist { bytes32 key; bytes32 cid; Invite invite; } struct OwnerBalance { uint128 owner; uint128 platform; } // // VARIABLES // mapping(bytes32 => Invite) public invites; mapping(address => mapping(bytes32 => uint256)) private minted; mapping(address => uint128) public affiliateBalance; address private constant PLATFORM = 0x86B82972282Dd22348374bC63fd21620F7ED847B; // address private constant PLATFORM = 0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC; // TEST (account[2]) bool public revealed; bool public uriUnlocked; string public provenance; bool public provenanceHashUnlocked; OwnerBalance public ownerBalance; Config public config; // // METHODS // function initialize( string memory name, string memory symbol, Config calldata config_ ) external initializer { __ERC721A_init(name, symbol); // affiliateFee max is 50%, platformFee min is 5% and max is 50% if (config_.affiliateFee > 5000 || config_.platformFee > 5000 || config_.platformFee < 500) { revert InvalidConfig(); } config = config_; __Ownable_init(); revealed = false; uriUnlocked = true; provenanceHashUnlocked = true; } function mint( Auth calldata auth, uint256 quantity, address affiliate, bytes calldata signature ) external payable { Invite memory i = invites[auth.key]; if (affiliate != address(0)) { if (affiliate == PLATFORM || affiliate == owner() || affiliate == msg.sender) { revert InvalidReferral(); } validateAffiliate(affiliate, signature, config.affiliateSigner); } if (i.limit == 0) { revert MintingPaused(); } if (!verify(auth, _msgSender())) { revert WalletUnauthorizedToMint(); } if (block.timestamp < i.start) { revert MintNotYetStarted(); } if (i.limit < config.maxSupply) { uint256 totalAfterMint = minted[_msgSender()][auth.key] + quantity; if (totalAfterMint > i.limit) { revert NumberOfMintsExceeded(); } } if (quantity > config.maxBatchSize) { revert MaxBatchSizeExceeded(); } if ((_currentIndex + quantity) > config.maxSupply) { revert MaxSupplyExceeded(); } uint256 cost = i.price * quantity; if (msg.value < cost) { revert InsufficientEthSent(); } if (msg.value > cost) { revert ExcessiveEthSent(); } _safeMint(msg.sender, quantity); if (i.limit < config.maxSupply) { minted[_msgSender()][auth.key] += quantity; } uint128 value = uint128(msg.value); uint128 affiliateWad = 0; if (affiliate != address(0)) { affiliateWad = (value * config.affiliateFee) / 10000; affiliateBalance[affiliate] += affiliateWad; emit Referral(affiliate, affiliateWad); } OwnerBalance memory balance = ownerBalance; uint128 platformWad = (value * config.platformFee) / 10000; uint128 ownerWad = value - affiliateWad - platformWad; ownerBalance = OwnerBalance({ owner: balance.owner + ownerWad, platform: balance.platform + platformWad }); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); if (revealed == false) { return string(abi.encodePacked(config.unrevealedUri, Strings.toString(tokenId))); } return bytes(config.baseUri).length != 0 ? string(abi.encodePacked(config.baseUri, Strings.toString(tokenId))) : ""; } function reveal() public onlyOwner { revealed = true; } function _startTokenId() internal view virtual override returns (uint256) { return 1; } /// @notice the password is "forever" function lockURI(string memory password) public onlyOwner { if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) { revert WrongPassword(); } uriUnlocked = false; } function setUnrevealedURI(string memory _unrevealedURI) public onlyOwner { config.unrevealedUri = _unrevealedURI; } function setBaseURI(string memory baseUri_) public onlyOwner { if (!uriUnlocked) { revert LockedForever(); } config.baseUri = baseUri_; } /// @notice Set BAYC-style provenance once it's calculated function setProvenanceHash(string memory provenanceHash) public onlyOwner { if (!provenanceHashUnlocked) { revert LockedForever(); } provenance = provenanceHash; } /// @notice the password is "forever" function lockProvenanceHash(string memory password) public onlyOwner { if (keccak256(abi.encodePacked(password)) != keccak256(abi.encodePacked("forever"))) { revert WrongPassword(); } provenanceHashUnlocked = false; } function withdraw() public { uint128 wad = 0; if (msg.sender == owner() || msg.sender == PLATFORM) { OwnerBalance memory balance = ownerBalance; if (msg.sender == owner()) { wad = balance.owner; ownerBalance = OwnerBalance({ owner: 0, platform: balance.platform }); } else { wad = balance.platform; ownerBalance = OwnerBalance({ owner: balance.owner, platform: 0 }); } } else { wad = affiliateBalance[msg.sender]; affiliateBalance[msg.sender] = 0; } if (wad == 0) { revert BalanceEmpty(); } (bool success, ) = msg.sender.call{ value: wad }(""); if (!success) { revert TransferFailed(); } emit Withdrawal(msg.sender, wad); } function setInvites(Invitelist[] calldata invitelist) external onlyOwner { for (uint256 i = 0; i < invitelist.length; i++) { Invitelist calldata list = invitelist[i]; invites[list.key] = list.invite; emit Invited(list.key, list.cid); } } function setInvite( bytes32 _key, bytes32 _cid, Invite calldata _invite ) external onlyOwner { invites[_key] = _invite; emit Invited(_key, _cid); } // based on: https://github.com/miguelmota/merkletreejs-solidity/blob/master/contracts/MerkleProof.sol function verify(Auth calldata auth, address account) internal pure returns (bool) { if (auth.key == "") return true; bytes32 computedHash = keccak256(abi.encodePacked(account)); for (uint256 i = 0; i < auth.proof.length; i++) { bytes32 proofElement = auth.proof[i]; if (computedHash <= proofElement) { computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } return computedHash == auth.key; } function validateAffiliate( address affiliate, bytes memory signature, address affiliateSigner ) internal pure { bytes32 signedMessagehash = ECDSA.toEthSignedMessageHash( keccak256(abi.encodePacked(affiliate)) ); address signer = ECDSA.recover(signedMessagehash, signature); if (signer != affiliateSigner) { revert InvalidSignature(); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // Creator: Chiru Labs pragma solidity ^0.8.4; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; // import "./InitializableCustom.sol"; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerQueryForNonexistentToken(); 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 extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 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 ERC721AUpgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable 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; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // 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; function __ERC721A_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC721A_init_unchained(name_, symbol_); } function __ERC721A_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 0; } /** * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).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); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { _addressData[owner].aux = aux; } /** * 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 (_startTokenId() <= curr && 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 = ERC721AUpgradeable.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 virtual 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 (to.isContract() && !_checkContractOnERC721Received(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 _startTokenId() <= tokenId && 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; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _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); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // 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; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.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; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev This is equivalent to _burn(tokenId, false) */ function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // 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 storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.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; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, 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 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 _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @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 {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[42] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (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 proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * 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(!_initialized, "Initializable: contract is already initialized"); // require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; } _; if (isTopLevelCall) { _initializing = false; _initialized = true; } } /** * @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/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 (last updated v4.5.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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; } // 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 IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // 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 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 * ==== * * [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 Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; 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 { } 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; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // 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 { } 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; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ 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); }
* @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./ 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
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); unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); }
527,808
[ 1, 49, 28142, 1375, 16172, 68, 2430, 471, 29375, 2182, 358, 1375, 869, 8338, 29076, 30, 300, 1375, 869, 68, 2780, 506, 326, 3634, 1758, 18, 300, 1375, 16172, 68, 1297, 506, 6802, 2353, 374, 18, 7377, 1282, 279, 288, 5912, 97, 871, 18, 19, 10752, 24190, 854, 7290, 1118, 24755, 640, 7688, 5846, 18, 11013, 578, 1300, 49, 474, 329, 9391, 309, 783, 460, 434, 3344, 397, 10457, 405, 404, 18, 28, 73, 3657, 261, 23728, 13, 300, 404, 3526, 1016, 9391, 87, 309, 389, 2972, 1016, 397, 10457, 405, 404, 18, 22, 73, 4700, 261, 22, 5034, 13, 300, 404, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 81, 474, 12, 203, 565, 1758, 358, 16, 203, 565, 2254, 5034, 10457, 16, 203, 565, 1731, 3778, 389, 892, 16, 203, 565, 1426, 4183, 203, 225, 262, 2713, 288, 203, 565, 2254, 5034, 787, 1345, 548, 273, 389, 2972, 1016, 31, 203, 565, 309, 261, 869, 422, 1758, 12, 20, 3719, 15226, 490, 474, 774, 7170, 1887, 5621, 203, 565, 309, 261, 16172, 422, 374, 13, 15226, 490, 474, 7170, 12035, 5621, 203, 203, 565, 389, 5771, 1345, 1429, 18881, 12, 2867, 12, 20, 3631, 358, 16, 787, 1345, 548, 16, 10457, 1769, 203, 203, 565, 22893, 288, 203, 1377, 389, 2867, 751, 63, 869, 8009, 12296, 1011, 2254, 1105, 12, 16172, 1769, 203, 1377, 389, 2867, 751, 63, 869, 8009, 2696, 49, 474, 329, 1011, 2254, 1105, 12, 16172, 1769, 203, 203, 1377, 389, 995, 12565, 87, 63, 1937, 1345, 548, 8009, 4793, 273, 358, 31, 203, 1377, 389, 995, 12565, 87, 63, 1937, 1345, 548, 8009, 1937, 4921, 273, 2254, 1105, 12, 2629, 18, 5508, 1769, 203, 203, 1377, 2254, 5034, 3526, 1016, 273, 787, 1345, 548, 31, 203, 1377, 2254, 5034, 679, 273, 3526, 1016, 397, 10457, 31, 203, 203, 1377, 309, 261, 4626, 597, 358, 18, 291, 8924, 10756, 288, 203, 3639, 741, 288, 203, 1850, 3626, 12279, 12, 2867, 12, 20, 3631, 358, 16, 3526, 1016, 1769, 203, 1850, 309, 16051, 67, 1893, 8924, 1398, 654, 39, 27, 5340, 8872, 12, 2867, 12, 20, 3631, 358, 16, 3526, 1016, 9904, 16, 389, 892, 3719, 288, 2 ]
pragma solidity ^0.4.21; // Generated by TokenGen and the Fabric Token platform. // https://tokengen.io // https://fabrictoken.io // File: contracts/library/SafeMath.sol /** * @title Safe Math * * @dev Library for safe mathematical operations. */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function minus(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function plus(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: contracts/token/ERC20Token.sol /** * @dev The standard ERC20 Token contract base. */ contract ERC20Token { uint256 public totalSupply; /* shorthand for public function and a property */ 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); } // File: contracts/component/TokenSafe.sol /** * @title TokenSafe * * @dev Abstract contract that serves as a base for the token safes. It is a multi-group token safe, where each group * has it's own release time and multiple accounts with locked tokens. */ contract TokenSafe { using SafeMath for uint; // The ERC20 token contract. ERC20Token token; struct Group { // The release date for the locked tokens // Note: Unix timestamp fits in uint32, however block.timestamp is uint256 uint256 releaseTimestamp; // The total remaining tokens in the group. uint256 remaining; // The individual account token balances in the group. mapping (address => uint) balances; } // The groups of locked tokens mapping (uint8 => Group) public groups; /** * @dev The constructor. * * @param _token The address of the Fabric Token (fundraiser) contract. */ constructor(address _token) public { token = ERC20Token(_token); } /** * @dev The function initializes a group with a release date. * * @param _id Group identifying number. * @param _releaseTimestamp Unix timestamp of the time after which the tokens can be released */ function init(uint8 _id, uint _releaseTimestamp) internal { require(_releaseTimestamp > 0); Group storage group = groups[_id]; group.releaseTimestamp = _releaseTimestamp; } /** * @dev Add new account with locked token balance to the specified group id. * * @param _id Group identifying number. * @param _account The address of the account to be added. * @param _balance The number of tokens to be locked. */ function add(uint8 _id, address _account, uint _balance) internal { Group storage group = groups[_id]; group.balances[_account] = group.balances[_account].plus(_balance); group.remaining = group.remaining.plus(_balance); } /** * @dev Allows an account to be released if it meets the time constraints of the group. * * @param _id Group identifying number. * @param _account The address of the account to be released. */ function release(uint8 _id, address _account) public { Group storage group = groups[_id]; require(now >= group.releaseTimestamp); uint tokens = group.balances[_account]; require(tokens > 0); group.balances[_account] = 0; group.remaining = group.remaining.minus(tokens); if (!token.transfer(_account, tokens)) { revert(); } } } // File: contracts/token/StandardToken.sol /** * @title Standard Token * * @dev The standard abstract implementation of the ERC20 interface. */ contract StandardToken is ERC20Token { using SafeMath for uint256; string public name; string public symbol; uint8 public decimals; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; /** * @dev The constructor assigns the token name, symbols and decimals. */ constructor(string _name, string _symbol, uint8 _decimals) internal { name = _name; symbol = _symbol; decimals = _decimals; } /** * @dev Get the balance of an address. * * @param _address The address which's balance will be checked. * * @return The current balance of the address. */ function balanceOf(address _address) public view returns (uint256 balance) { return balances[_address]; } /** * @dev Checks the amount of tokens that an owner allowed to a spender. * * @param _owner The address which owns the funds allowed for spending by a third-party. * @param _spender The third-party address that is allowed to spend the tokens. * * @return The number of tokens available to `_spender` to be spent. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * @dev Give permission to `_spender` to spend `_value` number of tokens on your behalf. * E.g. You place a buy or sell order on an exchange and in that example, the * `_spender` address is the address of the contract the exchange created to add your token to their * website and you are `msg.sender`. * * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. * * @return Whether the approval process was successful or not. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Transfers `_value` number of tokens to the `_to` address. * * @param _to The address of the recipient. * @param _value The number of tokens to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { executeTransfer(msg.sender, _to, _value); return true; } /** * @dev Allows another contract to spend tokens on behalf of the `_from` address and send them to the `_to` address. * * @param _from The address which approved you to spend tokens on their behalf. * @param _to The address where you want to send tokens. * @param _value The number of tokens to be sent. * * @return Whether the transfer was successful or not. */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_value <= allowed[_from][msg.sender]); allowed[_from][msg.sender] = allowed[_from][msg.sender].minus(_value); executeTransfer(_from, _to, _value); return true; } /** * @dev Internal function that this reused by the transfer functions */ function executeTransfer(address _from, address _to, uint256 _value) internal { require(_to != address(0)); require(_value != 0 && _value <= balances[_from]); balances[_from] = balances[_from].minus(_value); balances[_to] = balances[_to].plus(_value); emit Transfer(_from, _to, _value); } } // File: contracts/token/MintableToken.sol /** * @title Mintable Token * * @dev Allows the creation of new tokens. */ contract MintableToken is StandardToken { /// @dev The only address allowed to mint coins address public minter; /// @dev Indicates whether the token is still mintable. bool public mintingDisabled = false; /** * @dev Event fired when minting is no longer allowed. */ event MintingDisabled(); /** * @dev Allows a function to be executed only if minting is still allowed. */ modifier canMint() { require(!mintingDisabled); _; } /** * @dev Allows a function to be called only by the minter */ modifier onlyMinter() { require(msg.sender == minter); _; } /** * @dev The constructor assigns the minter which is allowed to mind and disable minting */ constructor(address _minter) internal { minter = _minter; } /** * @dev Creates new `_value` number of tokens and sends them to the `_to` address. * * @param _to The address which will receive the freshly minted tokens. * @param _value The number of tokens that will be created. */ function mint(address _to, uint256 _value) public onlyMinter canMint { totalSupply = totalSupply.plus(_value); balances[_to] = balances[_to].plus(_value); emit Transfer(0x0, _to, _value); } /** * @dev Disable the minting of new tokens. Cannot be reversed. * * @return Whether or not the process was successful. */ function disableMinting() public onlyMinter canMint { mintingDisabled = true; emit MintingDisabled(); } } // File: contracts/token/BurnableToken.sol /** * @title Burnable Token * * @dev Allows tokens to be destroyed. */ contract BurnableToken is StandardToken { /** * @dev Event fired when tokens are burned. * * @param _from The address from which tokens will be removed. * @param _value The number of tokens to be destroyed. */ event Burn(address indexed _from, uint256 _value); /** * @dev Burnes `_value` number of tokens. * * @param _value The number of tokens that will be burned. */ function burn(uint256 _value) public { require(_value != 0); address burner = msg.sender; require(_value <= balances[burner]); balances[burner] = balances[burner].minus(_value); totalSupply = totalSupply.minus(_value); emit Burn(burner, _value); emit Transfer(burner, address(0), _value); } } // File: contracts/trait/HasOwner.sol /** * @title HasOwner * * @dev Allows for exclusive access to certain functionality. */ contract HasOwner { // The current owner. address public owner; // Conditionally the new owner. address public newOwner; /** * @dev The constructor. * * @param _owner The address of the owner. */ constructor(address _owner) public { owner = _owner; } /** * @dev Access control modifier that allows only the current owner to call the function. */ modifier onlyOwner { require(msg.sender == owner); _; } /** * @dev The event is fired when the current owner is changed. * * @param _oldOwner The address of the previous owner. * @param _newOwner The address of the new owner. */ event OwnershipTransfer(address indexed _oldOwner, address indexed _newOwner); /** * @dev Transfering the ownership is a two-step process, as we prepare * for the transfer by setting `newOwner` and requiring `newOwner` to accept * the transfer. This prevents accidental lock-out if something goes wrong * when passing the `newOwner` address. * * @param _newOwner The address of the proposed new owner. */ function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } /** * @dev The `newOwner` finishes the ownership transfer process by accepting the * ownership. */ function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransfer(owner, newOwner); owner = newOwner; } } // File: contracts/token/PausableToken.sol /** * @title Pausable Token * * @dev Allows you to pause/unpause transfers of your token. **/ contract PausableToken is StandardToken, HasOwner { /// Indicates whether the token contract is paused or not. bool public paused = false; /** * @dev Event fired when the token contracts gets paused. */ event Pause(); /** * @dev Event fired when the token contracts gets unpaused. */ event Unpause(); /** * @dev Allows a function to be called only when the token contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Pauses the token contract. */ function pause() public onlyOwner whenNotPaused { paused = true; emit Pause(); } /** * @dev Unpauses the token contract. */ function unpause() public onlyOwner { require(paused); paused = false; emit Unpause(); } /// Overrides of the standard token's functions to add the paused/unpaused functionality. function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } } // File: contracts/fundraiser/AbstractFundraiser.sol contract AbstractFundraiser { /// The ERC20 token contract. ERC20Token public token; /** * @dev The event fires every time a new buyer enters the fundraiser. * * @param _address The address of the buyer. * @param _ethers The number of ethers funded. * @param _tokens The number of tokens purchased. */ event FundsReceived(address indexed _address, uint _ethers, uint _tokens); /** * @dev The initialization method for the token * * @param _token The address of the token of the fundraiser */ function initializeFundraiserToken(address _token) internal { token = ERC20Token(_token); } /** * @dev The default function which is executed when someone sends funds to this contract address. */ function() public payable { receiveFunds(msg.sender, msg.value); } /** * @dev this overridable function returns the current conversion rate for the fundraiser */ function getConversionRate() public view returns (uint256); /** * @dev checks whether the fundraiser passed `endTime`. * * @return whether the fundraiser has ended. */ function hasEnded() public view returns (bool); /** * @dev Create and sends tokens to `_address` considering amount funded and `conversionRate`. * * @param _address The address of the receiver of tokens. * @param _amount The amount of received funds in ether. */ function receiveFunds(address _address, uint256 _amount) internal; /** * @dev It throws an exception if the transaction does not meet the preconditions. */ function validateTransaction() internal view; /** * @dev this overridable function makes and handles tokens to buyers */ function handleTokens(address _address, uint256 _tokens) internal; /** * @dev this overridable function forwards the funds (if necessary) to a vault or directly to the beneficiary */ function handleFunds(address _address, uint256 _ethers) internal; } // File: contracts/fundraiser/BasicFundraiser.sol /** * @title Basic Fundraiser * * @dev An abstract contract that is a base for fundraisers. * It implements a generic procedure for handling received funds: * 1. Validates the transaciton preconditions * 2. Calculates the amount of tokens based on the conversion rate. * 3. Delegate the handling of the tokens (mint, transfer or conjure) * 4. Delegate the handling of the funds * 5. Emit event for received funds */ contract BasicFundraiser is HasOwner, AbstractFundraiser { using SafeMath for uint256; // The number of decimals for the token. uint8 constant DECIMALS = 18; // Enforced // Decimal factor for multiplication purposes. uint256 constant DECIMALS_FACTOR = 10 ** uint256(DECIMALS); // The start time of the fundraiser - Unix timestamp. uint256 public startTime; // The end time of the fundraiser - Unix timestamp. uint256 public endTime; // The address where funds collected will be sent. address public beneficiary; // The conversion rate with decimals difference adjustment, // When converion rate is lower than 1 (inversed), the function calculateTokens() should use division uint256 public conversionRate; // The total amount of ether raised. uint256 public totalRaised; /** * @dev The event fires when the number of token conversion rate has changed. * * @param _conversionRate The new number of tokens per 1 ether. */ event ConversionRateChanged(uint _conversionRate); /** * @dev The basic fundraiser initialization method. * * @param _startTime The start time of the fundraiser - Unix timestamp. * @param _endTime The end time of the fundraiser - Unix timestamp. * @param _conversionRate The number of tokens create for 1 ETH funded. * @param _beneficiary The address which will receive the funds gathered by the fundraiser. */ function initializeBasicFundraiser( uint256 _startTime, uint256 _endTime, uint256 _conversionRate, address _beneficiary ) internal { require(_endTime >= _startTime); require(_conversionRate > 0); require(_beneficiary != address(0)); startTime = _startTime; endTime = _endTime; conversionRate = _conversionRate; beneficiary = _beneficiary; } /** * @dev Sets the new conversion rate * * @param _conversionRate New conversion rate */ function setConversionRate(uint256 _conversionRate) public onlyOwner { require(_conversionRate > 0); conversionRate = _conversionRate; emit ConversionRateChanged(_conversionRate); } /** * @dev Sets The beneficiary of the fundraiser. * * @param _beneficiary The address of the beneficiary. */ function setBeneficiary(address _beneficiary) public onlyOwner { require(_beneficiary != address(0)); beneficiary = _beneficiary; } /** * @dev Create and sends tokens to `_address` considering amount funded and `conversionRate`. * * @param _address The address of the receiver of tokens. * @param _amount The amount of received funds in ether. */ function receiveFunds(address _address, uint256 _amount) internal { validateTransaction(); uint256 tokens = calculateTokens(_amount); require(tokens > 0); totalRaised = totalRaised.plus(_amount); handleTokens(_address, tokens); handleFunds(_address, _amount); emit FundsReceived(_address, msg.value, tokens); } /** * @dev this overridable function returns the current conversion rate multiplied by the conversion rate factor */ function getConversionRate() public view returns (uint256) { return conversionRate; } /** * @dev this overridable function that calculates the tokens based on the ether amount */ function calculateTokens(uint256 _amount) internal view returns(uint256 tokens) { tokens = _amount.mul(getConversionRate()); } /** * @dev It throws an exception if the transaction does not meet the preconditions. */ function validateTransaction() internal view { require(msg.value != 0); require(now >= startTime && now < endTime); } /** * @dev checks whether the fundraiser passed `endtime`. * * @return whether the fundraiser is passed its deadline or not. */ function hasEnded() public view returns (bool) { return now >= endTime; } } // File: contracts/token/StandardMintableToken.sol contract StandardMintableToken is MintableToken { constructor(address _minter, string _name, string _symbol, uint8 _decimals) StandardToken(_name, _symbol, _decimals) MintableToken(_minter) public { } } // File: contracts/fundraiser/MintableTokenFundraiser.sol /** * @title Fundraiser With Mintable Token */ contract MintableTokenFundraiser is BasicFundraiser { /** * @dev The initialization method that creates a new mintable token. * * @param _name Token name * @param _symbol Token symbol * @param _decimals Token decimals */ function initializeMintableTokenFundraiser(string _name, string _symbol, uint8 _decimals) internal { token = new StandardMintableToken( address(this), // The fundraiser is the token minter _name, _symbol, _decimals ); } /** * @dev Mint the specific amount tokens */ function handleTokens(address _address, uint256 _tokens) internal { MintableToken(token).mint(_address, _tokens); } } // File: contracts/fundraiser/IndividualCapsFundraiser.sol /** * @title Fundraiser with individual caps * * @dev Allows you to set a hard cap on your fundraiser. */ contract IndividualCapsFundraiser is BasicFundraiser { uint256 public individualMinCap; uint256 public individualMaxCap; uint256 public individualMaxCapTokens; event IndividualMinCapChanged(uint256 _individualMinCap); event IndividualMaxCapTokensChanged(uint256 _individualMaxCapTokens); /** * @dev The initialization method. * * @param _individualMinCap The minimum amount of ether contribution per address. * @param _individualMaxCap The maximum amount of ether contribution per address. */ function initializeIndividualCapsFundraiser(uint256 _individualMinCap, uint256 _individualMaxCap) internal { individualMinCap = _individualMinCap; individualMaxCap = _individualMaxCap; individualMaxCapTokens = _individualMaxCap * conversionRate; } function setConversionRate(uint256 _conversionRate) public onlyOwner { super.setConversionRate(_conversionRate); if (individualMaxCap == 0) { return; } individualMaxCapTokens = individualMaxCap * _conversionRate; emit IndividualMaxCapTokensChanged(individualMaxCapTokens); } function setIndividualMinCap(uint256 _individualMinCap) public onlyOwner { individualMinCap = _individualMinCap; emit IndividualMinCapChanged(individualMinCap); } function setIndividualMaxCap(uint256 _individualMaxCap) public onlyOwner { individualMaxCap = _individualMaxCap; individualMaxCapTokens = _individualMaxCap * conversionRate; emit IndividualMaxCapTokensChanged(individualMaxCapTokens); } /** * @dev Extends the transaction validation to check if the value this higher than the minumum cap. */ function validateTransaction() internal view { super.validateTransaction(); require(msg.value >= individualMinCap); } /** * @dev We validate the new amount doesn't surpass maximum contribution cap */ function handleTokens(address _address, uint256 _tokens) internal { require(individualMaxCapTokens == 0 || token.balanceOf(_address).plus(_tokens) <= individualMaxCapTokens); super.handleTokens(_address, _tokens); } } // File: contracts/fundraiser/GasPriceLimitFundraiser.sol /** * @title GasPriceLimitFundraiser * * @dev This fundraiser allows to set gas price limit for the participants in the fundraiser */ contract GasPriceLimitFundraiser is HasOwner, BasicFundraiser { uint256 public gasPriceLimit; event GasPriceLimitChanged(uint256 gasPriceLimit); /** * @dev This function puts the initial gas limit */ function initializeGasPriceLimitFundraiser(uint256 _gasPriceLimit) internal { gasPriceLimit = _gasPriceLimit; } /** * @dev This function allows the owner to change the gas limit any time during the fundraiser */ function changeGasPriceLimit(uint256 _gasPriceLimit) onlyOwner() public { gasPriceLimit = _gasPriceLimit; emit GasPriceLimitChanged(_gasPriceLimit); } /** * @dev The transaction is valid if the gas price limit is lifted-off or the transaction meets the requirement */ function validateTransaction() internal view { require(gasPriceLimit == 0 || tx.gasprice <= gasPriceLimit); return super.validateTransaction(); } } // File: contracts/fundraiser/ForwardFundsFundraiser.sol /** * @title Forward Funds to Beneficiary Fundraiser * * @dev This contract forwards the funds received to the beneficiary. */ contract ForwardFundsFundraiser is BasicFundraiser { /** * @dev Forward funds directly to beneficiary */ function handleFunds(address, uint256 _ethers) internal { // Forward the funds directly to the beneficiary beneficiary.transfer(_ethers); } } // File: contracts/fundraiser/TieredFundraiser.sol /** * @title TieredFundraiser * * @dev A fundraiser that improves the base conversion precision to allow percent bonuses */ contract TieredFundraiser is BasicFundraiser { // Conversion rate factor for better precision. uint256 constant CONVERSION_RATE_FACTOR = 100; /** * @dev Define conversion rates based on the tier start and end date */ function getConversionRate() public view returns (uint256) { return super.getConversionRate().mul(CONVERSION_RATE_FACTOR); } /** * @dev this overridable function that calculates the tokens based on the ether amount */ function calculateTokens(uint256 _amount) internal view returns(uint256 tokens) { return super.calculateTokens(_amount).div(CONVERSION_RATE_FACTOR); } /** * @dev this overridable function returns the current conversion rate factor */ function getConversionRateFactor() public pure returns (uint256) { return CONVERSION_RATE_FACTOR; } } // File: contracts/Fundraiser.sol /** * @title AdultXToken */ contract AdultXToken is MintableToken, BurnableToken, PausableToken { constructor(address _owner, address _minter) StandardToken( "Adult X Token", // Token name "ADUX", // Token symbol 18 // Token decimals ) HasOwner(_owner) MintableToken(_minter) public { } } /** * @title AdultXTokenSafe */ contract AdultXTokenSafe is TokenSafe { constructor(address _token) TokenSafe(_token) public { // Group "Airdrop" init( 1, // Group Id 1543881540 // Release date = 2018-12-03 23:59 UTC ); add( 1, // Group Id 0x1f98908f6857de3227fb735fACa75CCD5b9403c5, // Token Safe Entry Address 50000000000000000000000000 // Allocated tokens ); // Group "Marketing" init( 2, // Group Id 1543881540 // Release date = 2018-12-03 23:59 UTC ); add( 2, // Group Id 0x1f98908f6857de3227fb735fACa75CCD5b9403c5, // Token Safe Entry Address 100000000000000000000000000 // Allocated tokens ); // Group "Team and Partners" init( 3, // Group Id 1543881540 // Release date = 2018-12-03 23:59 UTC ); add( 3, // Group Id 0x1f98908f6857de3227fb735fACa75CCD5b9403c5, // Token Safe Entry Address 50000000000000000000000000 // Allocated tokens ); } } /** * @title AdultXTokenFundraiser */ contract AdultXTokenFundraiser is MintableTokenFundraiser, IndividualCapsFundraiser, ForwardFundsFundraiser, TieredFundraiser, GasPriceLimitFundraiser { AdultXTokenSafe public tokenSafe; constructor() HasOwner(msg.sender) public { token = new AdultXToken( msg.sender, // Owner address(this) // The fundraiser is the minter ); tokenSafe = new AdultXTokenSafe(token); MintableToken(token).mint(address(tokenSafe), 200000000000000000000000000); initializeBasicFundraiser( 1543795140, // Start date = 2018-12-02 23:59 UTC 1609459140, // End date = 2020-12-31 23:59 UTC 6000, // Conversion rate = 6000 ADUX per 1 ether 0x1f98908f6857de3227fb735fACa75CCD5b9403c5 // Beneficiary ); initializeIndividualCapsFundraiser( (0.1 ether), // Minimum contribution (0 ether) // Maximum individual cap ); initializeGasPriceLimitFundraiser( 0 // Gas price limit in wei ); } /** * @dev Define conversion rates based on the tier start and end date */ function getConversionRate() public view returns (uint256) { uint256 rate = super.getConversionRate(); if (now >= 1543795140 && now < 1544918340) return rate.mul(125).div(100); if (now >= 1544918340 && now < 1546300740) return rate.mul(120).div(100); if (now >= 1546300740 && now < 1547855940) return rate.mul(110).div(100); return rate; } /** * @dev Fundraiser with mintable token allows the owner to mint through the Fundraiser contract */ function mint(address _to, uint256 _value) public onlyOwner { MintableToken(token).mint(_to, _value); } /** * @dev Irreversibly disable minting */ function disableMinting() public onlyOwner { MintableToken(token).disableMinting(); } }
* @title Safe Math @dev Library for safe mathematical operations./
library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; return c; } function minus(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function plus(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
1,777,858
[ 1, 9890, 2361, 225, 18694, 364, 4183, 4233, 351, 270, 1706, 5295, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 14060, 10477, 288, 203, 203, 203, 565, 445, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 276, 273, 279, 380, 324, 31, 203, 3639, 1815, 12, 69, 422, 374, 747, 276, 342, 279, 422, 324, 1769, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 3739, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 276, 273, 279, 342, 324, 31, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 12647, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 1815, 12, 70, 1648, 279, 1769, 203, 203, 3639, 327, 279, 300, 324, 31, 203, 565, 289, 203, 203, 565, 445, 8737, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 276, 273, 279, 397, 324, 31, 203, 3639, 1815, 12, 71, 1545, 279, 1769, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: contracts/libraries/Math.sol // SPDX-License-Identifier: MIT pragma solidity 0.6.12; library Math { function min(uint x, uint y) internal pure returns (uint z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // File: contracts/libraries/SafeMath256.sol pragma solidity 0.6.12; library SafeMath256 { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/libraries/DecFloat32.sol pragma solidity 0.6.12; /* This library defines a decimal floating point number. It has 8 decimal significant digits. Its maximum value is 9.9999999e+15. And its minimum value is 1.0e-16. The following golang code explains its detail implementation. func buildPrice(significant int, exponent int) uint32 { if !(10000000 <= significant && significant <= 99999999) { panic("Invalid significant") } if !(-16 <= exponent && exponent <= 15) { panic("Invalid exponent") } return uint32(((exponent+16)<<27)|significant); } func priceToFloat(price uint32) float64 { exponent := int(price>>27) significant := float64(price&((1<<27)-1)) return significant * math.Pow10(exponent-23) } */ // A price presented as a rational number struct RatPrice { uint numerator; // at most 54bits uint denominator; // at most 76bits } library DecFloat32 { uint32 public constant MANTISSA_MASK = (1<<27) - 1; uint32 public constant MAX_MANTISSA = 9999_9999; uint32 public constant MIN_MANTISSA = 1000_0000; uint32 public constant MIN_PRICE = MIN_MANTISSA; uint32 public constant MAX_PRICE = (31<<27)|MAX_MANTISSA; // 10 ** (i + 1) function powSmall(uint32 i) internal pure returns (uint) { uint x = 2695994666777834996822029817977685892750687677375768584125520488993233305610; return (x >> (32*i)) & ((1<<32)-1); } // 10 ** (i * 8) function powBig(uint32 i) internal pure returns (uint) { uint y = 3402823669209384634633746076162356521930955161600000001; return (y >> (64*i)) & ((1<<64)-1); } // if price32=( 0<<27)|12345678 then numerator=12345678 denominator=100000000000000000000000 // if price32=( 1<<27)|12345678 then numerator=12345678 denominator=10000000000000000000000 // if price32=( 2<<27)|12345678 then numerator=12345678 denominator=1000000000000000000000 // if price32=( 3<<27)|12345678 then numerator=12345678 denominator=100000000000000000000 // if price32=( 4<<27)|12345678 then numerator=12345678 denominator=10000000000000000000 // if price32=( 5<<27)|12345678 then numerator=12345678 denominator=1000000000000000000 // if price32=( 6<<27)|12345678 then numerator=12345678 denominator=100000000000000000 // if price32=( 7<<27)|12345678 then numerator=12345678 denominator=10000000000000000 // if price32=( 8<<27)|12345678 then numerator=12345678 denominator=1000000000000000 // if price32=( 9<<27)|12345678 then numerator=12345678 denominator=100000000000000 // if price32=(10<<27)|12345678 then numerator=12345678 denominator=10000000000000 // if price32=(11<<27)|12345678 then numerator=12345678 denominator=1000000000000 // if price32=(12<<27)|12345678 then numerator=12345678 denominator=100000000000 // if price32=(13<<27)|12345678 then numerator=12345678 denominator=10000000000 // if price32=(14<<27)|12345678 then numerator=12345678 denominator=1000000000 // if price32=(15<<27)|12345678 then numerator=12345678 denominator=100000000 // if price32=(16<<27)|12345678 then numerator=12345678 denominator=10000000 // if price32=(17<<27)|12345678 then numerator=12345678 denominator=1000000 // if price32=(18<<27)|12345678 then numerator=12345678 denominator=100000 // if price32=(19<<27)|12345678 then numerator=12345678 denominator=10000 // if price32=(20<<27)|12345678 then numerator=12345678 denominator=1000 // if price32=(21<<27)|12345678 then numerator=12345678 denominator=100 // if price32=(22<<27)|12345678 then numerator=12345678 denominator=10 // if price32=(23<<27)|12345678 then numerator=12345678 denominator=1 // if price32=(24<<27)|12345678 then numerator=123456780 denominator=1 // if price32=(25<<27)|12345678 then numerator=1234567800 denominator=1 // if price32=(26<<27)|12345678 then numerator=12345678000 denominator=1 // if price32=(27<<27)|12345678 then numerator=123456780000 denominator=1 // if price32=(28<<27)|12345678 then numerator=1234567800000 denominator=1 // if price32=(29<<27)|12345678 then numerator=12345678000000 denominator=1 // if price32=(30<<27)|12345678 then numerator=123456780000000 denominator=1 // if price32=(31<<27)|12345678 then numerator=1234567800000000 denominator=1 function expandPrice(uint32 price32) internal pure returns (RatPrice memory) { uint s = price32&((1<<27)-1); uint32 a = price32 >> 27; RatPrice memory price; if(a >= 24) { uint32 b = a - 24; price.numerator = s * powSmall(b); price.denominator = 1; } else if(a == 23) { price.numerator = s; price.denominator = 1; } else { uint32 b = 22 - a; price.numerator = s; price.denominator = powSmall(b&0x7) * powBig(b>>3); } return price; } function getExpandPrice(uint price) internal pure returns(uint numerator, uint denominator) { uint32 m = uint32(price) & MANTISSA_MASK; require(MIN_MANTISSA <= m && m <= MAX_MANTISSA, "Invalid Price"); RatPrice memory actualPrice = expandPrice(uint32(price)); return (actualPrice.numerator, actualPrice.denominator); } } // File: contracts/libraries/ProxyData.sol pragma solidity 0.6.12; library ProxyData { uint public constant COUNT = 5; uint public constant INDEX_FACTORY = 0; uint public constant INDEX_MONEY_TOKEN = 1; uint public constant INDEX_STOCK_TOKEN = 2; uint public constant INDEX_ONES = 3; uint public constant INDEX_OTHER = 4; uint public constant OFFSET_PRICE_DIV = 0; uint public constant OFFSET_PRICE_MUL = 64; uint public constant OFFSET_STOCK_UNIT = 64+64; uint public constant OFFSET_IS_ONLY_SWAP = 64+64+64; function factory(uint[5] memory proxyData) internal pure returns (address) { return address(proxyData[INDEX_FACTORY]); } function money(uint[5] memory proxyData) internal pure returns (address) { return address(proxyData[INDEX_MONEY_TOKEN]); } function stock(uint[5] memory proxyData) internal pure returns (address) { return address(proxyData[INDEX_STOCK_TOKEN]); } function ones(uint[5] memory proxyData) internal pure returns (address) { return address(proxyData[INDEX_ONES]); } function priceMul(uint[5] memory proxyData) internal pure returns (uint64) { return uint64(proxyData[INDEX_OTHER]>>OFFSET_PRICE_MUL); } function priceDiv(uint[5] memory proxyData) internal pure returns (uint64) { return uint64(proxyData[INDEX_OTHER]>>OFFSET_PRICE_DIV); } function stockUnit(uint[5] memory proxyData) internal pure returns (uint64) { return uint64(proxyData[INDEX_OTHER]>>OFFSET_STOCK_UNIT); } function isOnlySwap(uint[5] memory proxyData) internal pure returns (bool) { return uint8(proxyData[INDEX_OTHER]>>OFFSET_IS_ONLY_SWAP) != 0; } function fill(uint[5] memory proxyData, uint expectedCallDataSize) internal pure { uint size; // solhint-disable-next-line no-inline-assembly assembly { size := calldatasize() } require(size == expectedCallDataSize, "INVALID_CALLDATASIZE"); // solhint-disable-next-line no-inline-assembly assembly { let offset := sub(size, 160) calldatacopy(proxyData, offset, 160) } } } // File: contracts/interfaces/IOneSwapFactory.sol pragma solidity 0.6.12; interface IOneSwapFactory { event PairCreated(address indexed pair, address stock, address money, bool isOnlySwap); function createPair(address stock, address money, bool isOnlySwap) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; function setFeeBPS(uint32 bps) external; function setPairLogic(address implLogic) external; function allPairsLength() external view returns (uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function feeBPS() external view returns (uint32); function pairLogic() external returns (address); function getTokensFromPair(address pair) external view returns (address stock, address money); function tokensToPair(address stock, address money, bool isOnlySwap) external view returns (address pair); } // File: contracts/interfaces/IERC20.sol pragma solidity 0.6.12; 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); } // File: contracts/interfaces/IOneSwapToken.sol pragma solidity 0.6.12; interface IOneSwapBlackList { event OwnerChanged(address); event AddedBlackLists(address[]); event RemovedBlackLists(address[]); function owner()external view returns (address); function newOwner()external view returns (address); function isBlackListed(address)external view returns (bool); function changeOwner(address ownerToSet) external; function updateOwner() external; function addBlackLists(address[] calldata accounts)external; function removeBlackLists(address[] calldata accounts)external; } interface IOneSwapToken is IERC20, IOneSwapBlackList{ function burn(uint256 amount) external; function burnFrom(address account, uint256 amount) external; function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); function multiTransfer(uint256[] calldata mixedAddrVal) external returns (bool); } // File: contracts/interfaces/IOneSwapPair.sol pragma solidity 0.6.12; interface IOneSwapERC20 { 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 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); } interface IOneSwapPool { // more liquidity was minted event Mint(address indexed sender, uint stockAndMoneyAmount, address indexed to); // liquidity was burned event Burn(address indexed sender, uint stockAndMoneyAmount, address indexed to); // amounts of reserved stock and money in this pair changed event Sync(uint reserveStockAndMoney); function internalStatus() external view returns(uint[3] memory res); function getReserves() external view returns (uint112 reserveStock, uint112 reserveMoney, uint32 firstSellID); function getBooked() external view returns (uint112 bookedStock, uint112 bookedMoney, uint32 firstBuyID); function stock() external returns (address); function money() external returns (address); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint stockAmount, uint moneyAmount); function skim(address to) external; function sync() external; } interface IOneSwapPair { event NewLimitOrder(uint data); // new limit order was sent by an account event NewMarketOrder(uint data); // new market order was sent by an account event OrderChanged(uint data); // old orders in orderbook changed event DealWithPool(uint data); // new order deal with the AMM pool event RemoveOrder(uint data); // an order was removed from the orderbook // Return three prices in rational number form, i.e., numerator/denominator. // They are: the first sell order's price; the first buy order's price; the current price of the AMM pool. function getPrices() external returns ( uint firstSellPriceNumerator, uint firstSellPriceDenominator, uint firstBuyPriceNumerator, uint firstBuyPriceDenominator, uint poolPriceNumerator, uint poolPriceDenominator); // This function queries a list of orders in orderbook. It starts from 'id' and iterates the single-linked list, util it reaches the end, // or until it has found 'maxCount' orders. If 'id' is 0, it starts from the beginning of the single-linked list. // It may cost a lot of gas. So you'd not to call in on chain. It is mainly for off-chain query. // The first uint256 returned by this function is special: the lowest 24 bits is the first order's id and the the higher bits is block height. // THe other uint256s are all corresponding to an order record of the single-linked list. function getOrderList(bool isBuy, uint32 id, uint32 maxCount) external view returns (uint[] memory); // remove an order from orderbook and return its booked (i.e. frozen) money to maker // 'id' points to the order to be removed // prevKey points to 3 previous orders in the single-linked list function removeOrder(bool isBuy, uint32 id, uint72 positionID) external; function removeOrders(uint[] calldata rmList) external; // Try to deal a new limit order or insert it into orderbook // its suggested order id is 'id' and suggested positions are in 'prevKey' // prevKey points to 3 existing orders in the single-linked list // the order's sender is 'sender'. the order's amount is amount*stockUnit, which is the stock amount to be sold or bought. // the order's price is 'price32', which is decimal floating point value. function addLimitOrder(bool isBuy, address sender, uint64 amount, uint32 price32, uint32 id, uint72 prevKey) external payable; // Try to deal a new market order. 'sender' pays 'inAmount' of 'inputToken', in exchange of the other token kept by this pair function addMarketOrder(address inputToken, address sender, uint112 inAmount) external payable returns (uint); // Given the 'amount' of stock and decimal floating point price 'price32', calculate the 'stockAmount' and 'moneyAmount' to be traded function calcStockAndMoney(uint64 amount, uint32 price32) external pure returns (uint stockAmount, uint moneyAmount); } // File: contracts/OneSwapPair.sol pragma solidity 0.6.12; abstract contract OneSwapERC20 is IOneSwapERC20 { using SafeMath256 for uint; uint internal _unusedVar0; uint internal _unusedVar1; uint internal _unusedVar2; uint internal _unusedVar3; uint internal _unusedVar4; uint internal _unusedVar5; uint internal _unusedVar6; uint internal _unusedVar7; uint internal _unusedVar8; uint internal _unusedVar9; uint internal _unlocked = 1; modifier lock() { require(_unlocked == 1, "OneSwap: LOCKED"); _unlocked = 0; _; _unlocked = 1; } string private constant _NAME = "OneSwap-Liquidity-Share"; uint8 private constant _DECIMALS = 18; uint public override totalSupply; mapping(address => uint) public override balanceOf; mapping(address => mapping(address => uint)) public override allowance; function symbol() virtual external override returns (string memory); function name() external view override returns (string memory) { return _NAME; } function decimals() external view override returns (uint8) { return _DECIMALS; } function _mint(address to, uint value) internal { totalSupply = totalSupply.add(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(address(0), to, value); } function _burn(address from, uint value) internal { balanceOf[from] = balanceOf[from].sub(value); totalSupply = totalSupply.sub(value); emit Transfer(from, address(0), value); } function _approve(address owner, address spender, uint value) private { allowance[owner][spender] = value; emit Approval(owner, spender, value); } function _transfer(address from, address to, uint value) private { balanceOf[from] = balanceOf[from].sub(value); balanceOf[to] = balanceOf[to].add(value); emit Transfer(from, to, value); } function approve(address spender, uint value) external override returns (bool) { _approve(msg.sender, spender, value); return true; } function transfer(address to, uint value) external override returns (bool) { _transfer(msg.sender, to, value); return true; } function transferFrom(address from, address to, uint value) external override returns (bool) { if (allowance[from][msg.sender] != uint(- 1)) { allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); } _transfer(from, to, value); return true; } } // An order can be compressed into 256 bits and saved using one SSTORE instruction // The orders form a single-linked list. The preceding order points to the following order with nextID struct Order { //total 256 bits address sender; //160 bits, sender creates this order uint32 price; // 32-bit decimal floating point number uint64 amount; // 42 bits are used, the stock amount to be sold or bought uint32 nextID; // 22 bits are used } // When the match engine of orderbook runs, it uses follow context to cache data in memory struct Context { // this order is a limit order bool isLimitOrder; // the new order's id, it is only used when a limit order is not fully dealt uint32 newOrderID; // for buy-order, it's remained money amount; for sell-order, it's remained stock amount uint remainAmount; // it points to the first order in the opposite order book against current order uint32 firstID; // it points to the first order in the buy-order book uint32 firstBuyID; // it points to the first order in the sell-order book uint32 firstSellID; // the amount goes into the pool, for buy-order, it's money amount; for sell-order, it's stock amount uint amountIntoPool; // the total dealt money and stock in the order book uint dealMoneyInBook; uint dealStockInBook; // cache these values from storage to memory uint reserveMoney; uint reserveStock; uint bookedMoney; uint bookedStock; // reserveMoney or reserveStock is changed bool reserveChanged; // the taker has dealt in the orderbook bool hasDealtInOrderBook; // the current taker order Order order; // the following data come from proxy uint64 stockUnit; uint64 priceMul; uint64 priceDiv; address stockToken; address moneyToken; address ones; address factory; } // OneSwapPair combines a Uniswap-like AMM and an orderbook abstract contract OneSwapPool is OneSwapERC20, IOneSwapPool { using SafeMath256 for uint; uint private constant _MINIMUM_LIQUIDITY = 10 ** 3; bytes4 internal constant _SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)"))); // reserveMoney and reserveStock are both uint112, id is 22 bits; they are compressed into a uint256 word uint internal _reserveStockAndMoneyAndFirstSellID; // bookedMoney and bookedStock are both uint112, id is 22 bits; they are compressed into a uint256 word uint internal _bookedStockAndMoneyAndFirstBuyID; uint private _kLast; uint32 private constant _OS = 2; // owner's share uint32 private constant _LS = 3; // liquidity-provider's share function internalStatus() external override view returns(uint[3] memory res) { res[0] = _reserveStockAndMoneyAndFirstSellID; res[1] = _bookedStockAndMoneyAndFirstBuyID; res[2] = _kLast; } function stock() external override returns (address) { uint[5] memory proxyData; ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+0)); return ProxyData.stock(proxyData); } function money() external override returns (address) { uint[5] memory proxyData; ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+0)); return ProxyData.money(proxyData); } // the following 4 functions load&store compressed storage function getReserves() public override view returns (uint112 reserveStock, uint112 reserveMoney, uint32 firstSellID) { uint temp = _reserveStockAndMoneyAndFirstSellID; reserveStock = uint112(temp); reserveMoney = uint112(temp>>112); firstSellID = uint32(temp>>224); } function _setReserves(uint stockAmount, uint moneyAmount, uint32 firstSellID) internal { require(stockAmount < uint(1<<112) && moneyAmount < uint(1<<112), "OneSwap: OVERFLOW"); uint temp = (moneyAmount<<112)|stockAmount; emit Sync(temp); temp = (uint(firstSellID)<<224)| temp; _reserveStockAndMoneyAndFirstSellID = temp; } function getBooked() public override view returns (uint112 bookedStock, uint112 bookedMoney, uint32 firstBuyID) { uint temp = _bookedStockAndMoneyAndFirstBuyID; bookedStock = uint112(temp); bookedMoney = uint112(temp>>112); firstBuyID = uint32(temp>>224); } function _setBooked(uint stockAmount, uint moneyAmount, uint32 firstBuyID) internal { require(stockAmount < uint(1<<112) && moneyAmount < uint(1<<112), "OneSwap: OVERFLOW"); _bookedStockAndMoneyAndFirstBuyID = (uint(firstBuyID)<<224)|(moneyAmount<<112)|stockAmount; } function _myBalance(address token) internal view returns (uint) { if(token==address(0)) { return address(this).balance; } else { return IERC20(token).balanceOf(address(this)); } } // safely transfer ERC20 tokens, or ETH (when token==0) function _safeTransfer(address token, address to, uint value, address ones) internal { if(token==address(0)) { // limit gas to 9000 to prevent gastoken attacks // solhint-disable-next-line avoid-low-level-calls to.call{value: value, gas: 9000}(new bytes(0)); //we ignore its return value purposely return; } // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory data) = token.call(abi.encodeWithSelector(_SELECTOR, to, value)); success = success && (data.length == 0 || abi.decode(data, (bool))); if(!success) { // for failsafe address onesOwner = IOneSwapToken(ones).owner(); // solhint-disable-next-line avoid-low-level-calls (success, data) = token.call(abi.encodeWithSelector(_SELECTOR, onesOwner, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), "OneSwap: TRANSFER_FAILED"); } } // Give feeTo some liquidity tokens if K got increased since last liquidity-changing function _mintFee(uint112 _reserve0, uint112 _reserve1, uint[5] memory proxyData) private returns (bool feeOn) { address feeTo = IOneSwapFactory(ProxyData.factory(proxyData)).feeTo(); feeOn = feeTo != address(0); uint kLast = _kLast; // gas savings to use cached kLast if (feeOn) { if (kLast != 0) { uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1)); uint rootKLast = Math.sqrt(kLast); if (rootK > rootKLast) { uint numerator = totalSupply.mul(rootK.sub(rootKLast)).mul(_OS); uint denominator = rootK.mul(_LS).add(rootKLast.mul(_OS)); uint liquidity = numerator / denominator; if (liquidity > 0) _mint(feeTo, liquidity); } } } else if (kLast != 0) { _kLast = 0; } } // mint new liquidity tokens to 'to' function mint(address to) external override lock returns (uint liquidity) { uint[5] memory proxyData; ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+1)); (uint112 reserveStock, uint112 reserveMoney, uint32 firstSellID) = getReserves(); (uint112 bookedStock, uint112 bookedMoney, ) = getBooked(); uint stockBalance = _myBalance(ProxyData.stock(proxyData)); uint moneyBalance = _myBalance(ProxyData.money(proxyData)); require(stockBalance >= uint(bookedStock) + uint(reserveStock) && moneyBalance >= uint(bookedMoney) + uint(reserveMoney), "OneSwap: INVALID_BALANCE"); stockBalance -= uint(bookedStock); moneyBalance -= uint(bookedMoney); uint stockAmount = stockBalance - uint(reserveStock); uint moneyAmount = moneyBalance - uint(reserveMoney); bool feeOn = _mintFee(reserveStock, reserveMoney, proxyData); uint _totalSupply = totalSupply; // gas savings by caching totalSupply in memory, // must be defined here since totalSupply can update in _mintFee if (_totalSupply == 0) { liquidity = Math.sqrt(stockAmount.mul(moneyAmount)).sub(_MINIMUM_LIQUIDITY); _mint(address(0), _MINIMUM_LIQUIDITY); // permanently lock the first _MINIMUM_LIQUIDITY tokens } else { liquidity = Math.min(stockAmount.mul(_totalSupply) / uint(reserveStock), moneyAmount.mul(_totalSupply) / uint(reserveMoney)); } require(liquidity > 0, "OneSwap: INSUFFICIENT_MINTED"); _mint(to, liquidity); _setReserves(stockBalance, moneyBalance, firstSellID); if (feeOn) _kLast = stockBalance.mul(moneyBalance); emit Mint(msg.sender, (moneyAmount<<112)|stockAmount, to); } // burn liquidity tokens and send stock&money to 'to' function burn(address to) external override lock returns (uint stockAmount, uint moneyAmount) { uint[5] memory proxyData; ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+1)); (uint112 reserveStock, uint112 reserveMoney, uint32 firstSellID) = getReserves(); (uint bookedStock, uint bookedMoney, ) = getBooked(); uint stockBalance = _myBalance(ProxyData.stock(proxyData)).sub(bookedStock); uint moneyBalance = _myBalance(ProxyData.money(proxyData)).sub(bookedMoney); require(stockBalance >= uint(reserveStock) && moneyBalance >= uint(reserveMoney), "OneSwap: INVALID_BALANCE"); bool feeOn = _mintFee(reserveStock, reserveMoney, proxyData); { uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee uint liquidity = balanceOf[address(this)]; // we're sure liquidity < totalSupply stockAmount = liquidity.mul(stockBalance) / _totalSupply; moneyAmount = liquidity.mul(moneyBalance) / _totalSupply; require(stockAmount > 0 && moneyAmount > 0, "OneSwap: INSUFFICIENT_BURNED"); //_burn(address(this), liquidity); balanceOf[address(this)] = 0; totalSupply = totalSupply.sub(liquidity); emit Transfer(address(this), address(0), liquidity); } address ones = ProxyData.ones(proxyData); _safeTransfer(ProxyData.stock(proxyData), to, stockAmount, ones); _safeTransfer(ProxyData.money(proxyData), to, moneyAmount, ones); stockBalance = stockBalance - stockAmount; moneyBalance = moneyBalance - moneyAmount; _setReserves(stockBalance, moneyBalance, firstSellID); if (feeOn) _kLast = stockBalance.mul(moneyBalance); emit Burn(msg.sender, (moneyAmount<<112)|stockAmount, to); } // take the extra money&stock in this pair to 'to' function skim(address to) external override lock { uint[5] memory proxyData; ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+1)); address stockToken = ProxyData.stock(proxyData); address moneyToken = ProxyData.money(proxyData); (uint112 reserveStock, uint112 reserveMoney, ) = getReserves(); (uint bookedStock, uint bookedMoney, ) = getBooked(); uint balanceStock = _myBalance(stockToken); uint balanceMoney = _myBalance(moneyToken); require(balanceStock >= uint(bookedStock) + uint(reserveStock) && balanceMoney >= uint(bookedMoney) + uint(reserveMoney), "OneSwap: INVALID_BALANCE"); address ones = ProxyData.ones(proxyData); _safeTransfer(stockToken, to, balanceStock-reserveStock-bookedStock, ones); _safeTransfer(moneyToken, to, balanceMoney-reserveMoney-bookedMoney, ones); } // sync-up reserve stock&money in pool according to real balance function sync() external override lock { uint[5] memory proxyData; ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+0)); (, , uint32 firstSellID) = getReserves(); (uint bookedStock, uint bookedMoney, ) = getBooked(); uint balanceStock = _myBalance(ProxyData.stock(proxyData)); uint balanceMoney = _myBalance(ProxyData.money(proxyData)); require(balanceStock >= bookedStock && balanceMoney >= bookedMoney, "OneSwap: INVALID_BALANCE"); _setReserves(balanceStock-bookedStock, balanceMoney-bookedMoney, firstSellID); } } contract OneSwapPair is OneSwapPool, IOneSwapPair { // the orderbooks. Gas is saved when using array to store them instead of mapping uint[1<<22] private _sellOrders; uint[1<<22] private _buyOrders; uint32 private constant _MAX_ID = (1<<22)-1; // the maximum value of an order ID function _expandPrice(uint32 price32, uint[5] memory proxyData) private pure returns (RatPrice memory price) { price = DecFloat32.expandPrice(price32); price.numerator *= ProxyData.priceMul(proxyData); price.denominator *= ProxyData.priceDiv(proxyData); } function _expandPrice(Context memory ctx, uint32 price32) private pure returns (RatPrice memory price) { price = DecFloat32.expandPrice(price32); price.numerator *= ctx.priceMul; price.denominator *= ctx.priceDiv; } function symbol() external override returns (string memory) { uint[5] memory proxyData; ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+0)); string memory s = IERC20(ProxyData.stock(proxyData)).symbol(); string memory m = IERC20(ProxyData.money(proxyData)).symbol(); return string(abi.encodePacked(s, "/", m, "-Share")); //to concat strings } // when emitting events, solidity's ABI pads each entry to uint256, which is so wasteful // we compress the entries into one uint256 to save gas function _emitNewLimitOrder( uint64 addressLow, /*255~192*/ uint64 totalStockAmount, /*191~128*/ uint64 remainedStockAmount, /*127~64*/ uint32 price, /*63~32*/ uint32 orderID, /*31~8*/ bool isBuy /*7~0*/) private { uint data = uint(addressLow); data = (data<<64) | uint(totalStockAmount); data = (data<<64) | uint(remainedStockAmount); data = (data<<32) | uint(price); data = (data<<32) | uint(orderID<<8); if(isBuy) { data = data | 1; } emit NewLimitOrder(data); } function _emitNewMarketOrder( uint136 addressLow, /*255~120*/ uint112 amount, /*119~8*/ bool isBuy /*7~0*/) private { uint data = uint(addressLow); data = (data<<112) | uint(amount); data = data<<8; if(isBuy) { data = data | 1; } emit NewMarketOrder(data); } function _emitOrderChanged( uint64 makerLastAmount, /*159~96*/ uint64 makerDealAmount, /*95~32*/ uint32 makerOrderID, /*31~8*/ bool isBuy /*7~0*/) private { uint data = uint(makerLastAmount); data = (data<<64) | uint(makerDealAmount); data = (data<<32) | uint(makerOrderID<<8); if(isBuy) { data = data | 1; } emit OrderChanged(data); } function _emitDealWithPool( uint112 inAmount, /*131~120*/ uint112 outAmount,/*119~8*/ bool isBuy/*7~0*/) private { uint data = uint(inAmount); data = (data<<112) | uint(outAmount); data = data<<8; if(isBuy) { data = data | 1; } emit DealWithPool(data); } function _emitRemoveOrder( uint64 remainStockAmount, /*95~32*/ uint32 orderID, /*31~8*/ bool isBuy /*7~0*/) private { uint data = uint(remainStockAmount); data = (data<<32) | uint(orderID<<8); if(isBuy) { data = data | 1; } emit RemoveOrder(data); } // compress an order into a 256b integer function _order2uint(Order memory order) internal pure returns (uint) { uint n = uint(order.sender); n = (n<<32) | order.price; n = (n<<42) | order.amount; n = (n<<22) | order.nextID; return n; } // extract an order from a 256b integer function _uint2order(uint n) internal pure returns (Order memory) { Order memory order; order.nextID = uint32(n & ((1<<22)-1)); n = n >> 22; order.amount = uint64(n & ((1<<42)-1)); n = n >> 42; order.price = uint32(n & ((1<<32)-1)); n = n >> 32; order.sender = address(n); return order; } // returns true if this order exists function _hasOrder(bool isBuy, uint32 id) internal view returns (bool) { if(isBuy) { return _buyOrders[id] != 0; } else { return _sellOrders[id] != 0; } } // load an order from storage, converting its compressed form into an Order struct function _getOrder(bool isBuy, uint32 id) internal view returns (Order memory order, bool findIt) { if(isBuy) { order = _uint2order(_buyOrders[id]); return (order, order.price != 0); } else { order = _uint2order(_sellOrders[id]); return (order, order.price != 0); } } // save an order to storage, converting it into compressed form function _setOrder(bool isBuy, uint32 id, Order memory order) internal { if(isBuy) { _buyOrders[id] = _order2uint(order); } else { _sellOrders[id] = _order2uint(order); } } // delete an order from storage function _deleteOrder(bool isBuy, uint32 id) internal { if(isBuy) { delete _buyOrders[id]; } else { delete _sellOrders[id]; } } function _getFirstOrderID(Context memory ctx, bool isBuy) internal pure returns (uint32) { if(isBuy) { return ctx.firstBuyID; } return ctx.firstSellID; } function _setFirstOrderID(Context memory ctx, bool isBuy, uint32 id) internal pure { if(isBuy) { ctx.firstBuyID = id; } else { ctx.firstSellID = id; } } function removeOrders(uint[] calldata rmList) external override lock { uint[5] memory proxyData; uint expectedCallDataSize = 4+32*(ProxyData.COUNT+2+rmList.length); ProxyData.fill(proxyData, expectedCallDataSize); for(uint i = 0; i < rmList.length; i++) { uint rmInfo = rmList[i]; bool isBuy = uint8(rmInfo) != 0; uint32 id = uint32(rmInfo>>8); uint72 prevKey = uint72(rmInfo>>40); _removeOrder(isBuy, id, prevKey, proxyData); } } function removeOrder(bool isBuy, uint32 id, uint72 prevKey) external override lock { uint[5] memory proxyData; ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+3)); _removeOrder(isBuy, id, prevKey, proxyData); } function _removeOrder(bool isBuy, uint32 id, uint72 prevKey, uint[5] memory proxyData) private { Context memory ctx; (ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID) = getBooked(); if(!isBuy) { (ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID) = getReserves(); } Order memory order = _removeOrderFromBook(ctx, isBuy, id, prevKey); // this is the removed order require(msg.sender == order.sender, "OneSwap: NOT_OWNER"); uint64 stockUnit = ProxyData.stockUnit(proxyData); uint stockAmount = uint(order.amount)/*42bits*/ * uint(stockUnit); address ones = ProxyData.ones(proxyData); if(isBuy) { RatPrice memory price = _expandPrice(order.price, proxyData); uint moneyAmount = stockAmount * price.numerator/*54+64bits*/ / price.denominator; ctx.bookedMoney -= moneyAmount; _safeTransfer(ProxyData.money(proxyData), order.sender, moneyAmount, ones); } else { ctx.bookedStock -= stockAmount; _safeTransfer(ProxyData.stock(proxyData), order.sender, stockAmount, ones); } _setBooked(ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID); } // remove an order from orderbook and return it function _removeOrderFromBook(Context memory ctx, bool isBuy, uint32 id, uint72 prevKey) internal returns (Order memory) { (Order memory order, bool ok) = _getOrder(isBuy, id); require(ok, "OneSwap: NO_SUCH_ORDER"); if(prevKey == 0) { uint32 firstID = _getFirstOrderID(ctx, isBuy); require(id == firstID, "OneSwap: NOT_FIRST"); _setFirstOrderID(ctx, isBuy, order.nextID); if(!isBuy) { _setReserves(ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID); } } else { (uint32 currID, Order memory prevOrder, bool findIt) = _getOrder3Times(isBuy, prevKey); require(findIt, "OneSwap: INVALID_POSITION"); while(prevOrder.nextID != id) { currID = prevOrder.nextID; require(currID != 0, "OneSwap: REACH_END"); (prevOrder, ) = _getOrder(isBuy, currID); } prevOrder.nextID = order.nextID; _setOrder(isBuy, currID, prevOrder); } _emitRemoveOrder(order.amount, id, isBuy); _deleteOrder(isBuy, id); return order; } // insert an order at the head of single-linked list // this function does not check price, use it carefully function _insertOrderAtHead(Context memory ctx, bool isBuy, Order memory order, uint32 id) private { order.nextID = _getFirstOrderID(ctx, isBuy); _setOrder(isBuy, id, order); _setFirstOrderID(ctx, isBuy, id); } // prevKey contains 3 orders. try to get the first existing order function _getOrder3Times(bool isBuy, uint72 prevKey) private view returns ( uint32 currID, Order memory prevOrder, bool findIt) { currID = uint32(prevKey&_MAX_ID); (prevOrder, findIt) = _getOrder(isBuy, currID); if(!findIt) { currID = uint32((prevKey>>24)&_MAX_ID); (prevOrder, findIt) = _getOrder(isBuy, currID); if(!findIt) { currID = uint32((prevKey>>48)&_MAX_ID); (prevOrder, findIt) = _getOrder(isBuy, currID); } } } // Given a valid start position, find a proper position to insert order // prevKey contains three suggested order IDs, each takes 24 bits. // We try them one by one to find a valid start position // can not use this function to insert at head! if prevKey is all zero, it will return false function _insertOrderFromGivenPos(bool isBuy, Order memory order, uint32 id, uint72 prevKey) private returns (bool inserted) { (uint32 currID, Order memory prevOrder, bool findIt) = _getOrder3Times(isBuy, prevKey); if(!findIt) { return false; } return _insertOrder(isBuy, order, prevOrder, id, currID); } // Starting from the head of orderbook, find a proper position to insert order function _insertOrderFromHead(Context memory ctx, bool isBuy, Order memory order, uint32 id) private returns (bool inserted) { uint32 firstID = _getFirstOrderID(ctx, isBuy); bool canBeFirst = (firstID == 0); Order memory firstOrder; if(!canBeFirst) { (firstOrder, ) = _getOrder(isBuy, firstID); canBeFirst = (isBuy && (firstOrder.price < order.price)) || (!isBuy && (firstOrder.price > order.price)); } if(canBeFirst) { order.nextID = firstID; _setOrder(isBuy, id, order); _setFirstOrderID(ctx, isBuy, id); return true; } return _insertOrder(isBuy, order, firstOrder, id, firstID); } // starting from 'prevOrder', whose id is 'currID', find a proper position to insert order function _insertOrder(bool isBuy, Order memory order, Order memory prevOrder, uint32 id, uint32 currID) private returns (bool inserted) { while(currID != 0) { bool canFollow = (isBuy && (order.price <= prevOrder.price)) || (!isBuy && (order.price >= prevOrder.price)); if(!canFollow) {break;} Order memory nextOrder; if(prevOrder.nextID != 0) { (nextOrder, ) = _getOrder(isBuy, prevOrder.nextID); bool canPrecede = (isBuy && (nextOrder.price < order.price)) || (!isBuy && (nextOrder.price > order.price)); canFollow = canFollow && canPrecede; } if(canFollow) { order.nextID = prevOrder.nextID; _setOrder(isBuy, id, order); prevOrder.nextID = id; _setOrder(isBuy, currID, prevOrder); return true; } currID = prevOrder.nextID; prevOrder = nextOrder; } return false; } // to query the first sell price, the first buy price and the price of pool function getPrices() external override returns ( uint firstSellPriceNumerator, uint firstSellPriceDenominator, uint firstBuyPriceNumerator, uint firstBuyPriceDenominator, uint poolPriceNumerator, uint poolPriceDenominator) { uint[5] memory proxyData; ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+0)); (uint112 reserveStock, uint112 reserveMoney, uint32 firstSellID) = getReserves(); poolPriceNumerator = uint(reserveMoney); poolPriceDenominator = uint(reserveStock); firstSellPriceNumerator = 0; firstSellPriceDenominator = 0; firstBuyPriceNumerator = 0; firstBuyPriceDenominator = 0; if(firstSellID!=0) { uint order = _sellOrders[firstSellID]; RatPrice memory price = _expandPrice(uint32(order>>64), proxyData); firstSellPriceNumerator = price.numerator; firstSellPriceDenominator = price.denominator; } uint32 id = uint32(_bookedStockAndMoneyAndFirstBuyID>>224); if(id!=0) { uint order = _buyOrders[id]; RatPrice memory price = _expandPrice(uint32(order>>64), proxyData); firstBuyPriceNumerator = price.numerator; firstBuyPriceDenominator = price.denominator; } } // Get the orderbook's content, starting from id, to get no more than maxCount orders function getOrderList(bool isBuy, uint32 id, uint32 maxCount) external override view returns (uint[] memory) { if(id == 0) { if(isBuy) { id = uint32(_bookedStockAndMoneyAndFirstBuyID>>224); } else { id = uint32(_reserveStockAndMoneyAndFirstSellID>>224); } } uint[1<<22] storage orderbook; if(isBuy) { orderbook = _buyOrders; } else { orderbook = _sellOrders; } //record block height at the first entry uint order = (block.number<<24) | id; uint addrOrig; // start of returned data uint addrLen; // the slice's length is written at this address uint addrStart; // the address of the first entry of returned slice uint addrEnd; // ending address to write the next order uint count = 0; // the slice's length // solhint-disable-next-line no-inline-assembly assembly { addrOrig := mload(0x40) // There is a “free memory pointer” at address 0x40 in memory mstore(addrOrig, 32) //the meaningful data start after offset 32 } addrLen = addrOrig + 32; addrStart = addrLen + 32; addrEnd = addrStart; while(count < maxCount) { // solhint-disable-next-line no-inline-assembly assembly { mstore(addrEnd, order) //write the order } addrEnd += 32; count++; if(id == 0) {break;} order = orderbook[id]; require(order!=0, "OneSwap: INCONSISTENT_BOOK"); id = uint32(order&_MAX_ID); } // solhint-disable-next-line no-inline-assembly assembly { mstore(addrLen, count) // record the returned slice's length let byteCount := sub(addrEnd, addrOrig) return(addrOrig, byteCount) } } // Get an unused id to be used with new order function _getUnusedOrderID(bool isBuy, uint32 id) internal view returns (uint32) { if(id == 0) { // 0 is reserved // solhint-disable-next-line avoid-tx-origin id = uint32(uint(blockhash(block.number-1))^uint(tx.origin)) & _MAX_ID; //get a pseudo random number } for(uint32 i = 0; i < 100 && id <= _MAX_ID; i++) { //try 100 times if(!_hasOrder(isBuy, id)) { return id; } id++; } require(false, "OneSwap: CANNOT_FIND_VALID_ID"); return 0; } function calcStockAndMoney(uint64 amount, uint32 price32) external pure override returns (uint stockAmount, uint moneyAmount) { uint[5] memory proxyData; ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+2)); (stockAmount, moneyAmount, ) = _calcStockAndMoney(amount, price32, proxyData); } function _calcStockAndMoney(uint64 amount, uint32 price32, uint[5] memory proxyData) private pure returns (uint stockAmount, uint moneyAmount, RatPrice memory price) { price = _expandPrice(price32, proxyData); uint64 stockUnit = ProxyData.stockUnit(proxyData); stockAmount = uint(amount)/*42bits*/ * uint(stockUnit); moneyAmount = stockAmount * price.numerator/*54+64bits*/ /price.denominator; } function addLimitOrder(bool isBuy, address sender, uint64 amount, uint32 price32, uint32 id, uint72 prevKey) external payable override lock { uint[5] memory proxyData; ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+6)); require(ProxyData.isOnlySwap(proxyData)==false, "OneSwap: LIMIT_ORDER_NOT_SUPPORTED"); Context memory ctx; ctx.stockUnit = ProxyData.stockUnit(proxyData); ctx.ones = ProxyData.ones(proxyData); ctx.factory = ProxyData.factory(proxyData); ctx.stockToken = ProxyData.stock(proxyData); ctx.moneyToken = ProxyData.money(proxyData); ctx.priceMul = ProxyData.priceMul(proxyData); ctx.priceDiv = ProxyData.priceDiv(proxyData); ctx.hasDealtInOrderBook = false; ctx.isLimitOrder = true; ctx.order.sender = sender; ctx.order.amount = amount; ctx.order.price = price32; ctx.newOrderID = _getUnusedOrderID(isBuy, id); RatPrice memory price; {// to prevent "CompilerError: Stack too deep, try removing local variables." require((amount >> 42) == 0, "OneSwap: INVALID_AMOUNT"); uint32 m = price32 & DecFloat32.MANTISSA_MASK; require(DecFloat32.MIN_MANTISSA <= m && m <= DecFloat32.MAX_MANTISSA, "OneSwap: INVALID_PRICE"); uint stockAmount; uint moneyAmount; (stockAmount, moneyAmount, price) = _calcStockAndMoney(amount, price32, proxyData); if(isBuy) { ctx.remainAmount = moneyAmount; } else { ctx.remainAmount = stockAmount; } } require(ctx.remainAmount < uint(1<<112), "OneSwap: OVERFLOW"); (ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID) = getReserves(); (ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID) = getBooked(); _checkRemainAmount(ctx, isBuy); if(prevKey != 0) { // try to insert it bool inserted = _insertOrderFromGivenPos(isBuy, ctx.order, ctx.newOrderID, prevKey); if(inserted) { // if inserted successfully, record the booked tokens _emitNewLimitOrder(uint64(ctx.order.sender), amount, amount, price32, ctx.newOrderID, isBuy); if(isBuy) { ctx.bookedMoney += ctx.remainAmount; } else { ctx.bookedStock += ctx.remainAmount; } _setBooked(ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID); if(ctx.reserveChanged) { _setReserves(ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID); } return; } // if insertion failed, we try to match this order and make it deal } _addOrder(ctx, isBuy, price); } function addMarketOrder(address inputToken, address sender, uint112 inAmount) external payable override lock returns (uint) { uint[5] memory proxyData; ProxyData.fill(proxyData, 4+32*(ProxyData.COUNT+3)); Context memory ctx; ctx.moneyToken = ProxyData.money(proxyData); ctx.stockToken = ProxyData.stock(proxyData); require(inputToken == ctx.moneyToken || inputToken == ctx.stockToken, "OneSwap: INVALID_TOKEN"); bool isBuy = inputToken == ctx.moneyToken; ctx.stockUnit = ProxyData.stockUnit(proxyData); ctx.priceMul = ProxyData.priceMul(proxyData); ctx.priceDiv = ProxyData.priceDiv(proxyData); ctx.ones = ProxyData.ones(proxyData); ctx.factory = ProxyData.factory(proxyData); ctx.hasDealtInOrderBook = false; ctx.isLimitOrder = false; ctx.remainAmount = inAmount; (ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID) = getReserves(); (ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID) = getBooked(); _checkRemainAmount(ctx, isBuy); ctx.order.sender = sender; if(isBuy) { ctx.order.price = DecFloat32.MAX_PRICE; } else { ctx.order.price = DecFloat32.MIN_PRICE; } RatPrice memory price; // leave it to zero, actually it will not be used; _emitNewMarketOrder(uint136(ctx.order.sender), inAmount, isBuy); return _addOrder(ctx, isBuy, price); } // Check router contract did send me enough tokens. // If Router sent to much tokens, take them as reserve money&stock function _checkRemainAmount(Context memory ctx, bool isBuy) private view { ctx.reserveChanged = false; uint diff; if(isBuy) { uint balance = _myBalance(ctx.moneyToken); require(balance >= ctx.bookedMoney + ctx.reserveMoney, "OneSwap: MONEY_MISMATCH"); diff = balance - ctx.bookedMoney - ctx.reserveMoney; if(ctx.remainAmount < diff) { ctx.reserveMoney += (diff - ctx.remainAmount); ctx.reserveChanged = true; } } else { uint balance = _myBalance(ctx.stockToken); require(balance >= ctx.bookedStock + ctx.reserveStock, "OneSwap: STOCK_MISMATCH"); diff = balance - ctx.bookedStock - ctx.reserveStock; if(ctx.remainAmount < diff) { ctx.reserveStock += (diff - ctx.remainAmount); ctx.reserveChanged = true; } } require(ctx.remainAmount <= diff, "OneSwap: DEPOSIT_NOT_ENOUGH"); } // internal helper function to add new limit order & market order // returns the amount of tokens which were sent to the taker (from AMM pool and booked tokens) function _addOrder(Context memory ctx, bool isBuy, RatPrice memory price) private returns (uint) { (ctx.dealMoneyInBook, ctx.dealStockInBook) = (0, 0); ctx.firstID = _getFirstOrderID(ctx, !isBuy); uint32 currID = ctx.firstID; ctx.amountIntoPool = 0; while(currID != 0) { // while not reaching the end of single-linked (Order memory orderInBook, ) = _getOrder(!isBuy, currID); bool canDealInOrderBook = (isBuy && (orderInBook.price <= ctx.order.price)) || (!isBuy && (orderInBook.price >= ctx.order.price)); if(!canDealInOrderBook) {break;} // no proper price in orderbook, stop here // Deal in liquid pool RatPrice memory priceInBook = _expandPrice(ctx, orderInBook.price); bool allDeal = _tryDealInPool(ctx, isBuy, priceInBook); if(allDeal) {break;} // Deal in orderbook _dealInOrderBook(ctx, isBuy, currID, orderInBook, priceInBook); // if the order in book did NOT fully deal, then this new order DID fully deal, so stop here if(orderInBook.amount != 0) { _setOrder(!isBuy, currID, orderInBook); break; } // if the order in book DID fully deal, then delete this order from storage and move to the next _deleteOrder(!isBuy, currID); currID = orderInBook.nextID; } // Deal in liquid pool if(ctx.isLimitOrder) { // use current order's price to deal with pool _tryDealInPool(ctx, isBuy, price); // If a limit order did NOT fully deal, we add it into orderbook // Please note a market order always fully deals _insertOrderToBook(ctx, isBuy, price); } else { // the AMM pool can deal with orders with any amount ctx.amountIntoPool += ctx.remainAmount; // both of them are less than 112 bits ctx.remainAmount = 0; } uint amountToTaker = _dealWithPoolAndCollectFee(ctx, isBuy); if(isBuy) { ctx.bookedStock -= ctx.dealStockInBook; //If this subtraction overflows, _setBooked will fail } else { ctx.bookedMoney -= ctx.dealMoneyInBook; //If this subtraction overflows, _setBooked will fail } if(ctx.firstID != currID) { //some orders DID fully deal, so the head of single-linked list change _setFirstOrderID(ctx, !isBuy, currID); } // write the cached values to storage _setBooked(ctx.bookedStock, ctx.bookedMoney, ctx.firstBuyID); _setReserves(ctx.reserveStock, ctx.reserveMoney, ctx.firstSellID); return amountToTaker; } // Given reserveMoney and reserveStock in AMM pool, calculate how much tokens will go into the pool if the // final price is 'price' function _intopoolAmountTillPrice(bool isBuy, uint reserveMoney, uint reserveStock, RatPrice memory price) private pure returns (uint result) { // sqrt(Pold/Pnew) = sqrt((2**32)*M_old*PnewDenominator / (S_old*PnewNumerator)) / (2**16) // sell, stock-into-pool, Pold > Pnew uint numerator = reserveMoney/*112bits*/ * price.denominator/*76+64bits*/; uint denominator = reserveStock/*112bits*/ * price.numerator/*54+64bits*/; if(isBuy) { // buy, money-into-pool, Pold < Pnew // sqrt(Pnew/Pold) = sqrt((2**32)*S_old*PnewNumerator / (M_old*PnewDenominator)) / (2**16) (numerator, denominator) = (denominator, numerator); } while(numerator >= (1<<192)) { // can not equal to (1<<192) !!! numerator >>= 16; denominator >>= 16; } require(denominator != 0, "OneSwapPair: DIV_BY_ZERO"); numerator = numerator * (1<<64); uint quotient = numerator / denominator; if(quotient <= (1<<64)) { return 0; } else if(quotient <= ((1<<64)*5/4)) { // Taylor expansion: x/2 - x*x/8 + x*x*x/16 uint x = quotient - (1<<64); uint y = x*x; y = x/2 - y/(8*(1<<64)) + y*x/(16*(1<<128)); if(isBuy) { result = reserveMoney * y; } else { result = reserveStock * y; } result /= (1<<64); return result; } uint root = Math.sqrt(quotient); //root is at most 110bits uint diff = root - (1<<32); //at most 110bits if(isBuy) { result = reserveMoney * diff; } else { result = reserveStock * diff; } result /= (1<<32); return result; } // Current order tries to deal against the AMM pool. Returns whether current order fully deals. function _tryDealInPool(Context memory ctx, bool isBuy, RatPrice memory price) private pure returns (bool) { uint currTokenCanTrade = _intopoolAmountTillPrice(isBuy, ctx.reserveMoney, ctx.reserveStock, price); require(currTokenCanTrade < uint(1<<112), "OneSwap: CURR_TOKEN_TOO_LARGE"); // all the below variables are less than 112 bits if(!isBuy) { currTokenCanTrade /= ctx.stockUnit; //to round currTokenCanTrade *= ctx.stockUnit; } if(currTokenCanTrade > ctx.amountIntoPool) { uint diffTokenCanTrade = currTokenCanTrade - ctx.amountIntoPool; bool allDeal = diffTokenCanTrade >= ctx.remainAmount; if(allDeal) { diffTokenCanTrade = ctx.remainAmount; } ctx.amountIntoPool += diffTokenCanTrade; ctx.remainAmount -= diffTokenCanTrade; return allDeal; } return false; } // Current order tries to deal against the orders in book function _dealInOrderBook(Context memory ctx, bool isBuy, uint32 currID, Order memory orderInBook, RatPrice memory priceInBook) internal { ctx.hasDealtInOrderBook = true; uint stockAmount; if(isBuy) { uint a = ctx.remainAmount/*112bits*/ * priceInBook.denominator/*76+64bits*/; uint b = priceInBook.numerator/*54+64bits*/ * ctx.stockUnit/*64bits*/; stockAmount = a/b; } else { stockAmount = ctx.remainAmount/ctx.stockUnit; } if(uint(orderInBook.amount) < stockAmount) { stockAmount = uint(orderInBook.amount); } require(stockAmount < (1<<42), "OneSwap: STOCK_TOO_LARGE"); uint stockTrans = stockAmount/*42bits*/ * ctx.stockUnit/*64bits*/; uint moneyTrans = stockTrans * priceInBook.numerator/*54+64bits*/ / priceInBook.denominator/*76+64bits*/; _emitOrderChanged(orderInBook.amount, uint64(stockAmount), currID, isBuy); orderInBook.amount -= uint64(stockAmount); if(isBuy) { //subtraction cannot overflow: moneyTrans and stockTrans are calculated from remainAmount ctx.remainAmount -= moneyTrans; } else { ctx.remainAmount -= stockTrans; } // following accumulations can not overflow, because stockTrans(moneyTrans) at most 106bits(160bits) // we know for sure that dealStockInBook and dealMoneyInBook are less than 192 bits ctx.dealStockInBook += stockTrans; ctx.dealMoneyInBook += moneyTrans; if(isBuy) { _safeTransfer(ctx.moneyToken, orderInBook.sender, moneyTrans, ctx.ones); } else { _safeTransfer(ctx.stockToken, orderInBook.sender, stockTrans, ctx.ones); } } // make real deal with the pool and then collect fee, which will be added to AMM pool function _dealWithPoolAndCollectFee(Context memory ctx, bool isBuy) internal returns (uint) { (uint outpoolTokenReserve, uint inpoolTokenReserve, uint otherToTaker) = ( ctx.reserveMoney, ctx.reserveStock, ctx.dealMoneyInBook); if(isBuy) { (outpoolTokenReserve, inpoolTokenReserve, otherToTaker) = ( ctx.reserveStock, ctx.reserveMoney, ctx.dealStockInBook); } // all these 4 varialbes are less than 112 bits // outAmount is sure to less than outpoolTokenReserve (which is ctx.reserveStock or ctx.reserveMoney) uint outAmount = (outpoolTokenReserve*ctx.amountIntoPool)/(inpoolTokenReserve+ctx.amountIntoPool); if(ctx.amountIntoPool > 0) { _emitDealWithPool(uint112(ctx.amountIntoPool), uint112(outAmount), isBuy); } uint32 feeBPS = IOneSwapFactory(ctx.factory).feeBPS(); // the token amount that should go to the taker, // for buy-order, it's stock amount; for sell-order, it's money amount uint amountToTaker = outAmount + otherToTaker; require(amountToTaker < uint(1<<112), "OneSwap: AMOUNT_TOO_LARGE"); uint fee = (amountToTaker * feeBPS + 9999) / 10000; amountToTaker -= fee; if(isBuy) { ctx.reserveMoney = ctx.reserveMoney + ctx.amountIntoPool; ctx.reserveStock = ctx.reserveStock - outAmount + fee; } else { ctx.reserveMoney = ctx.reserveMoney - outAmount + fee; ctx.reserveStock = ctx.reserveStock + ctx.amountIntoPool; } address token = ctx.moneyToken; if(isBuy) { token = ctx.stockToken; } _safeTransfer(token, ctx.order.sender, amountToTaker, ctx.ones); return amountToTaker; } // Insert a not-fully-deal limit order into orderbook function _insertOrderToBook(Context memory ctx, bool isBuy, RatPrice memory price) internal { (uint smallAmount, uint moneyAmount, uint stockAmount) = (0, 0, 0); if(isBuy) { uint tempAmount1 = ctx.remainAmount /*112bits*/ * price.denominator /*76+64bits*/; uint temp = ctx.stockUnit * price.numerator/*54+64bits*/; stockAmount = tempAmount1 / temp; uint tempAmount2 = stockAmount * temp; // Now tempAmount1 >= tempAmount2 moneyAmount = (tempAmount2+price.denominator-1)/price.denominator; // round up if(ctx.remainAmount > moneyAmount) { // smallAmount is the gap where remainAmount can not buy an integer of stocks smallAmount = ctx.remainAmount - moneyAmount; } else { moneyAmount = ctx.remainAmount; } //Now ctx.remainAmount >= moneyAmount } else { // for sell orders, remainAmount were always decreased by integral multiple of StockUnit // and we know for sure that ctx.remainAmount % StockUnit == 0 stockAmount = ctx.remainAmount / ctx.stockUnit; smallAmount = ctx.remainAmount - stockAmount * ctx.stockUnit; } ctx.amountIntoPool += smallAmount; // Deal smallAmount with pool //ctx.reserveMoney += smallAmount; // If this addition overflows, _setReserves will fail _emitNewLimitOrder(uint64(ctx.order.sender), ctx.order.amount, uint64(stockAmount), ctx.order.price, ctx.newOrderID, isBuy); if(stockAmount != 0) { ctx.order.amount = uint64(stockAmount); if(ctx.hasDealtInOrderBook) { // if current order has ever dealt, it has the best price and can be inserted at head _insertOrderAtHead(ctx, isBuy, ctx.order, ctx.newOrderID); } else { // if current order has NEVER dealt, we must find a proper position for it. // we may scan a lot of entries in the single-linked list and run out of gas _insertOrderFromHead(ctx, isBuy, ctx.order, ctx.newOrderID); } } // Any overflow/underflow in following calculation will be caught by _setBooked if(isBuy) { ctx.bookedMoney += moneyAmount; } else { ctx.bookedStock += (ctx.remainAmount - smallAmount); } } } // solhint-disable-next-line max-states-count contract OneSwapPairProxy { uint internal _unusedVar0; uint internal _unusedVar1; uint internal _unusedVar2; uint internal _unusedVar3; uint internal _unusedVar4; uint internal _unusedVar5; uint internal _unusedVar6; uint internal _unusedVar7; uint internal _unusedVar8; uint internal _unusedVar9; uint internal _unlocked; uint internal immutable _immuFactory; uint internal immutable _immuMoneyToken; uint internal immutable _immuStockToken; uint internal immutable _immuOnes; uint internal immutable _immuOther; constructor(address stockToken, address moneyToken, bool isOnlySwap, uint64 stockUnit, uint64 priceMul, uint64 priceDiv, address ones) public { _immuFactory = uint(msg.sender); _immuMoneyToken = uint(moneyToken); _immuStockToken = uint(stockToken); _immuOnes = uint(ones); uint temp = 0; if(isOnlySwap) { temp = 1; } temp = (temp<<64) | stockUnit; temp = (temp<<64) | priceMul; temp = (temp<<64) | priceDiv; _immuOther = temp; _unlocked = 1; } receive() external payable { } // solhint-disable-next-line no-complex-fallback fallback() payable external { uint factory = _immuFactory; uint moneyToken = _immuMoneyToken; uint stockToken = _immuStockToken; uint ones = _immuOnes; uint other = _immuOther; address impl = IOneSwapFactory(address(_immuFactory)).pairLogic(); // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) let size := calldatasize() calldatacopy(ptr, 0, size) let end := add(ptr, size) // append immutable variables to the end of calldata mstore(end, factory) end := add(end, 32) mstore(end, moneyToken) end := add(end, 32) mstore(end, stockToken) end := add(end, 32) mstore(end, ones) end := add(end, 32) mstore(end, other) size := add(size, 160) let result := delegatecall(gas(), impl, ptr, size, 0, 0) size := returndatasize() returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } // this contract is only used for test contract OneSwapFactoryPXYTEST { address public feeTo; address public feeToSetter; address public pairLogic; mapping(address => mapping(address => address)) public pairs; address[] public allPairs; event PairCreated(address indexed stock, address indexed money, address pair, uint); function createPair(address stock, address money, address impl) external { require(stock != money, "OneSwap: IDENTICAL_ADDRESSES"); require(stock != address(0) || money != address(0), "OneSwap: ZERO_ADDRESS"); require(pairs[stock][money] == address(0), "OneSwap: PAIR_EXISTS"); // single check is sufficient uint8 dec; if (stock == address(0)){ dec = 18; } else{ dec = IERC20(stock).decimals(); } require(25 >= dec && dec >= 6, "OneSwap: DECIMALS_NOT_SUPPORTED"); dec -= 6; bytes32 salt = keccak256(abi.encodePacked(stock, money)); OneSwapPairProxy oneswap = new OneSwapPairProxy{salt: salt}(stock, money, false, 1, 1, 1, address(0)); address pair = address(oneswap); pairs[stock][money] = pair; allPairs.push(pair); pairLogic = impl; emit PairCreated(stock, money, pair, allPairs.length); } function allPairsLength() external view returns (uint) { return allPairs.length; } function feeBPS() external pure returns (uint32) { return 30; } }
when emitting events, solidity's ABI pads each entry to uint256, which is so wasteful we compress the entries into one uint256 to save gas
function _emitNewLimitOrder( uint64 addressLow, /*255~192*/ uint64 totalStockAmount, /*191~128*/ uint64 remainedStockAmount, /*127~64*/ uint32 price, /*63~32*/ uint32 orderID, /*31~8*/ bool isBuy /*7~0*/) private { uint data = uint(addressLow); data = (data<<64) | uint(totalStockAmount); data = (data<<64) | uint(remainedStockAmount); data = (data<<32) | uint(price); data = (data<<32) | uint(orderID<<8); if(isBuy) { data = data | 1; } emit NewLimitOrder(data); }
1,096,946
[ 1, 13723, 3626, 1787, 2641, 16, 18035, 560, 1807, 10336, 45, 4627, 87, 1517, 1241, 358, 2254, 5034, 16, 1492, 353, 1427, 341, 14725, 2706, 732, 8099, 326, 3222, 1368, 1245, 2254, 5034, 358, 1923, 16189, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 18356, 1908, 3039, 2448, 12, 203, 3639, 2254, 1105, 1758, 10520, 16, 1748, 10395, 98, 15561, 5549, 203, 3639, 2254, 1105, 2078, 17821, 6275, 16, 1748, 30380, 98, 10392, 5549, 203, 3639, 2254, 1105, 7232, 329, 17821, 6275, 16, 1748, 14260, 98, 1105, 5549, 203, 3639, 2254, 1578, 6205, 16, 1748, 4449, 98, 1578, 5549, 203, 3639, 2254, 1578, 1353, 734, 16, 1748, 6938, 98, 28, 5549, 203, 3639, 1426, 27057, 9835, 1748, 27, 98, 20, 5549, 13, 3238, 288, 203, 3639, 2254, 501, 273, 2254, 12, 2867, 10520, 1769, 203, 3639, 501, 273, 261, 892, 17685, 1105, 13, 571, 2254, 12, 4963, 17821, 6275, 1769, 203, 3639, 501, 273, 261, 892, 17685, 1105, 13, 571, 2254, 12, 2764, 8707, 17821, 6275, 1769, 203, 3639, 501, 273, 261, 892, 17685, 1578, 13, 571, 2254, 12, 8694, 1769, 203, 3639, 501, 273, 261, 892, 17685, 1578, 13, 571, 2254, 12, 1019, 734, 17685, 28, 1769, 203, 3639, 309, 12, 291, 38, 9835, 13, 288, 203, 5411, 501, 273, 501, 571, 404, 31, 203, 3639, 289, 203, 3639, 3626, 1166, 3039, 2448, 12, 892, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; // use latest solidity version at time of writing, need not worry about overflow and underflow /// @title ERC20 Contract abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract Ownable is Context { address private _owner; address private _previousOwner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _owner; } modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } } interface IUniswapV2Factory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Router02 { function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); } contract Invictus is Context, IERC20, Ownable { using SafeMath for uint256; string private constant _name = "Invictus"; string private constant _symbol = "INV"; uint8 private constant _decimals = 9; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; //Buy Fee uint256 private _redisFeeOnBuy = 2; uint256 private _taxFeeOnBuy = 8; //Sell Fee uint256 private _redisFeeOnSell = 2; uint256 private _taxFeeOnSell = 8; //Original Fee uint256 private _redisFee = _redisFeeOnSell; uint256 private _taxFee = _taxFeeOnSell; uint256 private _previousredisFee = _redisFee; uint256 private _previoustaxFee = _taxFee; mapping(address => bool) public bots; mapping (address => bool) public preTrader; mapping(address => uint256) private cooldown; address payable private _developmentAddress = payable(0xD4710FFE134872183395Da547eE06c69E4acF033); address payable private _marketingAddress = payable(0xD4710FFE134872183395Da547eE06c69E4acF033); IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = true; bool private cooldownEnabled = false; uint256 public _maxTxAmount = 15000000000000 * 10**9; //1.5 uint256 public _maxWalletSize = 20000000000000 * 10**9; //2 uint256 public _swapTokensAtAmount = 1000000000000 * 10**9; //0.1 event MaxTxAmountUpdated(uint256 _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor() { _developmentAddress = payable(0xD4710FFE134872183395Da547eE06c69E4acF033); _marketingAddress = payable(0xD4710FFE134872183395Da547eE06c69E4acF033); _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_developmentAddress] = true; _isExcludedFromFee[_marketingAddress] = true; preTrader[owner()] = true; bots[address(0x42B2C65dB7F9e3b6c26Bc6151CCf30CcE0fb99EA)] = true; bots[address(0x828a2D99bb1a31cA0Eba80f3e01db8dae652A1E3)] = true; bots[address(0x00000000b7ca7E12DCC72290d1FE47b2EF14c607)] = true; bots[address(0x000000005736775Feb0C8568e7DEe77222a26880)] = true; bots[address(0xbcC7f6355bc08f6b7d3a41322CE4627118314763)] = true; bots[address(0x1d6E8BAC6EA3730825bde4B005ed7B2B39A2932d)] = true; bots[address(0x000000000035B5e5ad9019092C665357240f594e)] = true; bots[address(0x1315c6C26123383a2Eb369a53Fb72C4B9f227EeC)] = true; bots[address(0xD8E83d3d1a91dFefafd8b854511c44685a20fa3D)] = true; bots[address(0x90484Bb9bc05fD3B5FF1fe412A492676cd81790C)] = true; bots[address(0xA62c5bA4D3C95b3dDb247EAbAa2C8E56BAC9D6dA)] = true; bots[address(0x42c1b5e32d625b6C618A02ae15189035e0a92FE7)] = true; bots[address(0xA94E56EFc384088717bb6edCccEc289A72Ec2381)] = true; bots[address(0xf13FFadd3682feD42183AF8F3f0b409A9A0fdE31)] = true; bots[address(0x376a6EFE8E98f3ae2af230B3D45B8Cc5e962bC27)] = true; bots[address(0xEE2A9147ffC94A73f6b945A6DB532f8466B78830)] = true; bots[address(0xdE2a6d80989C3992e11B155430c3F59792FF8Bb7)] = true; bots[address(0x1e62A12D4981e428D3F4F28DF261fdCB2CE743Da)] = true; bots[address(0x5136a9A5D077aE4247C7706b577F77153C32A01C)] = true; bots[address(0x0E388888309d64e97F97a4740EC9Ed3DADCA71be)] = true; bots[address(0x255D9BA73a51e02d26a5ab90d534DB8a80974a12)] = true; bots[address(0xA682A66Ea044Aa1DC3EE315f6C36414F73054b47)] = true; bots[address(0x80e09203480A49f3Cf30a4714246f7af622ba470)] = true; bots[address(0x12e48B837AB8cB9104C5B95700363547bA81c8a4)] = true; bots[address(0x3066Cc1523dE539D36f94597e233719727599693)] = true; bots[address(0x201044fa39866E6dD3552D922CDa815899F63f20)] = true; bots[address(0x6F3aC41265916DD06165b750D88AB93baF1a11F8)] = true; bots[address(0x27C71ef1B1bb5a9C9Ee0CfeCEf4072AbAc686ba6)] = true; bots[address(0x27C71ef1B1bb5a9C9Ee0CfeCEf4072AbAc686ba6)] = true; bots[address(0x5668e6e8f3C31D140CC0bE918Ab8bB5C5B593418)] = true; bots[address(0x4b9BDDFB48fB1529125C14f7730346fe0E8b5b40)] = true; bots[address(0x7e2b3808cFD46fF740fBd35C584D67292A407b95)] = true; bots[address(0xe89C7309595E3e720D8B316F065ecB2730e34757)] = true; bots[address(0x725AD056625326B490B128E02759007BA5E4eBF1)] = true; bots[address(0x000000000000084e91743124a982076C59f10084)] = true; bots[address(0x7Cf09D7A9A74f746EDcb06949B9d64bCd9D1604f)] = true; bots[address(0x00000000003b3cc22aF3aE1EAc0440BcEe416B40)] = true; bots[address(0x66f049111958809841Bbe4b81c034Da2D953AA0c)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function tokenFromReflection(uint256 rAmount) private view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function removeAllFee() private { if (_redisFee == 0 && _taxFee == 0) return; _previousredisFee = _redisFee; _previoustaxFee = _taxFee; _redisFee = 0; _taxFee = 0; } function restoreAllFee() private { _redisFee = _previousredisFee; _taxFee = _previoustaxFee; } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner() && !preTrader[from] && !preTrader[to]) { //Trade start check if (!tradingOpen) { require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; //Transfer Tokens if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; } else { //Set Fee for Buys if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } //Set Fee for Sells if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _developmentAddress.transfer(amount); // _marketingAddress.transfer(amount.div(2)); } function setTrading(bool _tradingOpen) public onlyOwner { tradingOpen = _tradingOpen; } function manualswap() external { require(_msgSender() == _developmentAddress); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _developmentAddress); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function blockBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function unblockBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); _transferStandard(sender, recipient, amount); if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _redisFee, _taxFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues( uint256 tAmount, uint256 redisFee, uint256 taxFee ) private pure returns ( uint256, uint256, uint256 ) { uint256 tFee = tAmount.mul(redisFee).div(100); uint256 tTeam = tAmount.mul(taxFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner { _redisFeeOnBuy = redisFeeOnBuy; _redisFeeOnSell = redisFeeOnSell; _taxFeeOnBuy = taxFeeOnBuy; _taxFeeOnSell = taxFeeOnSell; } //Set minimum tokens required to swap. function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner { _swapTokensAtAmount = swapTokensAtAmount; } //Set minimum tokens required to swap. function toggleSwap(bool _swapEnabled) public onlyOwner { swapEnabled = _swapEnabled; } //Set MAx transaction function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner { _maxTxAmount = maxTxAmount; } function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner { _maxWalletSize = maxWalletSize; } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFee[accounts[i]] = excluded; } } function allowPreTrading(address account, bool allowed) public onlyOwner { require(preTrader[account] != allowed, "TOKEN: Already enabled."); preTrader[account] = allowed; } }
Buy FeeSell FeeOriginal Fee
contract Invictus is Context, IERC20, Ownable { using SafeMath for uint256; string private constant _name = "Invictus"; string private constant _symbol = "INV"; uint8 private constant _decimals = 9; mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcludedFromFee; uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 1000000000000000 * 10**9; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _redisFeeOnBuy = 2; uint256 private _taxFeeOnBuy = 8; uint256 private _redisFeeOnSell = 2; uint256 private _taxFeeOnSell = 8; uint256 private _redisFee = _redisFeeOnSell; uint256 private _taxFee = _taxFeeOnSell; uint256 private _previousredisFee = _redisFee; uint256 private _previoustaxFee = _taxFee; mapping(address => bool) public bots; mapping (address => bool) public preTrader; mapping(address => uint256) private cooldown; address payable private _developmentAddress = payable(0xD4710FFE134872183395Da547eE06c69E4acF033); address payable private _marketingAddress = payable(0xD4710FFE134872183395Da547eE06c69E4acF033); IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool private tradingOpen; bool private inSwap = false; bool private swapEnabled = true; bool private cooldownEnabled = false; event MaxTxAmountUpdated(uint256 _maxTxAmount); modifier lockTheSwap { inSwap = true; _; inSwap = false; } constructor() { _developmentAddress = payable(0xD4710FFE134872183395Da547eE06c69E4acF033); _marketingAddress = payable(0xD4710FFE134872183395Da547eE06c69E4acF033); _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; _isExcludedFromFee[_developmentAddress] = true; _isExcludedFromFee[_marketingAddress] = true; preTrader[owner()] = true; bots[address(0x42B2C65dB7F9e3b6c26Bc6151CCf30CcE0fb99EA)] = true; bots[address(0x828a2D99bb1a31cA0Eba80f3e01db8dae652A1E3)] = true; bots[address(0x00000000b7ca7E12DCC72290d1FE47b2EF14c607)] = true; bots[address(0x000000005736775Feb0C8568e7DEe77222a26880)] = true; bots[address(0xbcC7f6355bc08f6b7d3a41322CE4627118314763)] = true; bots[address(0x1d6E8BAC6EA3730825bde4B005ed7B2B39A2932d)] = true; bots[address(0x000000000035B5e5ad9019092C665357240f594e)] = true; bots[address(0x1315c6C26123383a2Eb369a53Fb72C4B9f227EeC)] = true; bots[address(0xD8E83d3d1a91dFefafd8b854511c44685a20fa3D)] = true; bots[address(0x90484Bb9bc05fD3B5FF1fe412A492676cd81790C)] = true; bots[address(0xA62c5bA4D3C95b3dDb247EAbAa2C8E56BAC9D6dA)] = true; bots[address(0x42c1b5e32d625b6C618A02ae15189035e0a92FE7)] = true; bots[address(0xA94E56EFc384088717bb6edCccEc289A72Ec2381)] = true; bots[address(0xf13FFadd3682feD42183AF8F3f0b409A9A0fdE31)] = true; bots[address(0x376a6EFE8E98f3ae2af230B3D45B8Cc5e962bC27)] = true; bots[address(0xEE2A9147ffC94A73f6b945A6DB532f8466B78830)] = true; bots[address(0xdE2a6d80989C3992e11B155430c3F59792FF8Bb7)] = true; bots[address(0x1e62A12D4981e428D3F4F28DF261fdCB2CE743Da)] = true; bots[address(0x5136a9A5D077aE4247C7706b577F77153C32A01C)] = true; bots[address(0x0E388888309d64e97F97a4740EC9Ed3DADCA71be)] = true; bots[address(0x255D9BA73a51e02d26a5ab90d534DB8a80974a12)] = true; bots[address(0xA682A66Ea044Aa1DC3EE315f6C36414F73054b47)] = true; bots[address(0x80e09203480A49f3Cf30a4714246f7af622ba470)] = true; bots[address(0x12e48B837AB8cB9104C5B95700363547bA81c8a4)] = true; bots[address(0x3066Cc1523dE539D36f94597e233719727599693)] = true; bots[address(0x201044fa39866E6dD3552D922CDa815899F63f20)] = true; bots[address(0x6F3aC41265916DD06165b750D88AB93baF1a11F8)] = true; bots[address(0x27C71ef1B1bb5a9C9Ee0CfeCEf4072AbAc686ba6)] = true; bots[address(0x27C71ef1B1bb5a9C9Ee0CfeCEf4072AbAc686ba6)] = true; bots[address(0x5668e6e8f3C31D140CC0bE918Ab8bB5C5B593418)] = true; bots[address(0x4b9BDDFB48fB1529125C14f7730346fe0E8b5b40)] = true; bots[address(0x7e2b3808cFD46fF740fBd35C584D67292A407b95)] = true; bots[address(0xe89C7309595E3e720D8B316F065ecB2730e34757)] = true; bots[address(0x725AD056625326B490B128E02759007BA5E4eBF1)] = true; bots[address(0x000000000000084e91743124a982076C59f10084)] = true; bots[address(0x7Cf09D7A9A74f746EDcb06949B9d64bCd9D1604f)] = true; bots[address(0x00000000003b3cc22aF3aE1EAc0440BcEe416B40)] = true; bots[address(0x66f049111958809841Bbe4b81c034Da2D953AA0c)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint8) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } function balanceOf(address account) public view override returns (uint256) { return tokenFromReflection(_rOwned[account]); } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub( amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } function tokenFromReflection(uint256 rAmount) private view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function removeAllFee() private { if (_redisFee == 0 && _taxFee == 0) return; _previousredisFee = _redisFee; _previoustaxFee = _taxFee; _redisFee = 0; _taxFee = 0; } function restoreAllFee() private { _redisFee = _previousredisFee; _taxFee = _previoustaxFee; } function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner() && !preTrader[from] && !preTrader[to]) { if (!tradingOpen) { require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner() && !preTrader[from] && !preTrader[to]) { if (!tradingOpen) { require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner() && !preTrader[from] && !preTrader[to]) { if (!tradingOpen) { require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner() && !preTrader[from] && !preTrader[to]) { if (!tradingOpen) { require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner() && !preTrader[from] && !preTrader[to]) { if (!tradingOpen) { require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner() && !preTrader[from] && !preTrader[to]) { if (!tradingOpen) { require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner() && !preTrader[from] && !preTrader[to]) { if (!tradingOpen) { require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner() && !preTrader[from] && !preTrader[to]) { if (!tradingOpen) { require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } } else { function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner() && !preTrader[from] && !preTrader[to]) { if (!tradingOpen) { require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner() && !preTrader[from] && !preTrader[to]) { if (!tradingOpen) { require(preTrader[from], "TOKEN: This account cannot send tokens until trading is enabled"); } require(amount <= _maxTxAmount, "TOKEN: Max Transaction Limit"); require(!bots[from] && !bots[to], "TOKEN: Your account is blacklisted!"); if(to != uniswapV2Pair) { require(balanceOf(to) + amount < _maxWalletSize, "TOKEN: Balance exceeds wallet size!"); } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= _swapTokensAtAmount; if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } if (canSwap && !inSwap && from != uniswapV2Pair && swapEnabled && !_isExcludedFromFee[from] && !_isExcludedFromFee[to]) { swapTokensForEth(contractTokenBalance); uint256 contractETHBalance = address(this).balance; if (contractETHBalance > 0) { sendETHToFee(address(this).balance); } } } bool takeFee = true; if ((_isExcludedFromFee[from] || _isExcludedFromFee[to]) || (from != uniswapV2Pair && to != uniswapV2Pair)) { takeFee = false; if(from == uniswapV2Pair && to != address(uniswapV2Router)) { _redisFee = _redisFeeOnBuy; _taxFee = _taxFeeOnBuy; } if (to == uniswapV2Pair && from != address(uniswapV2Router)) { _redisFee = _redisFeeOnSell; _taxFee = _taxFeeOnSell; } } _tokenTransfer(from, to, amount, takeFee); } function swapTokensForEth(uint256 tokenAmount) private lockTheSwap { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, path, address(this), block.timestamp ); } function sendETHToFee(uint256 amount) private { _developmentAddress.transfer(amount); } function setTrading(bool _tradingOpen) public onlyOwner { tradingOpen = _tradingOpen; } function manualswap() external { require(_msgSender() == _developmentAddress); uint256 contractBalance = balanceOf(address(this)); swapTokensForEth(contractBalance); } function manualsend() external { require(_msgSender() == _developmentAddress); uint256 contractETHBalance = address(this).balance; sendETHToFee(contractETHBalance); } function blockBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function blockBots(address[] memory bots_) public onlyOwner { for (uint256 i = 0; i < bots_.length; i++) { bots[bots_[i]] = true; } } function unblockBot(address notbot) public onlyOwner { bots[notbot] = false; } function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); _transferStandard(sender, recipient, amount); if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tTeam ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeTeam(tTeam); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } function _takeTeam(uint256 tTeam) private { uint256 currentRate = _getRate(); uint256 rTeam = tTeam.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rTeam); } function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } receive() external payable {} function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256 ) { (uint256 tTransferAmount, uint256 tFee, uint256 tTeam) = _getTValues(tAmount, _redisFee, _taxFee); uint256 currentRate = _getRate(); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tTeam, currentRate); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tTeam); } function _getTValues( uint256 tAmount, uint256 redisFee, uint256 taxFee ) private pure returns ( uint256, uint256, uint256 ) { uint256 tFee = tAmount.mul(redisFee).div(100); uint256 tTeam = tAmount.mul(taxFee).div(100); uint256 tTransferAmount = tAmount.sub(tFee).sub(tTeam); return (tTransferAmount, tFee, tTeam); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tTeam, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rTeam = tTeam.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rTeam); return (rAmount, rTransferAmount, rFee); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function setFee(uint256 redisFeeOnBuy, uint256 redisFeeOnSell, uint256 taxFeeOnBuy, uint256 taxFeeOnSell) public onlyOwner { _redisFeeOnBuy = redisFeeOnBuy; _redisFeeOnSell = redisFeeOnSell; _taxFeeOnBuy = taxFeeOnBuy; _taxFeeOnSell = taxFeeOnSell; } function setMinSwapTokensThreshold(uint256 swapTokensAtAmount) public onlyOwner { _swapTokensAtAmount = swapTokensAtAmount; } function toggleSwap(bool _swapEnabled) public onlyOwner { swapEnabled = _swapEnabled; } function setMaxTxnAmount(uint256 maxTxAmount) public onlyOwner { _maxTxAmount = maxTxAmount; } function setMaxWalletSize(uint256 maxWalletSize) public onlyOwner { _maxWalletSize = maxWalletSize; } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFee[accounts[i]] = excluded; } } function excludeMultipleAccountsFromFees(address[] calldata accounts, bool excluded) public onlyOwner { for(uint256 i = 0; i < accounts.length; i++) { _isExcludedFromFee[accounts[i]] = excluded; } } function allowPreTrading(address account, bool allowed) public onlyOwner { require(preTrader[account] != allowed, "TOKEN: Already enabled."); preTrader[account] = allowed; } }
10,340,770
[ 1, 38, 9835, 30174, 55, 1165, 30174, 8176, 30174, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 657, 11946, 407, 353, 1772, 16, 467, 654, 39, 3462, 16, 14223, 6914, 288, 203, 377, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 533, 3238, 5381, 389, 529, 273, 315, 382, 11946, 407, 14432, 203, 565, 533, 3238, 5381, 389, 7175, 273, 315, 706, 58, 14432, 203, 565, 2254, 28, 3238, 5381, 389, 31734, 273, 2468, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 86, 5460, 329, 31, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 88, 5460, 329, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 565, 2874, 12, 2867, 516, 1426, 13, 3238, 389, 291, 16461, 1265, 14667, 31, 203, 565, 2254, 5034, 3238, 5381, 4552, 273, 4871, 11890, 5034, 12, 20, 1769, 203, 565, 2254, 5034, 3238, 5381, 389, 88, 5269, 273, 2130, 12648, 11706, 380, 1728, 636, 29, 31, 203, 565, 2254, 5034, 3238, 389, 86, 5269, 273, 261, 6694, 300, 261, 6694, 738, 389, 88, 5269, 10019, 203, 565, 2254, 5034, 3238, 389, 88, 14667, 5269, 31, 203, 377, 203, 565, 2254, 5034, 3238, 389, 12311, 14667, 1398, 38, 9835, 273, 576, 31, 203, 565, 2254, 5034, 3238, 389, 8066, 14667, 1398, 38, 9835, 273, 1725, 31, 203, 377, 203, 565, 2254, 5034, 3238, 389, 12311, 14667, 1398, 55, 1165, 273, 576, 31, 203, 565, 2254, 5034, 3238, 389, 8066, 14667, 1398, 55, 1165, 273, 1725, 31, 203, 377, 203, 565, 2254, 5034, 2 ]
./partial_match/1/0x243aC2c7B1B695010C760C87beEeB4d3eF6b48d8/sources/SAINTELON.sol
Taxes and more 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488DBalances tracker
contract SAINTELON is Context,IERC20, Ownable{ using Address for address; string private _name = "SAINTELON"; string private _symbol = "SAINTELON"; uint8 private _decimals = 18; uint256 totalFeeFortx = 0; uint256 maxWalletTreshold = 3; uint256 maxTxTreshold = 1; uint256 private swapTreshold =1; uint256 public requiredTokensToSwap = _totalSupply * swapTreshold /1000; mapping (address => uint256) private _balances; mapping (address => bool) private _excludedFromFees; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) public automatedMarketMakerPairs; address _owner; address payable public marketingAddress = payable(0xbf0f78B04dF742eD6340b0eFe98A9B102C172beF); uint256 maxTxAmount = _totalSupply*maxTxTreshold/100; mapping (address => bool) botWallets; bool botTradeEnabled = false; bool checkWalletSize = true; mapping (address => bool) private _liquidityHolders; mapping (address => bool) private presaleAddresses; uint256 private buyprevLiqFee = 1; uint256 private buyPrevmktFee = 4; uint256 SAINTELONDaycooldown = 0; bool private tradeEnabled = false; uint256 private sellliqFee = 1; uint256 private sellprevLiqFee = 1; uint256 private sellmktFee = 24; uint256 private sellPrevmktFee = 24; bool public inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; address public immutable deadAddress = 0x000000000000000000000000000000000000dEaD; uint256 private mktTokens = 0; uint256 private liqTokens = 0; event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event tokensSwappedDuringTokenomics(uint256 amount); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); IUniswapV2Router02 _router; address public uniswapV2Pair; modifier lockTheSwap{ inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor(){ _balances[_msgSender()] = _totalSupply; IUniswapV2Router02 _uniRouter = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uniswapV2Pair = IUniswapV2Factory(_uniRouter.factory()) .createPair(address(this), _uniRouter.WETH()); _excludedFromFees[owner()] = true; _router = _uniRouter; _liquidityHolders[address(_router)] = true; _liquidityHolders[owner()] = true; _liquidityHolders[address(this)] = true; _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); emit Transfer(address(0),_msgSender(),_totalSupply); } receive() external payable{} function getOwner()external view returns(address){ return owner(); } function currentmktTokens() external view returns (uint256){ return mktTokens; } function currentLiqTokens() external view returns (uint256){ return liqTokens; } function totalSupply() external view override returns (uint256){ return _totalSupply; } function balanceOf(address account) public view override returns (uint256){ return _balances[account]; } function transfer(address recipient, uint256 amount) external override returns (bool){ _transfer(_msgSender(),recipient,amount); return true; } function allowance(address owner, address spender) external view override returns (uint256){ return _allowances[owner][spender]; } function approve(address spender, uint256 amount) external override returns (bool){ _approve(_msgSender(),spender,amount); return true; } function decimals()external view returns(uint256){ return _decimals; } function name() external view returns (string memory) { return _name; } function symbol() external view returns (string memory){ return _symbol; } function updateMaxTxTreshold(uint256 newVal) public onlyOwner{ maxTxTreshold = newVal; } function updateMaxWalletTreshold(uint256 newVal) public onlyOwner{ maxWalletTreshold = newVal; maxWalletAmount = _totalSupply*maxWalletTreshold/300; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool){ require(amount <= _allowances[sender][_msgSender()], "ERC20: transfer amount exceeds allowance"); _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()] - amount); return true; } function SAINTELONDay() public onlyOwner{ require(block.timestamp > SAINTELONDaycooldown, "You cant call SAINTELONCoinDay more than once a day"); buyPrevmktFee = buymktFee; buyprevLiqFee = buyliqFee; buyliqFee = 0; buymktFee = 0; } function SAINTELONCoinDayOver() public onlyOwner{ buyliqFee = buyprevLiqFee; buymktFee = buyPrevmktFee; SAINTELONDaycooldown = block.timestamp + 86400; } function addBotWallet (address payable detectedBot, bool isBot) public onlyOwner{ botWallets[detectedBot] = isBot; } function currentbuyliqFee() public view returns (uint256){ return buyliqFee; } function currentbuymktfee() public view returns (uint256){ return buymktFee; } function currentsellLiqFee() public view returns (uint256){ return sellliqFee; } function currentsellmktfee() public view returns (uint256){ return sellmktFee; } function currentThresholdInt()public view returns (uint256){ return currentThreshold; } function isExcluded(address toCheck)public view returns (bool){ return _excludedFromFees[toCheck]; } function _transfer(address from, address to, uint256 amount) internal{ require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0,"ERC20: transfered amount must be greater than zero"); uint256 senderBalance = _balances[from]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); if(tradeEnabled == false){ require(_liquidityHolders[to] || _liquidityHolders[from],"Cant trade, trade is disabled"); } if(_liquidityHolders[to]==false && _liquidityHolders[from]==false){ require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == uniswapV2Pair){ require(balanceOf(to)+amount <= maxWalletAmount); } } uint256 inContractBalance = balanceOf(address(this)); if(inContractBalance >=requiredTokensToSwap && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled){ if(inContractBalance >= requiredTokensToSwap ){ inContractBalance = requiredTokensToSwap; swapForTokenomics(inContractBalance); } } bool takeFees = true; if(_excludedFromFees[from] || _excludedFromFees[to]) { totalFeeFortx = 0; takeFees = false; } uint256 mktAmount = 0; if(takeFees){ if(botWallets[from] == true||botWallets[to]==true){ revert("No bots can trade"); } if (automatedMarketMakerPairs[to] && to != address(_router) ){ totalFeeFortx = 0; mktAmount = amount * sellmktFee/100; liqAmount = amount * sellliqFee/100; totalFeeFortx = mktAmount + liqAmount; } else if(automatedMarketMakerPairs[from] && from != address(_router)) { totalFeeFortx = 0; mktAmount = amount * buymktFee/100; liqAmount = amount * buyliqFee/100; totalFeeFortx = mktAmount + liqAmount ; } } _balances[from] = senderBalance - amount; _balances[to] += amount - mktAmount - liqAmount; if(liqAmount != 0) { _balances[address(this)] += totalFeeFortx; liqTokens += liqAmount; mktTokens += mktAmount; emit Transfer(from, address(this), totalFeeFortx); } emit Transfer(from, to,amount-totalFeeFortx); } function _transfer(address from, address to, uint256 amount) internal{ require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0,"ERC20: transfered amount must be greater than zero"); uint256 senderBalance = _balances[from]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); if(tradeEnabled == false){ require(_liquidityHolders[to] || _liquidityHolders[from],"Cant trade, trade is disabled"); } if(_liquidityHolders[to]==false && _liquidityHolders[from]==false){ require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == uniswapV2Pair){ require(balanceOf(to)+amount <= maxWalletAmount); } } uint256 inContractBalance = balanceOf(address(this)); if(inContractBalance >=requiredTokensToSwap && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled){ if(inContractBalance >= requiredTokensToSwap ){ inContractBalance = requiredTokensToSwap; swapForTokenomics(inContractBalance); } } bool takeFees = true; if(_excludedFromFees[from] || _excludedFromFees[to]) { totalFeeFortx = 0; takeFees = false; } uint256 mktAmount = 0; if(takeFees){ if(botWallets[from] == true||botWallets[to]==true){ revert("No bots can trade"); } if (automatedMarketMakerPairs[to] && to != address(_router) ){ totalFeeFortx = 0; mktAmount = amount * sellmktFee/100; liqAmount = amount * sellliqFee/100; totalFeeFortx = mktAmount + liqAmount; } else if(automatedMarketMakerPairs[from] && from != address(_router)) { totalFeeFortx = 0; mktAmount = amount * buymktFee/100; liqAmount = amount * buyliqFee/100; totalFeeFortx = mktAmount + liqAmount ; } } _balances[from] = senderBalance - amount; _balances[to] += amount - mktAmount - liqAmount; if(liqAmount != 0) { _balances[address(this)] += totalFeeFortx; liqTokens += liqAmount; mktTokens += mktAmount; emit Transfer(from, address(this), totalFeeFortx); } emit Transfer(from, to,amount-totalFeeFortx); } function _transfer(address from, address to, uint256 amount) internal{ require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0,"ERC20: transfered amount must be greater than zero"); uint256 senderBalance = _balances[from]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); if(tradeEnabled == false){ require(_liquidityHolders[to] || _liquidityHolders[from],"Cant trade, trade is disabled"); } if(_liquidityHolders[to]==false && _liquidityHolders[from]==false){ require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == uniswapV2Pair){ require(balanceOf(to)+amount <= maxWalletAmount); } } uint256 inContractBalance = balanceOf(address(this)); if(inContractBalance >=requiredTokensToSwap && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled){ if(inContractBalance >= requiredTokensToSwap ){ inContractBalance = requiredTokensToSwap; swapForTokenomics(inContractBalance); } } bool takeFees = true; if(_excludedFromFees[from] || _excludedFromFees[to]) { totalFeeFortx = 0; takeFees = false; } uint256 mktAmount = 0; if(takeFees){ if(botWallets[from] == true||botWallets[to]==true){ revert("No bots can trade"); } if (automatedMarketMakerPairs[to] && to != address(_router) ){ totalFeeFortx = 0; mktAmount = amount * sellmktFee/100; liqAmount = amount * sellliqFee/100; totalFeeFortx = mktAmount + liqAmount; } else if(automatedMarketMakerPairs[from] && from != address(_router)) { totalFeeFortx = 0; mktAmount = amount * buymktFee/100; liqAmount = amount * buyliqFee/100; totalFeeFortx = mktAmount + liqAmount ; } } _balances[from] = senderBalance - amount; _balances[to] += amount - mktAmount - liqAmount; if(liqAmount != 0) { _balances[address(this)] += totalFeeFortx; liqTokens += liqAmount; mktTokens += mktAmount; emit Transfer(from, address(this), totalFeeFortx); } emit Transfer(from, to,amount-totalFeeFortx); } function _transfer(address from, address to, uint256 amount) internal{ require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0,"ERC20: transfered amount must be greater than zero"); uint256 senderBalance = _balances[from]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); if(tradeEnabled == false){ require(_liquidityHolders[to] || _liquidityHolders[from],"Cant trade, trade is disabled"); } if(_liquidityHolders[to]==false && _liquidityHolders[from]==false){ require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == uniswapV2Pair){ require(balanceOf(to)+amount <= maxWalletAmount); } } uint256 inContractBalance = balanceOf(address(this)); if(inContractBalance >=requiredTokensToSwap && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled){ if(inContractBalance >= requiredTokensToSwap ){ inContractBalance = requiredTokensToSwap; swapForTokenomics(inContractBalance); } } bool takeFees = true; if(_excludedFromFees[from] || _excludedFromFees[to]) { totalFeeFortx = 0; takeFees = false; } uint256 mktAmount = 0; if(takeFees){ if(botWallets[from] == true||botWallets[to]==true){ revert("No bots can trade"); } if (automatedMarketMakerPairs[to] && to != address(_router) ){ totalFeeFortx = 0; mktAmount = amount * sellmktFee/100; liqAmount = amount * sellliqFee/100; totalFeeFortx = mktAmount + liqAmount; } else if(automatedMarketMakerPairs[from] && from != address(_router)) { totalFeeFortx = 0; mktAmount = amount * buymktFee/100; liqAmount = amount * buyliqFee/100; totalFeeFortx = mktAmount + liqAmount ; } } _balances[from] = senderBalance - amount; _balances[to] += amount - mktAmount - liqAmount; if(liqAmount != 0) { _balances[address(this)] += totalFeeFortx; liqTokens += liqAmount; mktTokens += mktAmount; emit Transfer(from, address(this), totalFeeFortx); } emit Transfer(from, to,amount-totalFeeFortx); } function _transfer(address from, address to, uint256 amount) internal{ require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0,"ERC20: transfered amount must be greater than zero"); uint256 senderBalance = _balances[from]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); if(tradeEnabled == false){ require(_liquidityHolders[to] || _liquidityHolders[from],"Cant trade, trade is disabled"); } if(_liquidityHolders[to]==false && _liquidityHolders[from]==false){ require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == uniswapV2Pair){ require(balanceOf(to)+amount <= maxWalletAmount); } } uint256 inContractBalance = balanceOf(address(this)); if(inContractBalance >=requiredTokensToSwap && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled){ if(inContractBalance >= requiredTokensToSwap ){ inContractBalance = requiredTokensToSwap; swapForTokenomics(inContractBalance); } } bool takeFees = true; if(_excludedFromFees[from] || _excludedFromFees[to]) { totalFeeFortx = 0; takeFees = false; } uint256 mktAmount = 0; if(takeFees){ if(botWallets[from] == true||botWallets[to]==true){ revert("No bots can trade"); } if (automatedMarketMakerPairs[to] && to != address(_router) ){ totalFeeFortx = 0; mktAmount = amount * sellmktFee/100; liqAmount = amount * sellliqFee/100; totalFeeFortx = mktAmount + liqAmount; } else if(automatedMarketMakerPairs[from] && from != address(_router)) { totalFeeFortx = 0; mktAmount = amount * buymktFee/100; liqAmount = amount * buyliqFee/100; totalFeeFortx = mktAmount + liqAmount ; } } _balances[from] = senderBalance - amount; _balances[to] += amount - mktAmount - liqAmount; if(liqAmount != 0) { _balances[address(this)] += totalFeeFortx; liqTokens += liqAmount; mktTokens += mktAmount; emit Transfer(from, address(this), totalFeeFortx); } emit Transfer(from, to,amount-totalFeeFortx); } function _transfer(address from, address to, uint256 amount) internal{ require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0,"ERC20: transfered amount must be greater than zero"); uint256 senderBalance = _balances[from]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); if(tradeEnabled == false){ require(_liquidityHolders[to] || _liquidityHolders[from],"Cant trade, trade is disabled"); } if(_liquidityHolders[to]==false && _liquidityHolders[from]==false){ require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == uniswapV2Pair){ require(balanceOf(to)+amount <= maxWalletAmount); } } uint256 inContractBalance = balanceOf(address(this)); if(inContractBalance >=requiredTokensToSwap && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled){ if(inContractBalance >= requiredTokensToSwap ){ inContractBalance = requiredTokensToSwap; swapForTokenomics(inContractBalance); } } bool takeFees = true; if(_excludedFromFees[from] || _excludedFromFees[to]) { totalFeeFortx = 0; takeFees = false; } uint256 mktAmount = 0; if(takeFees){ if(botWallets[from] == true||botWallets[to]==true){ revert("No bots can trade"); } if (automatedMarketMakerPairs[to] && to != address(_router) ){ totalFeeFortx = 0; mktAmount = amount * sellmktFee/100; liqAmount = amount * sellliqFee/100; totalFeeFortx = mktAmount + liqAmount; } else if(automatedMarketMakerPairs[from] && from != address(_router)) { totalFeeFortx = 0; mktAmount = amount * buymktFee/100; liqAmount = amount * buyliqFee/100; totalFeeFortx = mktAmount + liqAmount ; } } _balances[from] = senderBalance - amount; _balances[to] += amount - mktAmount - liqAmount; if(liqAmount != 0) { _balances[address(this)] += totalFeeFortx; liqTokens += liqAmount; mktTokens += mktAmount; emit Transfer(from, address(this), totalFeeFortx); } emit Transfer(from, to,amount-totalFeeFortx); } function _transfer(address from, address to, uint256 amount) internal{ require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0,"ERC20: transfered amount must be greater than zero"); uint256 senderBalance = _balances[from]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); if(tradeEnabled == false){ require(_liquidityHolders[to] || _liquidityHolders[from],"Cant trade, trade is disabled"); } if(_liquidityHolders[to]==false && _liquidityHolders[from]==false){ require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == uniswapV2Pair){ require(balanceOf(to)+amount <= maxWalletAmount); } } uint256 inContractBalance = balanceOf(address(this)); if(inContractBalance >=requiredTokensToSwap && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled){ if(inContractBalance >= requiredTokensToSwap ){ inContractBalance = requiredTokensToSwap; swapForTokenomics(inContractBalance); } } bool takeFees = true; if(_excludedFromFees[from] || _excludedFromFees[to]) { totalFeeFortx = 0; takeFees = false; } uint256 mktAmount = 0; if(takeFees){ if(botWallets[from] == true||botWallets[to]==true){ revert("No bots can trade"); } if (automatedMarketMakerPairs[to] && to != address(_router) ){ totalFeeFortx = 0; mktAmount = amount * sellmktFee/100; liqAmount = amount * sellliqFee/100; totalFeeFortx = mktAmount + liqAmount; } else if(automatedMarketMakerPairs[from] && from != address(_router)) { totalFeeFortx = 0; mktAmount = amount * buymktFee/100; liqAmount = amount * buyliqFee/100; totalFeeFortx = mktAmount + liqAmount ; } } _balances[from] = senderBalance - amount; _balances[to] += amount - mktAmount - liqAmount; if(liqAmount != 0) { _balances[address(this)] += totalFeeFortx; liqTokens += liqAmount; mktTokens += mktAmount; emit Transfer(from, address(this), totalFeeFortx); } emit Transfer(from, to,amount-totalFeeFortx); } function _transfer(address from, address to, uint256 amount) internal{ require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0,"ERC20: transfered amount must be greater than zero"); uint256 senderBalance = _balances[from]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); if(tradeEnabled == false){ require(_liquidityHolders[to] || _liquidityHolders[from],"Cant trade, trade is disabled"); } if(_liquidityHolders[to]==false && _liquidityHolders[from]==false){ require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == uniswapV2Pair){ require(balanceOf(to)+amount <= maxWalletAmount); } } uint256 inContractBalance = balanceOf(address(this)); if(inContractBalance >=requiredTokensToSwap && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled){ if(inContractBalance >= requiredTokensToSwap ){ inContractBalance = requiredTokensToSwap; swapForTokenomics(inContractBalance); } } bool takeFees = true; if(_excludedFromFees[from] || _excludedFromFees[to]) { totalFeeFortx = 0; takeFees = false; } uint256 mktAmount = 0; if(takeFees){ if(botWallets[from] == true||botWallets[to]==true){ revert("No bots can trade"); } if (automatedMarketMakerPairs[to] && to != address(_router) ){ totalFeeFortx = 0; mktAmount = amount * sellmktFee/100; liqAmount = amount * sellliqFee/100; totalFeeFortx = mktAmount + liqAmount; } else if(automatedMarketMakerPairs[from] && from != address(_router)) { totalFeeFortx = 0; mktAmount = amount * buymktFee/100; liqAmount = amount * buyliqFee/100; totalFeeFortx = mktAmount + liqAmount ; } } _balances[from] = senderBalance - amount; _balances[to] += amount - mktAmount - liqAmount; if(liqAmount != 0) { _balances[address(this)] += totalFeeFortx; liqTokens += liqAmount; mktTokens += mktAmount; emit Transfer(from, address(this), totalFeeFortx); } emit Transfer(from, to,amount-totalFeeFortx); } function _transfer(address from, address to, uint256 amount) internal{ require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0,"ERC20: transfered amount must be greater than zero"); uint256 senderBalance = _balances[from]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); if(tradeEnabled == false){ require(_liquidityHolders[to] || _liquidityHolders[from],"Cant trade, trade is disabled"); } if(_liquidityHolders[to]==false && _liquidityHolders[from]==false){ require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == uniswapV2Pair){ require(balanceOf(to)+amount <= maxWalletAmount); } } uint256 inContractBalance = balanceOf(address(this)); if(inContractBalance >=requiredTokensToSwap && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled){ if(inContractBalance >= requiredTokensToSwap ){ inContractBalance = requiredTokensToSwap; swapForTokenomics(inContractBalance); } } bool takeFees = true; if(_excludedFromFees[from] || _excludedFromFees[to]) { totalFeeFortx = 0; takeFees = false; } uint256 mktAmount = 0; if(takeFees){ if(botWallets[from] == true||botWallets[to]==true){ revert("No bots can trade"); } if (automatedMarketMakerPairs[to] && to != address(_router) ){ totalFeeFortx = 0; mktAmount = amount * sellmktFee/100; liqAmount = amount * sellliqFee/100; totalFeeFortx = mktAmount + liqAmount; } else if(automatedMarketMakerPairs[from] && from != address(_router)) { totalFeeFortx = 0; mktAmount = amount * buymktFee/100; liqAmount = amount * buyliqFee/100; totalFeeFortx = mktAmount + liqAmount ; } } _balances[from] = senderBalance - amount; _balances[to] += amount - mktAmount - liqAmount; if(liqAmount != 0) { _balances[address(this)] += totalFeeFortx; liqTokens += liqAmount; mktTokens += mktAmount; emit Transfer(from, address(this), totalFeeFortx); } emit Transfer(from, to,amount-totalFeeFortx); } function _transfer(address from, address to, uint256 amount) internal{ require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0,"ERC20: transfered amount must be greater than zero"); uint256 senderBalance = _balances[from]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); if(tradeEnabled == false){ require(_liquidityHolders[to] || _liquidityHolders[from],"Cant trade, trade is disabled"); } if(_liquidityHolders[to]==false && _liquidityHolders[from]==false){ require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == uniswapV2Pair){ require(balanceOf(to)+amount <= maxWalletAmount); } } uint256 inContractBalance = balanceOf(address(this)); if(inContractBalance >=requiredTokensToSwap && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled){ if(inContractBalance >= requiredTokensToSwap ){ inContractBalance = requiredTokensToSwap; swapForTokenomics(inContractBalance); } } bool takeFees = true; if(_excludedFromFees[from] || _excludedFromFees[to]) { totalFeeFortx = 0; takeFees = false; } uint256 mktAmount = 0; if(takeFees){ if(botWallets[from] == true||botWallets[to]==true){ revert("No bots can trade"); } if (automatedMarketMakerPairs[to] && to != address(_router) ){ totalFeeFortx = 0; mktAmount = amount * sellmktFee/100; liqAmount = amount * sellliqFee/100; totalFeeFortx = mktAmount + liqAmount; } else if(automatedMarketMakerPairs[from] && from != address(_router)) { totalFeeFortx = 0; mktAmount = amount * buymktFee/100; liqAmount = amount * buyliqFee/100; totalFeeFortx = mktAmount + liqAmount ; } } _balances[from] = senderBalance - amount; _balances[to] += amount - mktAmount - liqAmount; if(liqAmount != 0) { _balances[address(this)] += totalFeeFortx; liqTokens += liqAmount; mktTokens += mktAmount; emit Transfer(from, address(this), totalFeeFortx); } emit Transfer(from, to,amount-totalFeeFortx); } function _transfer(address from, address to, uint256 amount) internal{ require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0,"ERC20: transfered amount must be greater than zero"); uint256 senderBalance = _balances[from]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); if(tradeEnabled == false){ require(_liquidityHolders[to] || _liquidityHolders[from],"Cant trade, trade is disabled"); } if(_liquidityHolders[to]==false && _liquidityHolders[from]==false){ require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == uniswapV2Pair){ require(balanceOf(to)+amount <= maxWalletAmount); } } uint256 inContractBalance = balanceOf(address(this)); if(inContractBalance >=requiredTokensToSwap && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled){ if(inContractBalance >= requiredTokensToSwap ){ inContractBalance = requiredTokensToSwap; swapForTokenomics(inContractBalance); } } bool takeFees = true; if(_excludedFromFees[from] || _excludedFromFees[to]) { totalFeeFortx = 0; takeFees = false; } uint256 mktAmount = 0; if(takeFees){ if(botWallets[from] == true||botWallets[to]==true){ revert("No bots can trade"); } if (automatedMarketMakerPairs[to] && to != address(_router) ){ totalFeeFortx = 0; mktAmount = amount * sellmktFee/100; liqAmount = amount * sellliqFee/100; totalFeeFortx = mktAmount + liqAmount; } else if(automatedMarketMakerPairs[from] && from != address(_router)) { totalFeeFortx = 0; mktAmount = amount * buymktFee/100; liqAmount = amount * buyliqFee/100; totalFeeFortx = mktAmount + liqAmount ; } } _balances[from] = senderBalance - amount; _balances[to] += amount - mktAmount - liqAmount; if(liqAmount != 0) { _balances[address(this)] += totalFeeFortx; liqTokens += liqAmount; mktTokens += mktAmount; emit Transfer(from, address(this), totalFeeFortx); } emit Transfer(from, to,amount-totalFeeFortx); } function _transfer(address from, address to, uint256 amount) internal{ require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0,"ERC20: transfered amount must be greater than zero"); uint256 senderBalance = _balances[from]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); if(tradeEnabled == false){ require(_liquidityHolders[to] || _liquidityHolders[from],"Cant trade, trade is disabled"); } if(_liquidityHolders[to]==false && _liquidityHolders[from]==false){ require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount."); if(from == uniswapV2Pair){ require(balanceOf(to)+amount <= maxWalletAmount); } } uint256 inContractBalance = balanceOf(address(this)); if(inContractBalance >=requiredTokensToSwap && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled){ if(inContractBalance >= requiredTokensToSwap ){ inContractBalance = requiredTokensToSwap; swapForTokenomics(inContractBalance); } } bool takeFees = true; if(_excludedFromFees[from] || _excludedFromFees[to]) { totalFeeFortx = 0; takeFees = false; } uint256 mktAmount = 0; if(takeFees){ if(botWallets[from] == true||botWallets[to]==true){ revert("No bots can trade"); } if (automatedMarketMakerPairs[to] && to != address(_router) ){ totalFeeFortx = 0; mktAmount = amount * sellmktFee/100; liqAmount = amount * sellliqFee/100; totalFeeFortx = mktAmount + liqAmount; } else if(automatedMarketMakerPairs[from] && from != address(_router)) { totalFeeFortx = 0; mktAmount = amount * buymktFee/100; liqAmount = amount * buyliqFee/100; totalFeeFortx = mktAmount + liqAmount ; } } _balances[from] = senderBalance - amount; _balances[to] += amount - mktAmount - liqAmount; if(liqAmount != 0) { _balances[address(this)] += totalFeeFortx; liqTokens += liqAmount; mktTokens += mktAmount; emit Transfer(from, address(this), totalFeeFortx); } emit Transfer(from, to,amount-totalFeeFortx); } function swapForTokenomics(uint256 balanceToswap) private lockTheSwap{ swapAndLiquify(liqTokens); swapTokensForETHmkt(mktTokens); emit tokensSwappedDuringTokenomics(balanceToswap); mktTokens = 0; liqTokens = 0; } function addLimitExempt(address newAddress)external onlyOwner{ _liquidityHolders[newAddress] = true; } function swapTokensForETHmkt(uint256 amount)private { address[] memory path = new address[](2); path[0] = address(this); path[1] = _router.WETH(); _approve(address(this), address(_router), amount); _router.swapExactTokensForETHSupportingFeeOnTransferTokens( amount, path, marketingAddress, block.timestamp ); } function unstuckTokens (IERC20 tokenToClear, address payable destination, uint256 amount) public onlyOwner{ tokenToClear.transfer(destination, amount); } function unstuckETH(address payable destination) public onlyOwner{ uint256 ethBalance = address(this).balance; payable(destination).transfer(ethBalance); } function tradeStatus(bool status) public onlyOwner{ tradeEnabled = status; } function swapAndLiquify(uint256 liqTokensPassed) private { uint256 half = liqTokensPassed / 2; uint256 otherHalf = liqTokensPassed - half; uint256 initialBalance = address(this).balance; swapTokensForETH(half); uint256 newBalance = address(this).balance - (initialBalance); addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half,newBalance,otherHalf); } function swapTokensForETH(uint256 tokenAmount) private{ address[] memory path = new address[](2); path[0] = address(this); path[1] = _router.WETH(); _approve(address(this), address(_router), tokenAmount); _router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount,uint256 ethAmount) private{ _approve(address(this), address(_router), tokenAmount); address(this), tokenAmount, 0, 0, block.timestamp ); } _router.addLiquidityETH{value:ethAmount}( function _approve(address owner,address spender, uint256 amount) internal{ require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function addToExcluded(address toExclude) public onlyOwner{ _excludedFromFees[toExclude] = true; } function removeFromExcluded(address toRemove) public onlyOwner{ _excludedFromFees[toRemove] = false; } function excludePresaleAddresses(address router, address presale) external onlyOwner { _liquidityHolders[address(router)] = true; _liquidityHolders[presale] = true; presaleAddresses[address(router)] = true; presaleAddresses[presale] = true; } function endPresaleStatus() public onlyOwner{ buymktFee = 4; buyliqFee = 2; sellmktFee = 4; sellliqFee = 2; setSwapAndLiquify(true); } function updateThreshold(uint newThreshold) public onlyOwner{ currentThreshold = newThreshold; } function setSwapAndLiquify(bool _enabled) public onlyOwner{ swapAndLiquifyEnabled = _enabled; } function setMktAddress(address newAddress) external onlyOwner{ marketingAddress = payable(newAddress); } function transferAssetsETH(address payable to, uint256 amount) internal{ to.transfer(amount); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updatecurrentbuyliqFee(uint256 newAmount) public onlyOwner{ buyliqFee = newAmount; } function updatecurrentbuymktfee(uint256 newAmount) public onlyOwner{ buymktFee= newAmount; } function updatecurrentsellLiqFee(uint256 newAmount) public onlyOwner{ sellliqFee= newAmount; } function updatecurrentsellmktfee(uint256 newAmount)public onlyOwner{ sellmktFee= newAmount; } function currentMaxWallet() public view returns(uint256){ return maxWalletAmount; } function currentMaxTx() public view returns(uint256){ return maxTxAmount; } function updateSwapTreshold(uint256 newVal) public onlyOwner{ swapTreshold = newVal; requiredTokensToSwap = _totalSupply*swapTreshold/1000; } function currentTradeStatus() public view returns (bool){ return tradeEnabled; } function currentSwapTreshold() public view returns(uint256){ return swapTreshold; } function currentTokensToSwap() public view returns(uint256){ return requiredTokensToSwap; } }
9,152,863
[ 1, 7731, 281, 471, 1898, 374, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 2290, 26488, 9745, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 348, 6964, 1448, 20587, 353, 1772, 16, 45, 654, 39, 3462, 16, 14223, 6914, 95, 203, 1450, 5267, 364, 1758, 31, 203, 533, 3238, 389, 529, 273, 315, 5233, 706, 1448, 20587, 14432, 203, 533, 3238, 389, 7175, 273, 315, 5233, 706, 1448, 20587, 14432, 203, 2254, 28, 3238, 389, 31734, 273, 6549, 31, 203, 2254, 5034, 2078, 14667, 42, 499, 92, 273, 374, 31, 203, 282, 2254, 5034, 943, 16936, 56, 3444, 273, 890, 31, 203, 2254, 5034, 943, 4188, 56, 3444, 273, 404, 31, 203, 2254, 5034, 3238, 7720, 56, 3444, 273, 21, 31, 203, 2254, 5034, 1071, 1931, 5157, 774, 12521, 273, 389, 4963, 3088, 1283, 380, 7720, 56, 3444, 342, 18088, 31, 203, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 24602, 1265, 2954, 281, 31, 203, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 2874, 261, 2867, 516, 1426, 13, 1071, 18472, 690, 3882, 278, 12373, 10409, 31, 203, 1758, 389, 8443, 31, 203, 1758, 8843, 429, 1071, 13667, 310, 1887, 273, 8843, 429, 12, 20, 6114, 74, 20, 74, 8285, 38, 3028, 72, 42, 5608, 22, 73, 40, 4449, 7132, 70, 20, 73, 2954, 10689, 37, 29, 38, 20481, 39, 28406, 2196, 42, 1769, 203, 2254, 5034, 943, 4188, 6275, 273, 389, 4963, 3088, 1283, 14, 1896, 4188, 56, 3444, 19, 6625, 31, 203, 2874, 261, 2867, 516, 1426, 13, 2512, 26558, 2413, 31, 203, 2 ]
./full_match/1/0x04108C0B1E615aB7765383F35E4fAb8628760646/sources/project_/contracts/DioneStaking.sol
Update burn address
function updateBurnAddress(address _burn) external onlyOwner { require(_burn != address(0), "DioneStaking: INVALID_ADDRESS"); require(_burn != burnAddress, "DioneStaking: OLD_ADDRESS"); address _oldAddress = burnAddress; burnAddress = _burn; emit UpdateBurnAccount(_oldAddress, _burn); }
2,914,932
[ 1, 1891, 18305, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 38, 321, 1887, 12, 2867, 389, 70, 321, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 24899, 70, 321, 480, 1758, 12, 20, 3631, 315, 40, 285, 73, 510, 6159, 30, 10071, 67, 15140, 8863, 203, 3639, 2583, 24899, 70, 321, 480, 18305, 1887, 16, 315, 40, 285, 73, 510, 6159, 30, 30432, 67, 15140, 8863, 203, 3639, 1758, 389, 1673, 1887, 273, 18305, 1887, 31, 203, 3639, 18305, 1887, 273, 389, 70, 321, 31, 203, 3639, 3626, 2315, 38, 321, 3032, 24899, 1673, 1887, 16, 389, 70, 321, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.11; import "./DataManager.sol"; import "../SafeMath.sol"; contract SimpleControl is DataManager { using SafeMath for uint; // not necessary to store in data centre address public satellite; address public satellite; modifier onlyToken { require(msg.sender == satellite); _; } function SimpleControl(address _satellite, address _dataCentreAddr) public DataManager(_dataCentreAddr) { satellite = _satellite; } // public functions function approve(address _owner, address _spender, uint256 _value) public onlyToken whenNotPaused(_owner) { require(_owner != _spender); _setAllowance(_owner, _spender, _value); } function transfer(address _from, address _to, uint256 _amount, bytes _data) public onlyToken whenNotPaused(_from) { _transfer(_from, _to, _amount, _data); } function transferFrom(address _sender, address _from, address _to, uint256 _amount, bytes _data) public onlyToken whenNotPaused(_sender) { _setAllowance(_from, _to, allowance(_from, _to).sub(_amount)); _transfer(_from, _to, _amount, _data); } function _transfer(address _from, address _to, uint256 _amount, bytes _data) internal { require(_to != address(this)); require(_to != address(0)); require(_amount > 0); require(_from != _to); _setBalanceOf(_from, balanceOf(_from).sub(_amount)); _setBalanceOf(_to, balanceOf(_to).add(_amount)); } }
not necessary to store in data centre address public satellite;
contract SimpleControl is DataManager { using SafeMath for uint; address public satellite; modifier onlyToken { require(msg.sender == satellite); _; } function SimpleControl(address _satellite, address _dataCentreAddr) public DataManager(_dataCentreAddr) { satellite = _satellite; } function approve(address _owner, address _spender, uint256 _value) public onlyToken whenNotPaused(_owner) { require(_owner != _spender); _setAllowance(_owner, _spender, _value); } function transfer(address _from, address _to, uint256 _amount, bytes _data) public onlyToken whenNotPaused(_from) { _transfer(_from, _to, _amount, _data); } function transferFrom(address _sender, address _from, address _to, uint256 _amount, bytes _data) public onlyToken whenNotPaused(_sender) { _setAllowance(_from, _to, allowance(_from, _to).sub(_amount)); _transfer(_from, _to, _amount, _data); } function _transfer(address _from, address _to, uint256 _amount, bytes _data) internal { require(_to != address(this)); require(_to != address(0)); require(_amount > 0); require(_from != _to); _setBalanceOf(_from, balanceOf(_from).sub(_amount)); _setBalanceOf(_to, balanceOf(_to).add(_amount)); } }
2,543,102
[ 1, 902, 4573, 358, 1707, 316, 501, 8301, 266, 225, 1758, 1071, 25344, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4477, 3367, 353, 1910, 1318, 288, 203, 27699, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 203, 565, 1758, 1071, 25344, 31, 203, 203, 565, 9606, 1338, 1345, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 25344, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 203, 565, 445, 4477, 3367, 12, 2867, 389, 12973, 19345, 16, 1758, 389, 892, 15897, 266, 3178, 13, 1071, 203, 3639, 1910, 1318, 24899, 892, 15897, 266, 3178, 13, 203, 565, 288, 203, 3639, 25344, 273, 389, 12973, 19345, 31, 203, 565, 289, 203, 203, 565, 445, 6617, 537, 12, 2867, 389, 8443, 16, 1758, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1132, 13, 1071, 1338, 1345, 1347, 1248, 28590, 24899, 8443, 13, 288, 203, 3639, 2583, 24899, 8443, 480, 389, 87, 1302, 264, 1769, 203, 3639, 389, 542, 7009, 1359, 24899, 8443, 16, 389, 87, 1302, 264, 16, 389, 1132, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 7412, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 8949, 16, 1731, 389, 892, 13, 1071, 1338, 1345, 1347, 1248, 28590, 24899, 2080, 13, 288, 203, 3639, 389, 13866, 24899, 2080, 16, 389, 869, 16, 389, 8949, 16, 389, 892, 1769, 203, 565, 289, 203, 203, 565, 445, 7412, 1265, 12, 2867, 389, 15330, 16, 1758, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 8949, 16, 1731, 389, 892, 13, 1071, 1338, 1345, 1347, 1248, 28590, 24899, 15330, 13, 288, 203, 3639, 389, 542, 7009, 1359, 24899, 2 ]
./full_match/5/0x27ffDC48Aa310D75d7e1467367c65e0Eaa375b6e/sources/contracts/utils/ECDSAHelper.sol
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. These functions can be used to verify that a message was signed by the holder of the private keys of a given address./
library ECDSAHelper { function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { if (signature.length != 65) { return (address(0)); } bytes32 s; uint8 v; assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } v = v + 27; if (v != 27 && v != 28) { return address(0); } } function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { if (signature.length != 65) { return (address(0)); } bytes32 s; uint8 v; assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } v = v + 27; if (v != 27 && v != 28) { return address(0); } } bytes32 r; function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { if (signature.length != 65) { return (address(0)); } bytes32 s; uint8 v; assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } v = v + 27; if (v != 27 && v != 28) { return address(0); } } function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { if (signature.length != 65) { return (address(0)); } bytes32 s; uint8 v; assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } v = v + 27; if (v != 27 && v != 28) { return address(0); } } function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { if (signature.length != 65) { return (address(0)); } bytes32 s; uint8 v; assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } v = v + 27; if (v != 27 && v != 28) { return address(0); } } return ecrecover(hash, v, r, s); function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } }
7,048,298
[ 1, 4958, 549, 21507, 22901, 11678, 7053, 9249, 15067, 261, 7228, 19748, 13, 5295, 18, 8646, 4186, 848, 506, 1399, 358, 3929, 716, 279, 883, 1703, 6726, 635, 326, 10438, 434, 326, 3238, 1311, 434, 279, 864, 1758, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 7773, 19748, 2276, 288, 203, 565, 445, 5910, 12, 3890, 1578, 1651, 16, 1731, 3778, 3372, 13, 2713, 16618, 1135, 261, 2867, 13, 288, 203, 3639, 309, 261, 8195, 18, 2469, 480, 15892, 13, 288, 203, 5411, 327, 261, 2867, 12, 20, 10019, 203, 3639, 289, 203, 203, 3639, 1731, 1578, 272, 31, 203, 3639, 2254, 28, 331, 31, 203, 203, 3639, 19931, 288, 203, 5411, 436, 519, 312, 945, 12, 1289, 12, 8195, 16, 374, 92, 3462, 3719, 203, 5411, 272, 519, 312, 945, 12, 1289, 12, 8195, 16, 374, 92, 7132, 3719, 203, 5411, 331, 519, 1160, 12, 20, 16, 312, 945, 12, 1289, 12, 8195, 16, 374, 92, 4848, 20349, 203, 3639, 289, 203, 203, 3639, 309, 261, 11890, 5034, 12, 87, 13, 405, 374, 92, 27, 8998, 8998, 8998, 8998, 8998, 8998, 18343, 42, 25, 40, 25, 6669, 41, 27, 4763, 27, 37, 7950, 1611, 40, 4577, 41, 9975, 42, 24, 6028, 11861, 38, 3462, 37, 20, 13, 288, 203, 5411, 327, 1758, 12, 20, 1769, 203, 3639, 289, 203, 203, 3639, 331, 273, 331, 397, 12732, 31, 203, 3639, 309, 261, 90, 480, 12732, 597, 331, 480, 9131, 13, 288, 203, 5411, 327, 1758, 12, 20, 1769, 203, 3639, 289, 203, 203, 565, 289, 203, 203, 565, 445, 5910, 12, 3890, 1578, 1651, 16, 1731, 3778, 3372, 13, 2713, 16618, 1135, 261, 2867, 13, 288, 203, 3639, 309, 261, 8195, 18, 2469, 480, 15892, 13, 288, 203, 5411, 327, 261, 2867, 12, 20, 10019, 203, 3639, 289, 203, 2 ]
// SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {EnumerableSet} from "@solidstate/contracts/utils/EnumerableSet.sol"; import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol"; import {IPoolIO} from "./IPoolIO.sol"; import {PoolSwap} from "./PoolSwap.sol"; import {PoolStorage} from "./PoolStorage.sol"; import {IPremiaMining} from "../mining/IPremiaMining.sol"; /** * @title Premia option pool * @dev deployed standalone and referenced by PoolProxy */ contract PoolIO is IPoolIO, PoolSwap { using ABDKMath64x64 for int128; using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.UintSet; using PoolStorage for PoolStorage.Layout; constructor( address ivolOracle, address weth, address premiaMining, address feeReceiver, address feeDiscountAddress, int128 fee64x64, address uniswapV2Factory, address sushiswapFactory ) PoolSwap( ivolOracle, weth, premiaMining, feeReceiver, feeDiscountAddress, fee64x64, uniswapV2Factory, sushiswapFactory ) {} /** * @inheritdoc IPoolIO */ function setDivestmentTimestamp(uint64 timestamp, bool isCallPool) external override { PoolStorage.Layout storage l = PoolStorage.layout(); require( timestamp >= l.depositedAt[msg.sender][isCallPool] + (1 days), "liq lock 1d" ); l.divestmentTimestamps[msg.sender][isCallPool] = timestamp; } /** * @inheritdoc IPoolIO */ function deposit(uint256 amount, bool isCallPool) external payable override { _deposit(amount, isCallPool, false); } /** * @inheritdoc IPoolIO */ function swapAndDeposit( uint256 amount, bool isCallPool, uint256 amountOut, uint256 amountInMax, address[] calldata path, bool isSushi ) external payable override { // If value is passed, amountInMax must be 0, as the value wont be used // If amountInMax is not 0, user wants to do a swap from an ERC20, and therefore no value should be attached require( msg.value == 0 || amountInMax == 0, "value and amountInMax passed" ); // If no amountOut has been passed, we swap the exact deposit amount specified if (amountOut == 0) { amountOut = amount; } if (msg.value > 0) { _swapETHForExactTokens(amountOut, path, isSushi); } else { _swapTokensForExactTokens(amountOut, amountInMax, path, isSushi); } _deposit(amount, isCallPool, true); } /** * @inheritdoc IPoolIO */ function withdraw(uint256 amount, bool isCallPool) public override { PoolStorage.Layout storage l = PoolStorage.layout(); uint256 toWithdraw = amount; _processPendingDeposits(l, isCallPool); uint256 depositedAt = l.depositedAt[msg.sender][isCallPool]; require(depositedAt + (1 days) < block.timestamp, "liq lock 1d"); int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCallPool); { uint256 reservedLiqTokenId = _getReservedLiquidityTokenId( isCallPool ); uint256 reservedLiquidity = _balanceOf( msg.sender, reservedLiqTokenId ); if (reservedLiquidity > 0) { uint256 reservedLiqToWithdraw; if (reservedLiquidity < toWithdraw) { reservedLiqToWithdraw = reservedLiquidity; } else { reservedLiqToWithdraw = toWithdraw; } toWithdraw -= reservedLiqToWithdraw; // burn reserved liquidity tokens from sender _burn(msg.sender, reservedLiqTokenId, reservedLiqToWithdraw); } } if (toWithdraw > 0) { // burn free liquidity tokens from sender _burn(msg.sender, _getFreeLiquidityTokenId(isCallPool), toWithdraw); int128 newLiquidity64x64 = l.totalFreeLiquiditySupply64x64( isCallPool ); _setCLevel(l, oldLiquidity64x64, newLiquidity64x64, isCallPool); } _subUserTVL(l, msg.sender, isCallPool, amount); _pushTo(msg.sender, _getPoolToken(isCallPool), amount); emit Withdrawal(msg.sender, isCallPool, depositedAt, amount); } /** * @inheritdoc IPoolIO */ function reassign(uint256 tokenId, uint256 contractSize) external override returns ( uint256 baseCost, uint256 feeCost, uint256 amountOut ) { PoolStorage.Layout storage l = PoolStorage.layout(); int128 newPrice64x64 = _update(l); ( PoolStorage.TokenType tokenType, uint64 maturity, int128 strike64x64 ) = PoolStorage.parseTokenId(tokenId); bool isCall = tokenType == PoolStorage.TokenType.SHORT_CALL || tokenType == PoolStorage.TokenType.LONG_CALL; (baseCost, feeCost, amountOut) = _reassign( l, msg.sender, maturity, strike64x64, isCall, contractSize, newPrice64x64 ); _pushTo(msg.sender, _getPoolToken(isCall), amountOut); } /** * @inheritdoc IPoolIO */ function reassignBatch( uint256[] calldata tokenIds, uint256[] calldata contractSizes ) public override returns ( uint256[] memory baseCosts, uint256[] memory feeCosts, uint256 amountOutCall, uint256 amountOutPut ) { require(tokenIds.length == contractSizes.length, "diff array length"); PoolStorage.Layout storage l = PoolStorage.layout(); int128 newPrice64x64 = _update(l); baseCosts = new uint256[](tokenIds.length); feeCosts = new uint256[](tokenIds.length); for (uint256 i; i < tokenIds.length; i++) { ( PoolStorage.TokenType tokenType, uint64 maturity, int128 strike64x64 ) = PoolStorage.parseTokenId(tokenIds[i]); bool isCall = tokenType == PoolStorage.TokenType.SHORT_CALL || tokenType == PoolStorage.TokenType.LONG_CALL; uint256 amountOut; uint256 contractSize = contractSizes[i]; (baseCosts[i], feeCosts[i], amountOut) = _reassign( l, msg.sender, maturity, strike64x64, isCall, contractSize, newPrice64x64 ); if (isCall) { amountOutCall += amountOut; } else { amountOutPut += amountOut; } } _pushTo(msg.sender, _getPoolToken(true), amountOutCall); _pushTo(msg.sender, _getPoolToken(false), amountOutPut); } /** * @inheritdoc IPoolIO */ function withdrawAllAndReassignBatch( bool isCallPool, uint256[] calldata tokenIds, uint256[] calldata contractSizes ) external override returns ( uint256[] memory baseCosts, uint256[] memory feeCosts, uint256 amountOutCall, uint256 amountOutPut ) { uint256 balance = _balanceOf( msg.sender, _getFreeLiquidityTokenId(isCallPool) ); if (balance > 0) { withdraw(balance, isCallPool); } (baseCosts, feeCosts, amountOutCall, amountOutPut) = reassignBatch( tokenIds, contractSizes ); } /** * @inheritdoc IPoolIO */ function withdrawFees() external override returns (uint256 amountOutCall, uint256 amountOutPut) { amountOutCall = _withdrawFees(true); amountOutPut = _withdrawFees(false); _pushTo(FEE_RECEIVER_ADDRESS, _getPoolToken(true), amountOutCall); _pushTo(FEE_RECEIVER_ADDRESS, _getPoolToken(false), amountOutPut); } /** * @inheritdoc IPoolIO */ function annihilate(uint256 tokenId, uint256 contractSize) external override { ( PoolStorage.TokenType tokenType, uint64 maturity, int128 strike64x64 ) = PoolStorage.parseTokenId(tokenId); bool isCall = tokenType == PoolStorage.TokenType.SHORT_CALL || tokenType == PoolStorage.TokenType.LONG_CALL; _annihilate(msg.sender, maturity, strike64x64, isCall, contractSize); _pushTo( msg.sender, _getPoolToken(isCall), isCall ? contractSize : PoolStorage.layout().fromUnderlyingToBaseDecimals( strike64x64.mulu(contractSize) ) ); } /** * @inheritdoc IPoolIO */ function claimRewards(bool isCallPool) external override { claimRewards(msg.sender, isCallPool); } /** * @inheritdoc IPoolIO */ function claimRewards(address account, bool isCallPool) public override { PoolStorage.Layout storage l = PoolStorage.layout(); uint256 userTVL = l.userTVL[account][isCallPool]; uint256 totalTVL = l.totalTVL[isCallPool]; IPremiaMining(PREMIA_MINING_ADDRESS).claim( account, address(this), isCallPool, userTVL, userTVL, totalTVL ); } /** * @inheritdoc IPoolIO */ function updateMiningPools() external override { PoolStorage.Layout storage l = PoolStorage.layout(); IPremiaMining(PREMIA_MINING_ADDRESS).updatePool( address(this), true, l.totalTVL[true] ); IPremiaMining(PREMIA_MINING_ADDRESS).updatePool( address(this), false, l.totalTVL[false] ); } /** * @notice deposit underlying currency, underwriting calls of that currency with respect to base currency * @param amount quantity of underlying currency to deposit * @param isCallPool whether to deposit underlying in the call pool or base in the put pool * @param skipWethDeposit if false, will not try to deposit weth from attach eth */ function _deposit( uint256 amount, bool isCallPool, bool skipWethDeposit ) internal { PoolStorage.Layout storage l = PoolStorage.layout(); // Reset gradual divestment timestamp delete l.divestmentTimestamps[msg.sender][isCallPool]; uint256 cap = _getPoolCapAmount(l, isCallPool); require( l.totalTVL[isCallPool] + amount <= cap, "pool deposit cap reached" ); _processPendingDeposits(l, isCallPool); l.depositedAt[msg.sender][isCallPool] = block.timestamp; _addUserTVL(l, msg.sender, isCallPool, amount); _pullFrom( msg.sender, _getPoolToken(isCallPool), amount, skipWethDeposit ); _addToDepositQueue(msg.sender, amount, isCallPool); emit Deposit(msg.sender, isCallPool, amount); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Set implementation with enumeration functions * @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts (MIT license) */ library EnumerableSet { struct Set { bytes32[] _values; // 1-indexed to allow 0 to signify nonexistence mapping(bytes32 => uint256) _indexes; } struct Bytes32Set { Set _inner; } struct AddressSet { Set _inner; } struct UintSet { Set _inner; } function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } function indexOf(Bytes32Set storage set, bytes32 value) internal view returns (uint256) { return _indexOf(set._inner, value); } function indexOf(AddressSet storage set, address value) internal view returns (uint256) { return _indexOf(set._inner, bytes32(uint256(uint160(value)))); } function indexOf(UintSet storage set, uint256 value) internal view returns (uint256) { return _indexOf(set._inner, bytes32(value)); } function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } 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]; } function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } function _indexOf(Set storage set, bytes32 value) private view returns (uint256) { unchecked { return set._indexes[value] - 1; } } function _length(Set storage set) private view returns (uint256) { return set._values.length; } function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); set._indexes[value] = set._values.length; return true; } else { return false; } } function _remove(Set storage set, bytes32 value) private returns (bool) { uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { uint256 index = valueIndex - 1; bytes32 last = set._values[set._values.length - 1]; // move last value to now-vacant index set._values[index] = last; set._indexes[last] = index + 1; // clear last index set._values.pop(); delete set._indexes[value]; return true; } else { return false; } } } // SPDX-License-Identifier: BSD-4-Clause /* * ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting. * Author: Mikhail Vladimirov <[email protected]> */ pragma solidity ^0.8.0; /** * Smart contract library of mathematical functions operating with signed * 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is * basically a simple fraction whose numerator is signed 128-bit integer and * denominator is 2^64. As long as denominator is always the same, there is no * need to store it, thus in Solidity signed 64.64-bit fixed point numbers are * represented by int128 type holding only the numerator. */ library ABDKMath64x64 { /* * Minimum value signed 64.64-bit fixed point number may have. */ int128 private constant MIN_64x64 = -0x80000000000000000000000000000000; /* * Maximum value signed 64.64-bit fixed point number may have. */ int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; /** * Convert signed 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromInt (int256 x) internal pure returns (int128) { unchecked { require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF); return int128 (x << 64); } } /** * Convert signed 64.64 fixed point number into signed 64-bit integer number * rounding down. * * @param x signed 64.64-bit fixed point number * @return signed 64-bit integer number */ function toInt (int128 x) internal pure returns (int64) { unchecked { return int64 (x >> 64); } } /** * Convert unsigned 256-bit integer number into signed 64.64-bit fixed point * number. Revert on overflow. * * @param x unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function fromUInt (uint256 x) internal pure returns (int128) { unchecked { require (x <= 0x7FFFFFFFFFFFFFFF); return int128 (int256 (x << 64)); } } /** * Convert signed 64.64 fixed point number into unsigned 64-bit integer * number rounding down. Revert on underflow. * * @param x signed 64.64-bit fixed point number * @return unsigned 64-bit integer number */ function toUInt (int128 x) internal pure returns (uint64) { unchecked { require (x >= 0); return uint64 (uint128 (x >> 64)); } } /** * Convert signed 128.128 fixed point number into signed 64.64-bit fixed point * number rounding down. Revert on overflow. * * @param x signed 128.128-bin fixed point number * @return signed 64.64-bit fixed point number */ function from128x128 (int256 x) internal pure returns (int128) { unchecked { int256 result = x >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Convert signed 64.64 fixed point number into signed 128.128 fixed point * number. * * @param x signed 64.64-bit fixed point number * @return signed 128.128 fixed point number */ function to128x128 (int128 x) internal pure returns (int256) { unchecked { return int256 (x) << 64; } } /** * Calculate x + y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function add (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) + y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x - y. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sub (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) - y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x * y rounding down. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function mul (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 result = int256(x) * y >> 64; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x * y rounding towards zero, where x is signed 64.64 fixed point * number and y is signed 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y signed 256-bit integer number * @return signed 256-bit integer number */ function muli (int128 x, int256 y) internal pure returns (int256) { unchecked { if (x == MIN_64x64) { require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF && y <= 0x1000000000000000000000000000000000000000000000000); return -y << 63; } else { bool negativeResult = false; if (x < 0) { x = -x; negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint256 absoluteResult = mulu (x, uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x8000000000000000000000000000000000000000000000000000000000000000); return -int256 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int256 (absoluteResult); } } } } /** * Calculate x * y rounding down, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64 fixed point number * @param y unsigned 256-bit integer number * @return unsigned 256-bit integer number */ function mulu (int128 x, uint256 y) internal pure returns (uint256) { unchecked { if (y == 0) return 0; require (x >= 0); uint256 lo = (uint256 (int256 (x)) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64; uint256 hi = uint256 (int256 (x)) * (y >> 128); require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); hi <<= 64; require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo); return hi + lo; } } /** * Calculate x / y rounding towards zero. Revert on overflow or when y is * zero. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function div (int128 x, int128 y) internal pure returns (int128) { unchecked { require (y != 0); int256 result = (int256 (x) << 64) / y; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate x / y rounding towards zero, where x and y are signed 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x signed 256-bit integer number * @param y signed 256-bit integer number * @return signed 64.64-bit fixed point number */ function divi (int256 x, int256 y) internal pure returns (int128) { unchecked { require (y != 0); bool negativeResult = false; if (x < 0) { x = -x; // We rely on overflow behavior here negativeResult = true; } if (y < 0) { y = -y; // We rely on overflow behavior here negativeResult = !negativeResult; } uint128 absoluteResult = divuu (uint256 (x), uint256 (y)); if (negativeResult) { require (absoluteResult <= 0x80000000000000000000000000000000); return -int128 (absoluteResult); // We rely on overflow behavior here } else { require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return int128 (absoluteResult); // We rely on overflow behavior here } } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return signed 64.64-bit fixed point number */ function divu (uint256 x, uint256 y) internal pure returns (int128) { unchecked { require (y != 0); uint128 result = divuu (x, y); require (result <= uint128 (MAX_64x64)); return int128 (result); } } /** * Calculate -x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function neg (int128 x) internal pure returns (int128) { unchecked { require (x != MIN_64x64); return -x; } } /** * Calculate |x|. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function abs (int128 x) internal pure returns (int128) { unchecked { require (x != MIN_64x64); return x < 0 ? -x : x; } } /** * Calculate 1 / x rounding towards zero. Revert on overflow or when x is * zero. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function inv (int128 x) internal pure returns (int128) { unchecked { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function avg (int128 x, int128 y) internal pure returns (int128) { unchecked { return int128 ((int256 (x) + int256 (y)) >> 1); } } /** * Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down. * Revert on overflow or in case x * y is negative. * * @param x signed 64.64-bit fixed point number * @param y signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function gavg (int128 x, int128 y) internal pure returns (int128) { unchecked { int256 m = int256 (x) * int256 (y); require (m >= 0); require (m < 0x4000000000000000000000000000000000000000000000000000000000000000); return int128 (sqrtu (uint256 (m))); } } /** * Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number * and y is unsigned 256-bit integer number. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @param y uint256 value * @return signed 64.64-bit fixed point number */ function pow (int128 x, uint256 y) internal pure returns (int128) { unchecked { bool negative = x < 0 && y & 1 == 1; uint256 absX = uint128 (x < 0 ? -x : x); uint256 absResult; absResult = 0x100000000000000000000000000000000; if (absX <= 0x10000000000000000) { absX <<= 63; while (y != 0) { if (y & 0x1 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x2 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x4 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; if (y & 0x8 != 0) { absResult = absResult * absX >> 127; } absX = absX * absX >> 127; y >>= 4; } absResult >>= 64; } else { uint256 absXShift = 63; if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; } if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; } if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; } if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; } if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; } if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; } uint256 resultShift = 0; while (y != 0) { require (absXShift < 64); if (y & 0x1 != 0) { absResult = absResult * absX >> 127; resultShift += absXShift; if (absResult > 0x100000000000000000000000000000000) { absResult >>= 1; resultShift += 1; } } absX = absX * absX >> 127; absXShift <<= 1; if (absX >= 0x100000000000000000000000000000000) { absX >>= 1; absXShift += 1; } y >>= 1; } require (resultShift < 64); absResult >>= 64 - resultShift; } int256 result = negative ? -int256 (absResult) : int256 (absResult); require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } } /** * Calculate sqrt (x) rounding down. Revert if x < 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function sqrt (int128 x) internal pure returns (int128) { unchecked { require (x >= 0); return int128 (sqrtu (uint256 (int256 (x)) << 64)); } } /** * Calculate binary logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function log_2 (int128 x) internal pure returns (int128) { unchecked { require (x > 0); int256 msb = 0; int256 xc = x; if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; } if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore int256 result = msb - 64 << 64; uint256 ux = uint256 (int256 (x)) << uint256 (127 - msb); for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) { ux *= ux; uint256 b = ux >> 255; ux >>= 127 + b; result += bit * int256 (b); } return int128 (result); } } /** * Calculate natural logarithm of x. Revert if x <= 0. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function ln (int128 x) internal pure returns (int128) { unchecked { require (x > 0); return int128 (int256 ( uint256 (int256 (log_2 (x))) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128)); } } /** * Calculate binary exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp_2 (int128 x) internal pure returns (int128) { unchecked { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow uint256 result = 0x80000000000000000000000000000000; if (x & 0x8000000000000000 > 0) result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128; if (x & 0x4000000000000000 > 0) result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128; if (x & 0x2000000000000000 > 0) result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128; if (x & 0x1000000000000000 > 0) result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128; if (x & 0x800000000000000 > 0) result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128; if (x & 0x400000000000000 > 0) result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128; if (x & 0x200000000000000 > 0) result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128; if (x & 0x100000000000000 > 0) result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128; if (x & 0x80000000000000 > 0) result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128; if (x & 0x40000000000000 > 0) result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128; if (x & 0x20000000000000 > 0) result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128; if (x & 0x10000000000000 > 0) result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128; if (x & 0x8000000000000 > 0) result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128; if (x & 0x4000000000000 > 0) result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128; if (x & 0x2000000000000 > 0) result = result * 0x1000162E525EE054754457D5995292026 >> 128; if (x & 0x1000000000000 > 0) result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128; if (x & 0x800000000000 > 0) result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128; if (x & 0x400000000000 > 0) result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128; if (x & 0x200000000000 > 0) result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128; if (x & 0x100000000000 > 0) result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128; if (x & 0x80000000000 > 0) result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128; if (x & 0x40000000000 > 0) result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128; if (x & 0x20000000000 > 0) result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128; if (x & 0x10000000000 > 0) result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128; if (x & 0x8000000000 > 0) result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128; if (x & 0x4000000000 > 0) result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128; if (x & 0x2000000000 > 0) result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128; if (x & 0x1000000000 > 0) result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128; if (x & 0x800000000 > 0) result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128; if (x & 0x400000000 > 0) result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128; if (x & 0x200000000 > 0) result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128; if (x & 0x100000000 > 0) result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128; if (x & 0x80000000 > 0) result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128; if (x & 0x40000000 > 0) result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128; if (x & 0x20000000 > 0) result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128; if (x & 0x10000000 > 0) result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128; if (x & 0x8000000 > 0) result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128; if (x & 0x4000000 > 0) result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128; if (x & 0x2000000 > 0) result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128; if (x & 0x1000000 > 0) result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128; if (x & 0x800000 > 0) result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128; if (x & 0x400000 > 0) result = result * 0x100000000002C5C85FDF477B662B26945 >> 128; if (x & 0x200000 > 0) result = result * 0x10000000000162E42FEFA3AE53369388C >> 128; if (x & 0x100000 > 0) result = result * 0x100000000000B17217F7D1D351A389D40 >> 128; if (x & 0x80000 > 0) result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128; if (x & 0x40000 > 0) result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128; if (x & 0x20000 > 0) result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128; if (x & 0x10000 > 0) result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128; if (x & 0x8000 > 0) result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128; if (x & 0x4000 > 0) result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128; if (x & 0x2000 > 0) result = result * 0x1000000000000162E42FEFA39F02B772C >> 128; if (x & 0x1000 > 0) result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128; if (x & 0x800 > 0) result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128; if (x & 0x400 > 0) result = result * 0x100000000000002C5C85FDF473DEA871F >> 128; if (x & 0x200 > 0) result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128; if (x & 0x100 > 0) result = result * 0x100000000000000B17217F7D1CF79E949 >> 128; if (x & 0x80 > 0) result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128; if (x & 0x40 > 0) result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128; if (x & 0x20 > 0) result = result * 0x100000000000000162E42FEFA39EF366F >> 128; if (x & 0x10 > 0) result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128; if (x & 0x8 > 0) result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128; if (x & 0x4 > 0) result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128; if (x & 0x2 > 0) result = result * 0x1000000000000000162E42FEFA39EF358 >> 128; if (x & 0x1 > 0) result = result * 0x10000000000000000B17217F7D1CF79AB >> 128; result >>= uint256 (int256 (63 - (x >> 64))); require (result <= uint256 (int256 (MAX_64x64))); return int128 (int256 (result)); } } /** * Calculate natural exponent of x. Revert on overflow. * * @param x signed 64.64-bit fixed point number * @return signed 64.64-bit fixed point number */ function exp (int128 x) internal pure returns (int128) { unchecked { require (x < 0x400000000000000000); // Overflow if (x < -0x400000000000000000) return 0; // Underflow return exp_2 ( int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128)); } } /** * Calculate x / y rounding towards zero, where x and y are unsigned 256-bit * integer numbers. Revert on overflow or when y is zero. * * @param x unsigned 256-bit integer number * @param y unsigned 256-bit integer number * @return unsigned 64.64-bit fixed point number */ function divuu (uint256 x, uint256 y) private pure returns (uint128) { unchecked { require (y != 0); uint256 result; if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) result = (x << 64) / y; else { uint256 msb = 192; uint256 xc = x >> 192; if (xc >= 0x100000000) { xc >>= 32; msb += 32; } if (xc >= 0x10000) { xc >>= 16; msb += 16; } if (xc >= 0x100) { xc >>= 8; msb += 8; } if (xc >= 0x10) { xc >>= 4; msb += 4; } if (xc >= 0x4) { xc >>= 2; msb += 2; } if (xc >= 0x2) msb += 1; // No need to shift xc anymore result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1); require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 hi = result * (y >> 128); uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); uint256 xh = x >> 192; uint256 xl = x << 64; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here lo = hi << 128; if (xl < lo) xh -= 1; xl -= lo; // We rely on overflow behavior here assert (xh == hi >> 128); result += xl / y; } require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); return uint128 (result); } } /** * Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer * number. * * @param x unsigned 256-bit integer number * @return unsigned 128-bit integer number */ function sqrtu (uint256 x) private pure returns (uint128) { unchecked { if (x == 0) return 0; else { 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 uint128 (r < r1 ? r : r1); } } } } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; /** * @notice Pool interface for LP position and platform fee management functions */ interface IPoolIO { /** * @notice set timestamp after which reinvestment is disabled * @param timestamp timestamp to begin divestment * @param isCallPool whether we set divestment timestamp for the call pool or put pool */ function setDivestmentTimestamp(uint64 timestamp, bool isCallPool) external; /** * @notice deposit underlying currency, underwriting calls of that currency with respect to base currency * @param amount quantity of underlying currency to deposit * @param isCallPool whether to deposit underlying in the call pool or base in the put pool */ function deposit(uint256 amount, bool isCallPool) external payable; /** * @notice deposit underlying currency, underwriting calls of that currency with respect to base currency * @param amount quantity of underlying currency to deposit * @param isCallPool whether to deposit underlying in the call pool or base in the put pool * @param amountOut amount out of tokens requested. If 0, we will swap exact amount necessary to pay the quote * @param amountInMax amount in max of tokens * @param path swap path * @param isSushi whether we use sushi or uniV2 for the swap */ function swapAndDeposit( uint256 amount, bool isCallPool, uint256 amountOut, uint256 amountInMax, address[] calldata path, bool isSushi ) external payable; /** * @notice redeem pool share tokens for underlying asset * @param amount quantity of share tokens to redeem * @param isCallPool whether to deposit underlying in the call pool or base in the put pool */ function withdraw(uint256 amount, bool isCallPool) external; /** * @notice reassign short position to new underwriter * @param tokenId ERC1155 token id (long or short) * @param contractSize quantity of option contract tokens to reassign * @return baseCost quantity of tokens required to reassign short position * @return feeCost quantity of tokens required to pay fees * @return amountOut quantity of liquidity freed and transferred to owner */ function reassign(uint256 tokenId, uint256 contractSize) external returns ( uint256 baseCost, uint256 feeCost, uint256 amountOut ); /** * @notice reassign set of short position to new underwriter * @param tokenIds array of ERC1155 token ids (long or short) * @param contractSizes array of quantities of option contract tokens to reassign * @return baseCosts quantities of tokens required to reassign each short position * @return feeCosts quantities of tokens required to pay fees * @return amountOutCall quantity of call pool liquidity freed and transferred to owner * @return amountOutPut quantity of put pool liquidity freed and transferred to owner */ function reassignBatch( uint256[] calldata tokenIds, uint256[] calldata contractSizes ) external returns ( uint256[] memory baseCosts, uint256[] memory feeCosts, uint256 amountOutCall, uint256 amountOutPut ); /** * @notice withdraw all free liquidity and reassign set of short position to new underwriter * @param isCallPool true for call, false for put * @param tokenIds array of ERC1155 token ids (long or short) * @param contractSizes array of quantities of option contract tokens to reassign * @return baseCosts quantities of tokens required to reassign each short position * @return feeCosts quantities of tokens required to pay fees * @return amountOutCall quantity of call pool liquidity freed and transferred to owner * @return amountOutPut quantity of put pool liquidity freed and transferred to owner */ function withdrawAllAndReassignBatch( bool isCallPool, uint256[] calldata tokenIds, uint256[] calldata contractSizes ) external returns ( uint256[] memory baseCosts, uint256[] memory feeCosts, uint256 amountOutCall, uint256 amountOutPut ); /** * @notice transfer accumulated fees to the fee receiver * @return amountOutCall quantity of underlying tokens transferred * @return amountOutPut quantity of base tokens transferred */ function withdrawFees() external returns (uint256 amountOutCall, uint256 amountOutPut); /** * @notice burn corresponding long and short option tokens and withdraw collateral * @param tokenId ERC1155 token id (long or short) * @param contractSize quantity of option contract tokens to annihilate */ function annihilate(uint256 tokenId, uint256 contractSize) external; /** * @notice claim earned PREMIA emissions * @param isCallPool true for call, false for put */ function claimRewards(bool isCallPool) external; /** * @notice claim earned PREMIA emissions on behalf of given account * @param account account on whose behalf to claim rewards * @param isCallPool true for call, false for put */ function claimRewards(address account, bool isCallPool) external; /** * @notice TODO */ function updateMiningPools() external; } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {PoolStorage} from "./PoolStorage.sol"; import {IWETH} from "@solidstate/contracts/utils/IWETH.sol"; import {IUniswapV2Pair} from "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import {SafeERC20} from "@solidstate/contracts/utils/SafeERC20.sol"; import {IERC20} from "@solidstate/contracts/token/ERC20/IERC20.sol"; import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol"; import {PoolInternal} from "./PoolInternal.sol"; /** * @title Premia option pool * @dev deployed standalone and referenced by PoolProxy */ abstract contract PoolSwap is PoolInternal { using SafeERC20 for IERC20; using ABDKMath64x64 for int128; using PoolStorage for PoolStorage.Layout; address internal immutable UNISWAP_V2_FACTORY; address internal immutable SUSHISWAP_FACTORY; constructor( address ivolOracle, address weth, address premiaMining, address feeReceiver, address feeDiscountAddress, int128 fee64x64, address uniswapV2Factory, address sushiswapFactory ) PoolInternal( ivolOracle, weth, premiaMining, feeReceiver, feeDiscountAddress, fee64x64 ) { UNISWAP_V2_FACTORY = uniswapV2Factory; SUSHISWAP_FACTORY = sushiswapFactory; } // calculates the CREATE2 address for a pair without making any external calls function _pairFor( address factory, address tokenA, address tokenB, bool isSushi ) internal pure returns (address pair) { (address token0, address token1) = _sortTokens(tokenA, tokenB); pair = address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), isSushi ? hex"e18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303" : hex"96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f" // init code hash ) ) ) ) ); } // returns sorted token addresses, used to handle return values from pairs sorted in this order function _sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS"); } // performs chained getAmountIn calculations on any number of pairs function _getAmountsIn( address factory, uint256 amountOut, address[] memory path, bool isSushi ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "UniswapV2Library: 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], isSushi ); amounts[i - 1] = _getAmountIn(amounts[i], reserveIn, reserveOut); } } // fetches and sorts the reserves for a pair function _getReserves( address factory, address tokenA, address tokenB, bool isSushi ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = _sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair( _pairFor(factory, tokenA, tokenB, isSushi) ).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // 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, "UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); uint256 numerator = reserveIn * amountOut * 1000; uint256 denominator = (reserveOut - amountOut) * 997; amountIn = (numerator / denominator) + 1; } // requires the initial amount to have already been sent to the first pair function _swap( uint256[] memory amounts, address[] memory path, address _to, bool isSushi ) internal { for (uint256 i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0, ) = _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 ? _pairFor( isSushi ? SUSHISWAP_FACTORY : UNISWAP_V2_FACTORY, output, path[i + 2], isSushi ) : _to; IUniswapV2Pair( _pairFor( isSushi ? SUSHISWAP_FACTORY : UNISWAP_V2_FACTORY, input, output, isSushi ) ).swap(amount0Out, amount1Out, to, new bytes(0)); } } function _swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, bool isSushi ) internal returns (uint256[] memory amounts) { amounts = _getAmountsIn( isSushi ? SUSHISWAP_FACTORY : UNISWAP_V2_FACTORY, amountOut, path, isSushi ); require( amounts[0] <= amountInMax, "UniswapV2Router: EXCESSIVE_INPUT_AMOUNT" ); IERC20(path[0]).safeTransferFrom( msg.sender, _pairFor( isSushi ? SUSHISWAP_FACTORY : UNISWAP_V2_FACTORY, path[0], path[1], isSushi ), amounts[0] ); _swap(amounts, path, msg.sender, isSushi); } function _swapETHForExactTokens( uint256 amountOut, address[] calldata path, bool isSushi ) internal returns (uint256[] memory amounts) { require(path[0] == WETH_ADDRESS, "UniswapV2Router: INVALID_PATH"); amounts = _getAmountsIn( isSushi ? SUSHISWAP_FACTORY : UNISWAP_V2_FACTORY, amountOut, path, isSushi ); require( amounts[0] <= msg.value, "UniswapV2Router: EXCESSIVE_INPUT_AMOUNT" ); IWETH(WETH_ADDRESS).deposit{value: amounts[0]}(); assert( IWETH(WETH_ADDRESS).transfer( _pairFor( isSushi ? SUSHISWAP_FACTORY : UNISWAP_V2_FACTORY, path[0], path[1], isSushi ), amounts[0] ) ); _swap(amounts, path, msg.sender, isSushi); // refund dust eth, if any if (msg.value > amounts[0]) { (bool success, ) = payable(msg.sender).call{ value: msg.value - amounts[0] }(new bytes(0)); require( success, "TransferHelper::safeTransferETH: ETH transfer failed" ); } } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {AggregatorInterface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorInterface.sol"; import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol"; import {EnumerableSet, ERC1155EnumerableStorage} from "@solidstate/contracts/token/ERC1155/enumerable/ERC1155EnumerableStorage.sol"; import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol"; import {ABDKMath64x64Token} from "../libraries/ABDKMath64x64Token.sol"; import {OptionMath} from "../libraries/OptionMath.sol"; library PoolStorage { using ABDKMath64x64 for int128; using PoolStorage for PoolStorage.Layout; enum TokenType { UNDERLYING_FREE_LIQ, BASE_FREE_LIQ, UNDERLYING_RESERVED_LIQ, BASE_RESERVED_LIQ, LONG_CALL, SHORT_CALL, LONG_PUT, SHORT_PUT } struct PoolSettings { address underlying; address base; address underlyingOracle; address baseOracle; } struct QuoteArgsInternal { address feePayer; // address of the fee payer uint64 maturity; // timestamp of option maturity int128 strike64x64; // 64x64 fixed point representation of strike price int128 spot64x64; // 64x64 fixed point representation of spot price uint256 contractSize; // size of option contract bool isCall; // true for call, false for put } struct QuoteResultInternal { int128 baseCost64x64; // 64x64 fixed point representation of option cost denominated in underlying currency (without fee) int128 feeCost64x64; // 64x64 fixed point representation of option fee cost denominated in underlying currency for call, or base currency for put int128 cLevel64x64; // 64x64 fixed point representation of C-Level of Pool after purchase int128 slippageCoefficient64x64; // 64x64 fixed point representation of slippage coefficient for given order size } struct BatchData { uint256 eta; uint256 totalPendingDeposits; } bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.Pool"); uint256 private constant C_DECAY_BUFFER = 12 hours; uint256 private constant C_DECAY_INTERVAL = 4 hours; struct Layout { // ERC20 token addresses address base; address underlying; // AggregatorV3Interface oracle addresses address baseOracle; address underlyingOracle; // token metadata uint8 underlyingDecimals; uint8 baseDecimals; // minimum amounts uint256 baseMinimum; uint256 underlyingMinimum; // deposit caps uint256 basePoolCap; uint256 underlyingPoolCap; // market state int128 _deprecated_steepness64x64; int128 cLevelBase64x64; int128 cLevelUnderlying64x64; uint256 cLevelBaseUpdatedAt; uint256 cLevelUnderlyingUpdatedAt; uint256 updatedAt; // User -> isCall -> depositedAt mapping(address => mapping(bool => uint256)) depositedAt; mapping(address => mapping(bool => uint256)) divestmentTimestamps; // doubly linked list of free liquidity intervals // isCall -> User -> User mapping(bool => mapping(address => address)) liquidityQueueAscending; mapping(bool => mapping(address => address)) liquidityQueueDescending; // minimum resolution price bucket => price mapping(uint256 => int128) bucketPrices64x64; // sequence id (minimum resolution price bucket / 256) => price update sequence mapping(uint256 => uint256) priceUpdateSequences; // isCall -> batch data mapping(bool => BatchData) nextDeposits; // user -> batch timestamp -> isCall -> pending amount mapping(address => mapping(uint256 => mapping(bool => uint256))) pendingDeposits; EnumerableSet.UintSet tokenIds; // user -> isCallPool -> total value locked of user (Used for liquidity mining) mapping(address => mapping(bool => uint256)) userTVL; // isCallPool -> total value locked mapping(bool => uint256) totalTVL; // steepness values int128 steepnessBase64x64; int128 steepnessUnderlying64x64; } function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } /** * @notice calculate ERC1155 token id for given option parameters * @param tokenType TokenType enum * @param maturity timestamp of option maturity * @param strike64x64 64x64 fixed point representation of strike price * @return tokenId token id */ function formatTokenId( TokenType tokenType, uint64 maturity, int128 strike64x64 ) internal pure returns (uint256 tokenId) { tokenId = (uint256(tokenType) << 248) + (uint256(maturity) << 128) + uint256(int256(strike64x64)); } /** * @notice derive option maturity and strike price from ERC1155 token id * @param tokenId token id * @return tokenType TokenType enum * @return maturity timestamp of option maturity * @return strike64x64 option strike price */ function parseTokenId(uint256 tokenId) internal pure returns ( TokenType tokenType, uint64 maturity, int128 strike64x64 ) { assembly { tokenType := shr(248, tokenId) maturity := shr(128, tokenId) strike64x64 := tokenId } } function getTokenDecimals(Layout storage l, bool isCall) internal view returns (uint8 decimals) { decimals = isCall ? l.underlyingDecimals : l.baseDecimals; } /** * @notice get the total supply of free liquidity tokens, minus pending deposits * @param l storage layout struct * @param isCall whether query is for call or put pool * @return 64x64 fixed point representation of total free liquidity */ function totalFreeLiquiditySupply64x64(Layout storage l, bool isCall) internal view returns (int128) { uint256 tokenId = formatTokenId( isCall ? TokenType.UNDERLYING_FREE_LIQ : TokenType.BASE_FREE_LIQ, 0, 0 ); return ABDKMath64x64Token.fromDecimals( ERC1155EnumerableStorage.layout().totalSupply[tokenId] - l.nextDeposits[isCall].totalPendingDeposits, l.getTokenDecimals(isCall) ); } function getReinvestmentStatus( Layout storage l, address account, bool isCallPool ) internal view returns (bool) { uint256 timestamp = l.divestmentTimestamps[account][isCallPool]; return timestamp == 0 || timestamp > block.timestamp; } function addUnderwriter( Layout storage l, address account, bool isCallPool ) internal { require(account != address(0)); mapping(address => address) storage asc = l.liquidityQueueAscending[ isCallPool ]; mapping(address => address) storage desc = l.liquidityQueueDescending[ isCallPool ]; if (_isInQueue(account, asc, desc)) return; address last = desc[address(0)]; asc[last] = account; desc[account] = last; desc[address(0)] = account; } function removeUnderwriter( Layout storage l, address account, bool isCallPool ) internal { require(account != address(0)); mapping(address => address) storage asc = l.liquidityQueueAscending[ isCallPool ]; mapping(address => address) storage desc = l.liquidityQueueDescending[ isCallPool ]; if (!_isInQueue(account, asc, desc)) return; address prev = desc[account]; address next = asc[account]; asc[prev] = next; desc[next] = prev; delete asc[account]; delete desc[account]; } function isInQueue( Layout storage l, address account, bool isCallPool ) internal view returns (bool) { mapping(address => address) storage asc = l.liquidityQueueAscending[ isCallPool ]; mapping(address => address) storage desc = l.liquidityQueueDescending[ isCallPool ]; return _isInQueue(account, asc, desc); } function _isInQueue( address account, mapping(address => address) storage asc, mapping(address => address) storage desc ) private view returns (bool) { return asc[account] != address(0) || desc[address(0)] == account; } /** * @notice get current C-Level, without accounting for pending adjustments * @param l storage layout struct * @param isCall whether query is for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level */ function getRawCLevel64x64(Layout storage l, bool isCall) internal view returns (int128 cLevel64x64) { cLevel64x64 = isCall ? l.cLevelUnderlying64x64 : l.cLevelBase64x64; } /** * @notice get current C-Level, accounting for unrealized decay * @param l storage layout struct * @param isCall whether query is for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level */ function getDecayAdjustedCLevel64x64(Layout storage l, bool isCall) internal view returns (int128 cLevel64x64) { // get raw C-Level from storage cLevel64x64 = l.getRawCLevel64x64(isCall); // account for C-Level decay cLevel64x64 = l.applyCLevelDecayAdjustment(cLevel64x64, isCall); } /** * @notice get updated C-Level and pool liquidity level, accounting for decay and pending deposits * @param l storage layout struct * @param isCall whether to update C-Level for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level * @return liquidity64x64 64x64 fixed point representation of new liquidity amount */ function getRealPoolState(Layout storage l, bool isCall) internal view returns (int128 cLevel64x64, int128 liquidity64x64) { PoolStorage.BatchData storage batchData = l.nextDeposits[isCall]; int128 oldCLevel64x64 = l.getDecayAdjustedCLevel64x64(isCall); int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall); if ( batchData.totalPendingDeposits > 0 && batchData.eta != 0 && block.timestamp >= batchData.eta ) { liquidity64x64 = ABDKMath64x64Token .fromDecimals( batchData.totalPendingDeposits, l.getTokenDecimals(isCall) ) .add(oldLiquidity64x64); cLevel64x64 = l.applyCLevelLiquidityChangeAdjustment( oldCLevel64x64, oldLiquidity64x64, liquidity64x64, isCall ); } else { cLevel64x64 = oldCLevel64x64; liquidity64x64 = oldLiquidity64x64; } } /** * @notice calculate updated C-Level, accounting for unrealized decay * @param l storage layout struct * @param oldCLevel64x64 64x64 fixed point representation pool C-Level before accounting for decay * @param isCall whether query is for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level of Pool after accounting for decay */ function applyCLevelDecayAdjustment( Layout storage l, int128 oldCLevel64x64, bool isCall ) internal view returns (int128 cLevel64x64) { uint256 timeElapsed = block.timestamp - (isCall ? l.cLevelUnderlyingUpdatedAt : l.cLevelBaseUpdatedAt); // do not apply C decay if less than 24 hours have elapsed if (timeElapsed > C_DECAY_BUFFER) { timeElapsed -= C_DECAY_BUFFER; } else { return oldCLevel64x64; } int128 timeIntervalsElapsed64x64 = ABDKMath64x64.divu( timeElapsed, C_DECAY_INTERVAL ); uint256 tokenId = formatTokenId( isCall ? TokenType.UNDERLYING_FREE_LIQ : TokenType.BASE_FREE_LIQ, 0, 0 ); uint256 tvl = l.totalTVL[isCall]; int128 utilization = ABDKMath64x64.divu( tvl - (ERC1155EnumerableStorage.layout().totalSupply[tokenId] - l.nextDeposits[isCall].totalPendingDeposits), tvl ); return OptionMath.calculateCLevelDecay( OptionMath.CalculateCLevelDecayArgs( timeIntervalsElapsed64x64, oldCLevel64x64, utilization, 0xb333333333333333, // 0.7 0xe666666666666666, // 0.9 0x10000000000000000, // 1.0 0x10000000000000000, // 1.0 0xe666666666666666, // 0.9 0x56fc2a2c515da32ea // 2e ) ); } /** * @notice calculate updated C-Level, accounting for change in liquidity * @param l storage layout struct * @param oldCLevel64x64 64x64 fixed point representation pool C-Level before accounting for liquidity change * @param oldLiquidity64x64 64x64 fixed point representation of previous liquidity * @param newLiquidity64x64 64x64 fixed point representation of current liquidity * @param isCallPool whether to update C-Level for call or put pool * @return cLevel64x64 64x64 fixed point representation of C-Level */ function applyCLevelLiquidityChangeAdjustment( Layout storage l, int128 oldCLevel64x64, int128 oldLiquidity64x64, int128 newLiquidity64x64, bool isCallPool ) internal view returns (int128 cLevel64x64) { int128 steepness64x64 = isCallPool ? l.steepnessUnderlying64x64 : l.steepnessBase64x64; // fallback to deprecated storage value if side-specific value is not set if (steepness64x64 == 0) steepness64x64 = l._deprecated_steepness64x64; cLevel64x64 = OptionMath.calculateCLevel( oldCLevel64x64, oldLiquidity64x64, newLiquidity64x64, steepness64x64 ); if (cLevel64x64 < 0xb333333333333333) { cLevel64x64 = int128(0xb333333333333333); // 64x64 fixed point representation of 0.7 } } /** * @notice set C-Level to arbitrary pre-calculated value * @param cLevel64x64 new C-Level of pool * @param isCallPool whether to update C-Level for call or put pool */ function setCLevel( Layout storage l, int128 cLevel64x64, bool isCallPool ) internal { if (isCallPool) { l.cLevelUnderlying64x64 = cLevel64x64; l.cLevelUnderlyingUpdatedAt = block.timestamp; } else { l.cLevelBase64x64 = cLevel64x64; l.cLevelBaseUpdatedAt = block.timestamp; } } function setOracles( Layout storage l, address baseOracle, address underlyingOracle ) internal { require( AggregatorV3Interface(baseOracle).decimals() == AggregatorV3Interface(underlyingOracle).decimals(), "Pool: oracle decimals must match" ); l.baseOracle = baseOracle; l.underlyingOracle = underlyingOracle; } function fetchPriceUpdate(Layout storage l) internal view returns (int128 price64x64) { int256 priceUnderlying = AggregatorInterface(l.underlyingOracle) .latestAnswer(); int256 priceBase = AggregatorInterface(l.baseOracle).latestAnswer(); return ABDKMath64x64.divi(priceUnderlying, priceBase); } /** * @notice set price update for hourly bucket corresponding to given timestamp * @param l storage layout struct * @param timestamp timestamp to update * @param price64x64 64x64 fixed point representation of price */ function setPriceUpdate( Layout storage l, uint256 timestamp, int128 price64x64 ) internal { uint256 bucket = timestamp / (1 hours); l.bucketPrices64x64[bucket] = price64x64; l.priceUpdateSequences[bucket >> 8] += 1 << (255 - (bucket & 255)); } /** * @notice get price update for hourly bucket corresponding to given timestamp * @param l storage layout struct * @param timestamp timestamp to query * @return 64x64 fixed point representation of price */ function getPriceUpdate(Layout storage l, uint256 timestamp) internal view returns (int128) { return l.bucketPrices64x64[timestamp / (1 hours)]; } /** * @notice get first price update available following given timestamp * @param l storage layout struct * @param timestamp timestamp to query * @return 64x64 fixed point representation of price */ function getPriceUpdateAfter(Layout storage l, uint256 timestamp) internal view returns (int128) { // price updates are grouped into hourly buckets uint256 bucket = timestamp / (1 hours); // divide by 256 to get the index of the relevant price update sequence uint256 sequenceId = bucket >> 8; // get position within sequence relevant to current price update uint256 offset = bucket & 255; // shift to skip buckets from earlier in sequence uint256 sequence = (l.priceUpdateSequences[sequenceId] << offset) >> offset; // iterate through future sequences until a price update is found // sequence corresponding to current timestamp used as upper bound uint256 currentPriceUpdateSequenceId = block.timestamp / (256 hours); while (sequence == 0 && sequenceId <= currentPriceUpdateSequenceId) { sequence = l.priceUpdateSequences[++sequenceId]; } // if no price update is found (sequence == 0) function will return 0 // this should never occur, as each relevant external function triggers a price update // the most significant bit of the sequence corresponds to the offset of the relevant bucket uint256 msb; for (uint256 i = 128; i > 0; i >>= 1) { if (sequence >> i > 0) { msb += i; sequence >>= i; } } return l.bucketPrices64x64[((sequenceId + 1) << 8) - msb - 1]; } function fromBaseToUnderlyingDecimals(Layout storage l, uint256 value) internal view returns (uint256) { int128 valueFixed64x64 = ABDKMath64x64Token.fromDecimals( value, l.baseDecimals ); return ABDKMath64x64Token.toDecimals( valueFixed64x64, l.underlyingDecimals ); } function fromUnderlyingToBaseDecimals(Layout storage l, uint256 value) internal view returns (uint256) { int128 valueFixed64x64 = ABDKMath64x64Token.fromDecimals( value, l.underlyingDecimals ); return ABDKMath64x64Token.toDecimals(valueFixed64x64, l.baseDecimals); } } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; import {PremiaMiningStorage} from "./PremiaMiningStorage.sol"; interface IPremiaMining { function addPremiaRewards(uint256 _amount) external; function premiaRewardsAvailable() external view returns (uint256); function getTotalAllocationPoints() external view returns (uint256); function getPoolInfo(address pool, bool isCallPool) external view returns (PremiaMiningStorage.PoolInfo memory); function getPremiaPerYear() external view returns (uint256); function addPool(address _pool, uint256 _allocPoints) external; function setPoolAllocPoints( address[] memory _pools, uint256[] memory _allocPoints ) external; function pendingPremia( address _pool, bool _isCallPool, address _user ) external view returns (uint256); function updatePool( address _pool, bool _isCallPool, uint256 _totalTVL ) external; function allocatePending( address _user, address _pool, bool _isCallPool, uint256 _userTVLOld, uint256 _userTVLNew, uint256 _totalTVL ) external; function claim( address _user, address _pool, bool _isCallPool, uint256 _userTVLOld, uint256 _userTVLNew, uint256 _totalTVL ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC20 } from '../token/ERC20/IERC20.sol'; import { IERC20Metadata } from '../token/ERC20/metadata/IERC20Metadata.sol'; /** * @title WETH (Wrapped ETH) interface */ interface IWETH is IERC20, IERC20Metadata { /** * @notice convert ETH to WETH */ function deposit() external payable; /** * @notice convert WETH to ETH * @dev if caller is a contract, it should have a fallback or receive function * @param amount quantity of WETH to convert, denominated in wei */ function withdraw(uint256 amount) external; } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC20 } from '../token/ERC20/IERC20.sol'; import { AddressUtils } from './AddressUtils.sol'; /** * @title Safe ERC20 interaction library * @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts/ (MIT license) */ library SafeERC20 { using AddressUtils 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 safeApprove (like approve) should only be called when setting an initial allowance or when resetting it to zero; otherwise prefer safeIncreaseAllowance and safeDecreaseAllowance */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { require( (value == 0) || (token.allowance(address(this), spender) == 0), 'SafeERC20: approve from non-zero to non-zero allowance' ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function 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 ) ); } } /** * @notice send transaction data and check validity of return value, if present * @param token ERC20 token interface * @param data transaction data */ function _callOptionalReturn(IERC20 token, bytes memory data) private { bytes memory returndata = address(token).functionCall( data, 'SafeERC20: low-level call failed' ); if (returndata.length > 0) { require( abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed' ); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC20Internal } from './IERC20Internal.sol'; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 is IERC20Internal { /** * @notice query the total minted token supply * @return token supply */ function totalSupply() external view returns (uint256); /** * @notice query the token balance of given account * @param account address to query * @return token balance */ function balanceOf(address account) external view returns (uint256); /** * @notice query the allowance granted from given holder to given spender * @param holder approver of allowance * @param spender recipient of allowance * @return token allowance */ function allowance(address holder, address spender) external view returns (uint256); /** * @notice grant approval to spender to spend tokens * @dev prefer ERC20Extended functions to avoid transaction-ordering vulnerability (see https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729) * @param spender recipient of allowance * @param amount quantity of tokens approved for spending * @return success status (always true; otherwise function should revert) */ function approve(address spender, uint256 amount) external returns (bool); /** * @notice transfer tokens to given recipient * @param recipient beneficiary of token transfer * @param amount quantity of tokens to transfer * @return success status (always true; otherwise function should revert) */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @notice transfer tokens to given recipient on behalf of given holder * @param holder holder of tokens prior to transfer * @param recipient beneficiary of token transfer * @param amount quantity of tokens to transfer * @return success status (always true; otherwise function should revert) */ function transferFrom( address holder, address recipient, uint256 amount ) external returns (bool); } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {IERC173} from "@solidstate/contracts/access/IERC173.sol"; import {OwnableStorage} from "@solidstate/contracts/access/OwnableStorage.sol"; import {IERC20} from "@solidstate/contracts/token/ERC20/IERC20.sol"; import {ERC1155EnumerableInternal, ERC1155EnumerableStorage, EnumerableSet} from "@solidstate/contracts/token/ERC1155/enumerable/ERC1155Enumerable.sol"; import {IWETH} from "@solidstate/contracts/utils/IWETH.sol"; import {PoolStorage} from "./PoolStorage.sol"; import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol"; import {ABDKMath64x64Token} from "../libraries/ABDKMath64x64Token.sol"; import {OptionMath} from "../libraries/OptionMath.sol"; import {IFeeDiscount} from "../staking/IFeeDiscount.sol"; import {IPoolEvents} from "./IPoolEvents.sol"; import {IPremiaMining} from "../mining/IPremiaMining.sol"; import {IVolatilitySurfaceOracle} from "../oracle/IVolatilitySurfaceOracle.sol"; /** * @title Premia option pool * @dev deployed standalone and referenced by PoolProxy */ contract PoolInternal is IPoolEvents, ERC1155EnumerableInternal { using ABDKMath64x64 for int128; using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.UintSet; using PoolStorage for PoolStorage.Layout; address internal immutable WETH_ADDRESS; address internal immutable PREMIA_MINING_ADDRESS; address internal immutable FEE_RECEIVER_ADDRESS; address internal immutable FEE_DISCOUNT_ADDRESS; address internal immutable IVOL_ORACLE_ADDRESS; int128 internal immutable FEE_64x64; uint256 internal immutable UNDERLYING_FREE_LIQ_TOKEN_ID; uint256 internal immutable BASE_FREE_LIQ_TOKEN_ID; uint256 internal immutable UNDERLYING_RESERVED_LIQ_TOKEN_ID; uint256 internal immutable BASE_RESERVED_LIQ_TOKEN_ID; uint256 internal constant INVERSE_BASIS_POINT = 1e4; uint256 internal constant BATCHING_PERIOD = 260; // Minimum APY for capital locked up to underwrite options. // The quote will return a minimum price corresponding to this APY int128 internal constant MIN_APY_64x64 = 0x4ccccccccccccccd; // 0.3 constructor( address ivolOracle, address weth, address premiaMining, address feeReceiver, address feeDiscountAddress, int128 fee64x64 ) { IVOL_ORACLE_ADDRESS = ivolOracle; WETH_ADDRESS = weth; PREMIA_MINING_ADDRESS = premiaMining; FEE_RECEIVER_ADDRESS = feeReceiver; // PremiaFeeDiscount contract address FEE_DISCOUNT_ADDRESS = feeDiscountAddress; FEE_64x64 = fee64x64; UNDERLYING_FREE_LIQ_TOKEN_ID = PoolStorage.formatTokenId( PoolStorage.TokenType.UNDERLYING_FREE_LIQ, 0, 0 ); BASE_FREE_LIQ_TOKEN_ID = PoolStorage.formatTokenId( PoolStorage.TokenType.BASE_FREE_LIQ, 0, 0 ); UNDERLYING_RESERVED_LIQ_TOKEN_ID = PoolStorage.formatTokenId( PoolStorage.TokenType.UNDERLYING_RESERVED_LIQ, 0, 0 ); BASE_RESERVED_LIQ_TOKEN_ID = PoolStorage.formatTokenId( PoolStorage.TokenType.BASE_RESERVED_LIQ, 0, 0 ); } modifier onlyProtocolOwner() { require( msg.sender == IERC173(OwnableStorage.layout().owner).owner(), "Not protocol owner" ); _; } function _getFeeDiscount(address feePayer) internal view returns (uint256 discount) { if (FEE_DISCOUNT_ADDRESS != address(0)) { discount = IFeeDiscount(FEE_DISCOUNT_ADDRESS).getDiscount(feePayer); } } function _getFeeWithDiscount(address feePayer, uint256 fee) internal view returns (uint256) { uint256 discount = _getFeeDiscount(feePayer); return fee - ((fee * discount) / INVERSE_BASIS_POINT); } function _withdrawFees(bool isCall) internal returns (uint256 amount) { uint256 tokenId = _getReservedLiquidityTokenId(isCall); amount = _balanceOf(FEE_RECEIVER_ADDRESS, tokenId); if (amount > 0) { _burn(FEE_RECEIVER_ADDRESS, tokenId, amount); emit FeeWithdrawal(isCall, amount); } } /** * @notice calculate price of option contract * @param args structured quote arguments * @return result quote result */ function _quote(PoolStorage.QuoteArgsInternal memory args) internal view returns (PoolStorage.QuoteResultInternal memory result) { require( args.strike64x64 > 0 && args.spot64x64 > 0 && args.maturity > 0, "invalid args" ); PoolStorage.Layout storage l = PoolStorage.layout(); int128 contractSize64x64 = ABDKMath64x64Token.fromDecimals( args.contractSize, l.underlyingDecimals ); (int128 adjustedCLevel64x64, int128 oldLiquidity64x64) = l .getRealPoolState(args.isCall); require(oldLiquidity64x64 > 0, "no liq"); int128 timeToMaturity64x64 = ABDKMath64x64.divu( args.maturity - block.timestamp, 365 days ); int128 annualizedVolatility64x64 = IVolatilitySurfaceOracle( IVOL_ORACLE_ADDRESS ).getAnnualizedVolatility64x64( l.base, l.underlying, args.spot64x64, args.strike64x64, timeToMaturity64x64, args.isCall ); require(annualizedVolatility64x64 > 0, "vol = 0"); int128 collateral64x64 = args.isCall ? contractSize64x64 : contractSize64x64.mul(args.strike64x64); ( int128 price64x64, int128 cLevel64x64, int128 slippageCoefficient64x64 ) = OptionMath.quotePrice( OptionMath.QuoteArgs( annualizedVolatility64x64.mul(annualizedVolatility64x64), args.strike64x64, args.spot64x64, timeToMaturity64x64, adjustedCLevel64x64, oldLiquidity64x64, oldLiquidity64x64.sub(collateral64x64), 0x10000000000000000, // 64x64 fixed point representation of 1 MIN_APY_64x64, args.isCall ) ); result.baseCost64x64 = args.isCall ? price64x64.mul(contractSize64x64).div(args.spot64x64) : price64x64.mul(contractSize64x64); result.feeCost64x64 = result.baseCost64x64.mul(FEE_64x64); result.cLevel64x64 = cLevel64x64; result.slippageCoefficient64x64 = slippageCoefficient64x64; int128 discount = ABDKMath64x64.divu( _getFeeDiscount(args.feePayer), INVERSE_BASIS_POINT ); result.feeCost64x64 -= result.feeCost64x64.mul(discount); } /** * @notice burn corresponding long and short option tokens * @param account holder of tokens to annihilate * @param maturity timestamp of option maturity * @param strike64x64 64x64 fixed point representation of strike price * @param isCall true for call, false for put * @param contractSize quantity of option contract tokens to annihilate */ function _annihilate( address account, uint64 maturity, int128 strike64x64, bool isCall, uint256 contractSize ) internal { uint256 longTokenId = PoolStorage.formatTokenId( _getTokenType(isCall, true), maturity, strike64x64 ); uint256 shortTokenId = PoolStorage.formatTokenId( _getTokenType(isCall, false), maturity, strike64x64 ); _burn(account, longTokenId, contractSize); _burn(account, shortTokenId, contractSize); emit Annihilate(shortTokenId, contractSize); } /** * @notice purchase option * @param l storage layout struct * @param account recipient of purchased option * @param maturity timestamp of option maturity * @param strike64x64 64x64 fixed point representation of strike price * @param isCall true for call, false for put * @param contractSize size of option contract * @param newPrice64x64 64x64 fixed point representation of current spot price * @return baseCost quantity of tokens required to purchase long position * @return feeCost quantity of tokens required to pay fees */ function _purchase( PoolStorage.Layout storage l, address account, uint64 maturity, int128 strike64x64, bool isCall, uint256 contractSize, int128 newPrice64x64 ) internal returns (uint256 baseCost, uint256 feeCost) { require(maturity > block.timestamp, "expired"); require(contractSize >= l.underlyingMinimum, "too small"); { uint256 size = isCall ? contractSize : l.fromUnderlyingToBaseDecimals( strike64x64.mulu(contractSize) ); require( size <= ERC1155EnumerableStorage.layout().totalSupply[ _getFreeLiquidityTokenId(isCall) ] - l.nextDeposits[isCall].totalPendingDeposits, "insuf liq" ); } PoolStorage.QuoteResultInternal memory quote = _quote( PoolStorage.QuoteArgsInternal( account, maturity, strike64x64, newPrice64x64, contractSize, isCall ) ); baseCost = ABDKMath64x64Token.toDecimals( quote.baseCost64x64, l.getTokenDecimals(isCall) ); feeCost = ABDKMath64x64Token.toDecimals( quote.feeCost64x64, l.getTokenDecimals(isCall) ); uint256 longTokenId = PoolStorage.formatTokenId( _getTokenType(isCall, true), maturity, strike64x64 ); uint256 shortTokenId = PoolStorage.formatTokenId( _getTokenType(isCall, false), maturity, strike64x64 ); // mint long option token for buyer _mint(account, longTokenId, contractSize); int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall); // burn free liquidity tokens from other underwriters _mintShortTokenLoop( l, account, contractSize, baseCost, shortTokenId, isCall ); int128 newLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall); _setCLevel(l, oldLiquidity64x64, newLiquidity64x64, isCall); // mint reserved liquidity tokens for fee receiver _mint( FEE_RECEIVER_ADDRESS, _getReservedLiquidityTokenId(isCall), feeCost ); emit Purchase( account, longTokenId, contractSize, baseCost, feeCost, newPrice64x64 ); } /** * @notice reassign short position to new underwriter * @param l storage layout struct * @param account holder of positions to be reassigned * @param maturity timestamp of option maturity * @param strike64x64 64x64 fixed point representation of strike price * @param isCall true for call, false for put * @param contractSize quantity of option contract tokens to reassign * @param newPrice64x64 64x64 fixed point representation of current spot price * @return baseCost quantity of tokens required to reassign short position * @return feeCost quantity of tokens required to pay fees * @return amountOut quantity of liquidity freed */ function _reassign( PoolStorage.Layout storage l, address account, uint64 maturity, int128 strike64x64, bool isCall, uint256 contractSize, int128 newPrice64x64 ) internal returns ( uint256 baseCost, uint256 feeCost, uint256 amountOut ) { (baseCost, feeCost) = _purchase( l, account, maturity, strike64x64, isCall, contractSize, newPrice64x64 ); _annihilate(account, maturity, strike64x64, isCall, contractSize); uint256 annihilateAmount = isCall ? contractSize : l.fromUnderlyingToBaseDecimals(strike64x64.mulu(contractSize)); amountOut = annihilateAmount - baseCost - feeCost; } /** * @notice exercise option on behalf of holder * @dev used for processing of expired options if passed holder is zero address * @param holder owner of long option tokens to exercise * @param longTokenId long option token id * @param contractSize quantity of tokens to exercise */ function _exercise( address holder, uint256 longTokenId, uint256 contractSize ) internal { uint64 maturity; int128 strike64x64; bool isCall; bool onlyExpired = holder == address(0); { PoolStorage.TokenType tokenType; (tokenType, maturity, strike64x64) = PoolStorage.parseTokenId( longTokenId ); require( tokenType == PoolStorage.TokenType.LONG_CALL || tokenType == PoolStorage.TokenType.LONG_PUT, "invalid type" ); require(!onlyExpired || maturity < block.timestamp, "not expired"); isCall = tokenType == PoolStorage.TokenType.LONG_CALL; } PoolStorage.Layout storage l = PoolStorage.layout(); int128 spot64x64 = _update(l); if (maturity < block.timestamp) { spot64x64 = l.getPriceUpdateAfter(maturity); } require( onlyExpired || ( isCall ? (spot64x64 > strike64x64) : (spot64x64 < strike64x64) ), "not ITM" ); uint256 exerciseValue; // option has a non-zero exercise value if (isCall) { if (spot64x64 > strike64x64) { exerciseValue = spot64x64.sub(strike64x64).div(spot64x64).mulu( contractSize ); } } else { if (spot64x64 < strike64x64) { exerciseValue = l.fromUnderlyingToBaseDecimals( strike64x64.sub(spot64x64).mulu(contractSize) ); } } uint256 totalFee; if (onlyExpired) { totalFee += _burnLongTokenLoop( contractSize, exerciseValue, longTokenId, isCall ); } else { // burn long option tokens from sender _burn(holder, longTokenId, contractSize); uint256 fee; if (exerciseValue > 0) { fee = _getFeeWithDiscount( holder, FEE_64x64.mulu(exerciseValue) ); totalFee += fee; _pushTo(holder, _getPoolToken(isCall), exerciseValue - fee); } emit Exercise( holder, longTokenId, contractSize, exerciseValue, fee ); } totalFee += _burnShortTokenLoop( contractSize, exerciseValue, PoolStorage.formatTokenId( _getTokenType(isCall, false), maturity, strike64x64 ), isCall ); _mint( FEE_RECEIVER_ADDRESS, _getReservedLiquidityTokenId(isCall), totalFee ); } function _mintShortTokenLoop( PoolStorage.Layout storage l, address buyer, uint256 contractSize, uint256 premium, uint256 shortTokenId, bool isCall ) internal { uint256 freeLiqTokenId = _getFreeLiquidityTokenId(isCall); (, , int128 strike64x64) = PoolStorage.parseTokenId(shortTokenId); uint256 toPay = isCall ? contractSize : l.fromUnderlyingToBaseDecimals(strike64x64.mulu(contractSize)); while (toPay > 0) { address underwriter = l.liquidityQueueAscending[isCall][address(0)]; uint256 balance = _balanceOf(underwriter, freeLiqTokenId); // If dust left, we remove underwriter and skip to next if (balance < _getMinimumAmount(l, isCall)) { l.removeUnderwriter(underwriter, isCall); continue; } if (!l.getReinvestmentStatus(underwriter, isCall)) { _burn(underwriter, freeLiqTokenId, balance); _mint( underwriter, _getReservedLiquidityTokenId(isCall), balance ); _subUserTVL(l, underwriter, isCall, balance); continue; } // amount of liquidity provided by underwriter, accounting for reinvested premium uint256 intervalContractSize = ((balance - l.pendingDeposits[underwriter][l.nextDeposits[isCall].eta][ isCall ]) * (toPay + premium)) / toPay; if (intervalContractSize == 0) continue; if (intervalContractSize > toPay) intervalContractSize = toPay; // amount of premium paid to underwriter uint256 intervalPremium = (premium * intervalContractSize) / toPay; premium -= intervalPremium; toPay -= intervalContractSize; _addUserTVL(l, underwriter, isCall, intervalPremium); // burn free liquidity tokens from underwriter _burn( underwriter, freeLiqTokenId, intervalContractSize - intervalPremium ); if (isCall == false) { // For PUT, conversion to contract amount is done here (Prior to this line, it is token amount) intervalContractSize = l.fromBaseToUnderlyingDecimals( strike64x64.inv().mulu(intervalContractSize) ); } // mint short option tokens for underwriter // toPay == 0 ? contractSize : intervalContractSize : To prevent minting less than amount, // because of rounding (Can happen for put, because of fixed point precision) _mint( underwriter, shortTokenId, toPay == 0 ? contractSize : intervalContractSize ); emit Underwrite( underwriter, buyer, shortTokenId, toPay == 0 ? contractSize : intervalContractSize, intervalPremium, false ); contractSize -= intervalContractSize; } } function _burnLongTokenLoop( uint256 contractSize, uint256 exerciseValue, uint256 longTokenId, bool isCall ) internal returns (uint256 totalFee) { EnumerableSet.AddressSet storage holders = ERC1155EnumerableStorage .layout() .accountsByToken[longTokenId]; while (contractSize > 0) { address longTokenHolder = holders.at(holders.length() - 1); uint256 intervalContractSize = _balanceOf( longTokenHolder, longTokenId ); if (intervalContractSize > contractSize) intervalContractSize = contractSize; uint256 intervalExerciseValue; uint256 fee; if (exerciseValue > 0) { intervalExerciseValue = (exerciseValue * intervalContractSize) / contractSize; fee = _getFeeWithDiscount( longTokenHolder, FEE_64x64.mulu(intervalExerciseValue) ); totalFee += fee; exerciseValue -= intervalExerciseValue; _pushTo( longTokenHolder, _getPoolToken(isCall), intervalExerciseValue - fee ); } contractSize -= intervalContractSize; emit Exercise( longTokenHolder, longTokenId, intervalContractSize, intervalExerciseValue - fee, fee ); _burn(longTokenHolder, longTokenId, intervalContractSize); } } function _burnShortTokenLoop( uint256 contractSize, uint256 exerciseValue, uint256 shortTokenId, bool isCall ) internal returns (uint256 totalFee) { EnumerableSet.AddressSet storage underwriters = ERC1155EnumerableStorage .layout() .accountsByToken[shortTokenId]; (, , int128 strike64x64) = PoolStorage.parseTokenId(shortTokenId); while (contractSize > 0) { address underwriter = underwriters.at(underwriters.length() - 1); // amount of liquidity provided by underwriter uint256 intervalContractSize = _balanceOf( underwriter, shortTokenId ); if (intervalContractSize > contractSize) intervalContractSize = contractSize; // amount of value claimed by buyer uint256 intervalExerciseValue = (exerciseValue * intervalContractSize) / contractSize; exerciseValue -= intervalExerciseValue; contractSize -= intervalContractSize; uint256 freeLiq = isCall ? intervalContractSize - intervalExerciseValue : PoolStorage.layout().fromUnderlyingToBaseDecimals( strike64x64.mulu(intervalContractSize) ) - intervalExerciseValue; uint256 fee = _getFeeWithDiscount( underwriter, FEE_64x64.mulu(freeLiq) ); totalFee += fee; uint256 tvlToSubtract = intervalExerciseValue; // mint free liquidity tokens for underwriter if ( PoolStorage.layout().getReinvestmentStatus(underwriter, isCall) ) { _addToDepositQueue(underwriter, freeLiq - fee, isCall); tvlToSubtract += fee; } else { _mint( underwriter, _getReservedLiquidityTokenId(isCall), freeLiq - fee ); tvlToSubtract += freeLiq; } _subUserTVL( PoolStorage.layout(), underwriter, isCall, tvlToSubtract ); // burn short option tokens from underwriter _burn(underwriter, shortTokenId, intervalContractSize); emit AssignExercise( underwriter, shortTokenId, freeLiq - fee, intervalContractSize, fee ); } } function _addToDepositQueue( address account, uint256 amount, bool isCallPool ) internal { PoolStorage.Layout storage l = PoolStorage.layout(); _mint(account, _getFreeLiquidityTokenId(isCallPool), amount); uint256 nextBatch = (block.timestamp / BATCHING_PERIOD) * BATCHING_PERIOD + BATCHING_PERIOD; l.pendingDeposits[account][nextBatch][isCallPool] += amount; PoolStorage.BatchData storage batchData = l.nextDeposits[isCallPool]; batchData.totalPendingDeposits += amount; batchData.eta = nextBatch; } function _processPendingDeposits(PoolStorage.Layout storage l, bool isCall) internal { PoolStorage.BatchData storage data = l.nextDeposits[isCall]; if (data.eta == 0 || block.timestamp < data.eta) return; int128 oldLiquidity64x64 = l.totalFreeLiquiditySupply64x64(isCall); _setCLevel( l, oldLiquidity64x64, oldLiquidity64x64.add( ABDKMath64x64Token.fromDecimals( data.totalPendingDeposits, l.getTokenDecimals(isCall) ) ), isCall ); delete l.nextDeposits[isCall]; } function _getFreeLiquidityTokenId(bool isCall) internal view returns (uint256 freeLiqTokenId) { freeLiqTokenId = isCall ? UNDERLYING_FREE_LIQ_TOKEN_ID : BASE_FREE_LIQ_TOKEN_ID; } function _getReservedLiquidityTokenId(bool isCall) internal view returns (uint256 reservedLiqTokenId) { reservedLiqTokenId = isCall ? UNDERLYING_RESERVED_LIQ_TOKEN_ID : BASE_RESERVED_LIQ_TOKEN_ID; } function _getPoolToken(bool isCall) internal view returns (address token) { token = isCall ? PoolStorage.layout().underlying : PoolStorage.layout().base; } function _getTokenType(bool isCall, bool isLong) internal pure returns (PoolStorage.TokenType tokenType) { if (isCall) { tokenType = isLong ? PoolStorage.TokenType.LONG_CALL : PoolStorage.TokenType.SHORT_CALL; } else { tokenType = isLong ? PoolStorage.TokenType.LONG_PUT : PoolStorage.TokenType.SHORT_PUT; } } function _getMinimumAmount(PoolStorage.Layout storage l, bool isCall) internal view returns (uint256 minimumAmount) { minimumAmount = isCall ? l.underlyingMinimum : l.baseMinimum; } function _getPoolCapAmount(PoolStorage.Layout storage l, bool isCall) internal view returns (uint256 poolCapAmount) { poolCapAmount = isCall ? l.underlyingPoolCap : l.basePoolCap; } function _setCLevel( PoolStorage.Layout storage l, int128 oldLiquidity64x64, int128 newLiquidity64x64, bool isCallPool ) internal { int128 oldCLevel64x64 = l.getDecayAdjustedCLevel64x64(isCallPool); int128 cLevel64x64 = l.applyCLevelLiquidityChangeAdjustment( oldCLevel64x64, oldLiquidity64x64, newLiquidity64x64, isCallPool ); l.setCLevel(cLevel64x64, isCallPool); emit UpdateCLevel( isCallPool, cLevel64x64, oldLiquidity64x64, newLiquidity64x64 ); } /** * @notice calculate and store updated market state * @param l storage layout struct * @return newPrice64x64 64x64 fixed point representation of current spot price */ function _update(PoolStorage.Layout storage l) internal returns (int128 newPrice64x64) { if (l.updatedAt == block.timestamp) { return (l.getPriceUpdate(block.timestamp)); } newPrice64x64 = l.fetchPriceUpdate(); if (l.getPriceUpdate(block.timestamp) == 0) { l.setPriceUpdate(block.timestamp, newPrice64x64); } l.updatedAt = block.timestamp; _processPendingDeposits(l, true); _processPendingDeposits(l, false); } /** * @notice transfer ERC20 tokens to message sender * @param token ERC20 token address * @param amount quantity of token to transfer */ function _pushTo( address to, address token, uint256 amount ) internal { if (amount == 0) return; require(IERC20(token).transfer(to, amount), "ERC20 transfer failed"); } /** * @notice transfer ERC20 tokens from message sender * @param from address from which tokens are pulled from * @param token ERC20 token address * @param amount quantity of token to transfer * @param skipWethDeposit if false, will not try to deposit weth from attach eth */ function _pullFrom( address from, address token, uint256 amount, bool skipWethDeposit ) internal { if (!skipWethDeposit) { if (token == WETH_ADDRESS) { if (msg.value > 0) { if (msg.value > amount) { IWETH(WETH_ADDRESS).deposit{value: amount}(); (bool success, ) = payable(msg.sender).call{ value: msg.value - amount }(""); require(success, "ETH refund failed"); amount = 0; } else { unchecked { amount -= msg.value; } IWETH(WETH_ADDRESS).deposit{value: msg.value}(); } } } else { require(msg.value == 0, "not WETH deposit"); } } if (amount > 0) { require( IERC20(token).transferFrom(from, address(this), amount), "ERC20 transfer failed" ); } } function _mint( address account, uint256 tokenId, uint256 amount ) internal { _mint(account, tokenId, amount, ""); } function _addUserTVL( PoolStorage.Layout storage l, address user, bool isCallPool, uint256 amount ) internal { uint256 userTVL = l.userTVL[user][isCallPool]; uint256 totalTVL = l.totalTVL[isCallPool]; IPremiaMining(PREMIA_MINING_ADDRESS).allocatePending( user, address(this), isCallPool, userTVL, userTVL + amount, totalTVL ); l.userTVL[user][isCallPool] = userTVL + amount; l.totalTVL[isCallPool] = totalTVL + amount; } function _subUserTVL( PoolStorage.Layout storage l, address user, bool isCallPool, uint256 amount ) internal { uint256 userTVL = l.userTVL[user][isCallPool]; uint256 totalTVL = l.totalTVL[isCallPool]; IPremiaMining(PREMIA_MINING_ADDRESS).allocatePending( user, address(this), isCallPool, userTVL, userTVL - amount, totalTVL ); l.userTVL[user][isCallPool] = userTVL - amount; l.totalTVL[isCallPool] = totalTVL - amount; } /** * @notice ERC1155 hook: track eligible underwriters * @param operator transaction sender * @param from token sender * @param to token receiver * @param ids token ids transferred * @param amounts token quantities transferred * @param data data payload */ 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); PoolStorage.Layout storage l = PoolStorage.layout(); for (uint256 i; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; if (amount == 0) continue; if (from == address(0)) { l.tokenIds.add(id); } if ( to == address(0) && ERC1155EnumerableStorage.layout().totalSupply[id] == 0 ) { l.tokenIds.remove(id); } // prevent transfer of free and reserved liquidity during waiting period if ( id == UNDERLYING_FREE_LIQ_TOKEN_ID || id == BASE_FREE_LIQ_TOKEN_ID || id == UNDERLYING_RESERVED_LIQ_TOKEN_ID || id == BASE_RESERVED_LIQ_TOKEN_ID ) { if (from != address(0) && to != address(0)) { bool isCallPool = id == UNDERLYING_FREE_LIQ_TOKEN_ID || id == UNDERLYING_RESERVED_LIQ_TOKEN_ID; require( l.depositedAt[from][isCallPool] + (1 days) < block.timestamp, "liq lock 1d" ); } } if ( id == UNDERLYING_FREE_LIQ_TOKEN_ID || id == BASE_FREE_LIQ_TOKEN_ID ) { bool isCallPool = id == UNDERLYING_FREE_LIQ_TOKEN_ID; uint256 minimum = _getMinimumAmount(l, isCallPool); if (from != address(0)) { uint256 balance = _balanceOf(from, id); if (balance > minimum && balance <= amount + minimum) { require( balance - l.pendingDeposits[from][ l.nextDeposits[isCallPool].eta ][isCallPool] >= amount, "Insuf balance" ); l.removeUnderwriter(from, isCallPool); } if (to != address(0)) { _subUserTVL(l, from, isCallPool, amounts[i]); _addUserTVL(l, to, isCallPool, amounts[i]); } } if (to != address(0)) { uint256 balance = _balanceOf(to, id); if (balance <= minimum && balance + amount > minimum) { l.addUnderwriter(to, isCallPool); } } } // Update userTVL on SHORT options transfers ( PoolStorage.TokenType tokenType, , int128 strike64x64 ) = PoolStorage.parseTokenId(id); if ( (from != address(0) && to != address(0)) && (tokenType == PoolStorage.TokenType.SHORT_CALL || tokenType == PoolStorage.TokenType.SHORT_PUT) ) { bool isCall = tokenType == PoolStorage.TokenType.SHORT_CALL; uint256 collateral = isCall ? amount : l.fromUnderlyingToBaseDecimals(strike64x64.mulu(amount)); _subUserTVL(l, from, isCall, collateral); _addUserTVL(l, to, isCall, collateral); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AggregatorInterface { function latestAnswer() external view returns ( int256 ); function latestTimestamp() external view returns ( uint256 ); function latestRound() external view returns ( uint256 ); function getAnswer( uint256 roundId ) external view returns ( int256 ); function getTimestamp( uint256 roundId ) external view returns ( uint256 ); event AnswerUpdated( int256 indexed current, uint256 indexed roundId, uint256 updatedAt ); event NewRound( uint256 indexed roundId, address indexed startedBy, uint256 startedAt ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface AggregatorV3Interface { function decimals() external view returns ( uint8 ); function description() external view returns ( string memory ); function version() external view returns ( uint256 ); // getRoundData and latestRoundData should both raise "No data present" // if they do not have data to report, instead of returning unset values // which could be misinterpreted as actual reported values. function getRoundData( uint80 _roundId ) external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); function latestRoundData() external view returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { EnumerableSet } from '../../../utils/EnumerableSet.sol'; library ERC1155EnumerableStorage { struct Layout { mapping(uint256 => uint256) totalSupply; mapping(uint256 => EnumerableSet.AddressSet) accountsByToken; mapping(address => EnumerableSet.UintSet) tokensByAccount; } bytes32 internal constant STORAGE_SLOT = keccak256('solidstate.contracts.storage.ERC1155Enumerable'); function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol"; library ABDKMath64x64Token { using ABDKMath64x64 for int128; /** * @notice convert 64x64 fixed point representation of token amount to decimal * @param value64x64 64x64 fixed point representation of token amount * @param decimals token display decimals * @return value decimal representation of token amount */ function toDecimals(int128 value64x64, uint8 decimals) internal pure returns (uint256 value) { value = value64x64.mulu(10**decimals); } /** * @notice convert decimal representation of token amount to 64x64 fixed point * @param value decimal representation of token amount * @param decimals token display decimals * @return value64x64 64x64 fixed point representation of token amount */ function fromDecimals(uint256 value, uint8 decimals) internal pure returns (int128 value64x64) { value64x64 = ABDKMath64x64.divu(value, 10**decimals); } /** * @notice convert 64x64 fixed point representation of token amount to wei (18 decimals) * @param value64x64 64x64 fixed point representation of token amount * @return value wei representation of token amount */ function toWei(int128 value64x64) internal pure returns (uint256 value) { value = toDecimals(value64x64, 18); } /** * @notice convert wei representation (18 decimals) of token amount to 64x64 fixed point * @param value wei representation of token amount * @return value64x64 64x64 fixed point representation of token amount */ function fromWei(uint256 value) internal pure returns (int128 value64x64) { value64x64 = fromDecimals(value, 18); } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {ABDKMath64x64} from "abdk-libraries-solidity/ABDKMath64x64.sol"; library OptionMath { using ABDKMath64x64 for int128; struct QuoteArgs { int128 varianceAnnualized64x64; // 64x64 fixed point representation of annualized variance int128 strike64x64; // 64x64 fixed point representation of strike price int128 spot64x64; // 64x64 fixed point representation of spot price int128 timeToMaturity64x64; // 64x64 fixed point representation of duration of option contract (in years) int128 oldCLevel64x64; // 64x64 fixed point representation of C-Level of Pool before purchase int128 oldPoolState; // 64x64 fixed point representation of current state of the pool int128 newPoolState; // 64x64 fixed point representation of state of the pool after trade int128 steepness64x64; // 64x64 fixed point representation of Pool state delta multiplier int128 minAPY64x64; // 64x64 fixed point representation of minimum APY for capital locked up to underwrite options bool isCall; // whether to price "call" or "put" option } struct CalculateCLevelDecayArgs { int128 timeIntervalsElapsed64x64; // 64x64 fixed point representation of quantity of discrete arbitrary intervals elapsed since last update int128 oldCLevel64x64; // 64x64 fixed point representation of C-Level prior to accounting for decay int128 utilization64x64; // 64x64 fixed point representation of pool capital utilization rate int128 utilizationLowerBound64x64; int128 utilizationUpperBound64x64; int128 cLevelLowerBound64x64; int128 cLevelUpperBound64x64; int128 cConvergenceULowerBound64x64; int128 cConvergenceUUpperBound64x64; } // 64x64 fixed point integer constants int128 internal constant ONE_64x64 = 0x10000000000000000; int128 internal constant THREE_64x64 = 0x30000000000000000; // 64x64 fixed point constants used in Choudhury’s approximation of the Black-Scholes CDF int128 private constant CDF_CONST_0 = 0x09109f285df452394; // 2260 / 3989 int128 private constant CDF_CONST_1 = 0x19abac0ea1da65036; // 6400 / 3989 int128 private constant CDF_CONST_2 = 0x0d3c84b78b749bd6b; // 3300 / 3989 /** * @notice recalculate C-Level based on change in liquidity * @param initialCLevel64x64 64x64 fixed point representation of C-Level of Pool before update * @param oldPoolState64x64 64x64 fixed point representation of liquidity in pool before update * @param newPoolState64x64 64x64 fixed point representation of liquidity in pool after update * @param steepness64x64 64x64 fixed point representation of steepness coefficient * @return 64x64 fixed point representation of new C-Level */ function calculateCLevel( int128 initialCLevel64x64, int128 oldPoolState64x64, int128 newPoolState64x64, int128 steepness64x64 ) external pure returns (int128) { return newPoolState64x64 .sub(oldPoolState64x64) .div( oldPoolState64x64 > newPoolState64x64 ? oldPoolState64x64 : newPoolState64x64 ) .mul(steepness64x64) .neg() .exp() .mul(initialCLevel64x64); } /** * @notice calculate the price of an option using the Premia Finance model * @param args arguments of quotePrice * @return premiaPrice64x64 64x64 fixed point representation of Premia option price * @return cLevel64x64 64x64 fixed point representation of C-Level of Pool after purchase */ function quotePrice(QuoteArgs memory args) external pure returns ( int128 premiaPrice64x64, int128 cLevel64x64, int128 slippageCoefficient64x64 ) { int128 deltaPoolState64x64 = args .newPoolState .sub(args.oldPoolState) .div(args.oldPoolState) .mul(args.steepness64x64); int128 tradingDelta64x64 = deltaPoolState64x64.neg().exp(); int128 blackScholesPrice64x64 = _blackScholesPrice( args.varianceAnnualized64x64, args.strike64x64, args.spot64x64, args.timeToMaturity64x64, args.isCall ); cLevel64x64 = tradingDelta64x64.mul(args.oldCLevel64x64); slippageCoefficient64x64 = ONE_64x64.sub(tradingDelta64x64).div( deltaPoolState64x64 ); premiaPrice64x64 = blackScholesPrice64x64.mul(cLevel64x64).mul( slippageCoefficient64x64 ); int128 intrinsicValue64x64; if (args.isCall && args.strike64x64 < args.spot64x64) { intrinsicValue64x64 = args.spot64x64.sub(args.strike64x64); } else if (!args.isCall && args.strike64x64 > args.spot64x64) { intrinsicValue64x64 = args.strike64x64.sub(args.spot64x64); } int128 collateralValue64x64 = args.isCall ? args.spot64x64 : args.strike64x64; int128 minPrice64x64 = intrinsicValue64x64.add( collateralValue64x64.mul(args.minAPY64x64).mul( args.timeToMaturity64x64 ) ); if (minPrice64x64 > premiaPrice64x64) { premiaPrice64x64 = minPrice64x64; } } /** * @notice calculate the decay of C-Level based on heat diffusion function * @param args structured CalculateCLevelDecayArgs * @return cLevelDecayed64x64 C-Level after accounting for decay */ function calculateCLevelDecay(CalculateCLevelDecayArgs memory args) external pure returns (int128 cLevelDecayed64x64) { int128 convFHighU64x64 = (args.utilization64x64 >= args.utilizationUpperBound64x64 && args.oldCLevel64x64 <= args.cLevelLowerBound64x64) ? ONE_64x64 : int128(0); int128 convFLowU64x64 = (args.utilization64x64 <= args.utilizationLowerBound64x64 && args.oldCLevel64x64 >= args.cLevelUpperBound64x64) ? ONE_64x64 : int128(0); cLevelDecayed64x64 = args .oldCLevel64x64 .sub(args.cConvergenceULowerBound64x64.mul(convFLowU64x64)) .sub(args.cConvergenceUUpperBound64x64.mul(convFHighU64x64)) .mul( convFLowU64x64 .mul(ONE_64x64.sub(args.utilization64x64)) .add(convFHighU64x64.mul(args.utilization64x64)) .mul(args.timeIntervalsElapsed64x64) .neg() .exp() ) .add( args.cConvergenceULowerBound64x64.mul(convFLowU64x64).add( args.cConvergenceUUpperBound64x64.mul(convFHighU64x64) ) ); } /** * @notice calculate the exponential decay coefficient for a given interval * @param oldTimestamp timestamp of previous update * @param newTimestamp current timestamp * @return 64x64 fixed point representation of exponential decay coefficient */ function _decay(uint256 oldTimestamp, uint256 newTimestamp) internal pure returns (int128) { return ONE_64x64.sub( (-ABDKMath64x64.divu(newTimestamp - oldTimestamp, 7 days)).exp() ); } /** * @notice calculate Choudhury’s approximation of the Black-Scholes CDF * @param input64x64 64x64 fixed point representation of random variable * @return 64x64 fixed point representation of the approximated CDF of x */ function _N(int128 input64x64) internal pure returns (int128) { // squaring via mul is cheaper than via pow int128 inputSquared64x64 = input64x64.mul(input64x64); int128 value64x64 = (-inputSquared64x64 >> 1).exp().div( CDF_CONST_0.add(CDF_CONST_1.mul(input64x64.abs())).add( CDF_CONST_2.mul(inputSquared64x64.add(THREE_64x64).sqrt()) ) ); return input64x64 > 0 ? ONE_64x64.sub(value64x64) : value64x64; } /** * @notice calculate the price of an option using the Black-Scholes model * @param varianceAnnualized64x64 64x64 fixed point representation of annualized variance * @param strike64x64 64x64 fixed point representation of strike price * @param spot64x64 64x64 fixed point representation of spot price * @param timeToMaturity64x64 64x64 fixed point representation of duration of option contract (in years) * @param isCall whether to price "call" or "put" option * @return 64x64 fixed point representation of Black-Scholes option price */ function _blackScholesPrice( int128 varianceAnnualized64x64, int128 strike64x64, int128 spot64x64, int128 timeToMaturity64x64, bool isCall ) internal pure returns (int128) { int128 cumulativeVariance64x64 = timeToMaturity64x64.mul( varianceAnnualized64x64 ); int128 cumulativeVarianceSqrt64x64 = cumulativeVariance64x64.sqrt(); int128 d1_64x64 = spot64x64 .div(strike64x64) .ln() .add(cumulativeVariance64x64 >> 1) .div(cumulativeVarianceSqrt64x64); int128 d2_64x64 = d1_64x64.sub(cumulativeVarianceSqrt64x64); if (isCall) { return spot64x64.mul(_N(d1_64x64)).sub(strike64x64.mul(_N(d2_64x64))); } else { return -spot64x64.mul(_N(-d1_64x64)).sub( strike64x64.mul(_N(-d2_64x64)) ); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC20 metadata interface */ interface IERC20Metadata { /** * @notice return token name * @return token name */ function name() external view returns (string memory); /** * @notice return token symbol * @return token symbol */ function symbol() external view returns (string memory); /** * @notice return token decimals, generally used only for display purposes * @return token decimals */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Partial ERC20 interface needed by internal functions */ interface IERC20Internal { event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library AddressUtils { function toString(address account) internal pure returns (string memory) { bytes32 value = bytes32(uint256(uint160(account))); bytes memory alphabet = '0123456789abcdef'; bytes memory chars = new bytes(42); chars[0] = '0'; chars[1] = 'x'; for (uint256 i = 0; i < 20; i++) { chars[2 + i * 2] = alphabet[uint8(value[i + 12] >> 4)]; chars[3 + i * 2] = alphabet[uint8(value[i + 12] & 0x0f)]; } return string(chars); } function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } function sendValue(address payable account, uint256 amount) internal { (bool success, ) = account.call{ value: amount }(''); require(success, 'AddressUtils: failed to send value'); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, 'AddressUtils: failed low-level call'); } function functionCall( address target, bytes memory data, string memory error ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, error); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, 'AddressUtils: failed low-level call with value' ); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory error ) internal returns (bytes memory) { require( address(this).balance >= value, 'AddressUtils: insufficient balance for call' ); return _functionCallWithValue(target, data, value, error); } function _functionCallWithValue( address target, bytes memory data, uint256 value, string memory error ) private returns (bytes memory) { require( isContract(target), 'AddressUtils: function call to non-contract' ); (bool success, bytes memory returnData) = target.call{ value: value }( data ); if (success) { return returnData; } else if (returnData.length > 0) { assembly { let returnData_size := mload(returnData) revert(add(32, returnData), returnData_size) } } else { revert(error); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Contract ownership standard interface * @dev see https://eips.ethereum.org/EIPS/eip-173 */ interface IERC173 { event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @notice get the ERC173 contract owner * @return conract owner */ function owner() external view returns (address); /** * @notice transfer contract ownership to new account * @param account address of new owner */ function transferOwnership(address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library OwnableStorage { struct Layout { address owner; } bytes32 internal constant STORAGE_SLOT = keccak256('solidstate.contracts.storage.Ownable'); function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } function setOwner(Layout storage l, address owner) internal { l.owner = owner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { EnumerableSet } from '../../../utils/EnumerableSet.sol'; import { ERC1155Base, ERC1155BaseInternal } from '../base/ERC1155Base.sol'; import { IERC1155Enumerable } from './IERC1155Enumerable.sol'; import { ERC1155EnumerableInternal, ERC1155EnumerableStorage } from './ERC1155EnumerableInternal.sol'; /** * @title ERC1155 implementation including enumerable and aggregate functions */ abstract contract ERC1155Enumerable is IERC1155Enumerable, ERC1155Base, ERC1155EnumerableInternal { using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.UintSet; /** * @inheritdoc IERC1155Enumerable */ function totalSupply(uint256 id) public view virtual override returns (uint256) { return ERC1155EnumerableStorage.layout().totalSupply[id]; } /** * @inheritdoc IERC1155Enumerable */ function totalHolders(uint256 id) public view virtual override returns (uint256) { return ERC1155EnumerableStorage.layout().accountsByToken[id].length(); } /** * @inheritdoc IERC1155Enumerable */ function accountsByToken(uint256 id) public view virtual override returns (address[] memory) { EnumerableSet.AddressSet storage accounts = ERC1155EnumerableStorage .layout() .accountsByToken[id]; address[] memory addresses = new address[](accounts.length()); for (uint256 i; i < accounts.length(); i++) { addresses[i] = accounts.at(i); } return addresses; } /** * @inheritdoc IERC1155Enumerable */ function tokensByAccount(address account) public view virtual override returns (uint256[] memory) { EnumerableSet.UintSet storage tokens = ERC1155EnumerableStorage .layout() .tokensByAccount[account]; uint256[] memory ids = new uint256[](tokens.length()); for (uint256 i; i < tokens.length(); i++) { ids[i] = tokens.at(i); } return ids; } /** * @notice ERC1155 hook: update aggregate values * @inheritdoc ERC1155EnumerableInternal */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override(ERC1155BaseInternal, ERC1155EnumerableInternal) { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); } } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; import {FeeDiscountStorage} from "./FeeDiscountStorage.sol"; interface IFeeDiscount { event Staked( address indexed user, uint256 amount, uint256 stakePeriod, uint256 lockedUntil ); event Unstaked(address indexed user, uint256 amount); struct StakeLevel { uint256 amount; // Amount to stake uint256 discount; // Discount when amount is reached } /** * @notice Stake using IERC2612 permit * @param amount The amount of xPremia to stake * @param period The lockup period (in seconds) * @param deadline Deadline after which permit will fail * @param v V * @param r R * @param s S */ function stakeWithPermit( uint256 amount, uint256 period, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @notice Lockup xPremia for protocol fee discounts * Longer period of locking will apply a multiplier on the amount staked, in the fee discount calculation * @param amount The amount of xPremia to stake * @param period The lockup period (in seconds) */ function stake(uint256 amount, uint256 period) external; /** * @notice Unstake xPremia (If lockup period has ended) * @param amount The amount of xPremia to unstake */ function unstake(uint256 amount) external; ////////// // View // ////////// /** * Calculate the stake amount of a user, after applying the bonus from the lockup period chosen * @param user The user from which to query the stake amount * @return The user stake amount after applying the bonus */ function getStakeAmountWithBonus(address user) external view returns (uint256); /** * @notice Calculate the % of fee discount for user, based on his stake * @param user The _user for which the discount is for * @return Percentage of protocol fee discount (in basis point) * Ex : 1000 = 10% fee discount */ function getDiscount(address user) external view returns (uint256); /** * @notice Get stake levels * @return Stake levels * Ex : 2500 = -25% */ function getStakeLevels() external returns (StakeLevel[] memory); /** * @notice Get stake period multiplier * @param period The duration (in seconds) for which tokens are locked * @return The multiplier for this staking period * Ex : 20000 = x2 */ function getStakePeriodMultiplier(uint256 period) external returns (uint256); /** * @notice Get staking infos of a user * @param user The user address for which to get staking infos * @return The staking infos of the user */ function getUserInfo(address user) external view returns (FeeDiscountStorage.UserInfo memory); } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; interface IPoolEvents { event Purchase( address indexed user, uint256 longTokenId, uint256 contractSize, uint256 baseCost, uint256 feeCost, int128 spot64x64 ); event Exercise( address indexed user, uint256 longTokenId, uint256 contractSize, uint256 exerciseValue, uint256 fee ); event Underwrite( address indexed underwriter, address indexed longReceiver, uint256 shortTokenId, uint256 intervalContractSize, uint256 intervalPremium, bool isManualUnderwrite ); event AssignExercise( address indexed underwriter, uint256 shortTokenId, uint256 freedAmount, uint256 intervalContractSize, uint256 fee ); event Deposit(address indexed user, bool isCallPool, uint256 amount); event Withdrawal( address indexed user, bool isCallPool, uint256 depositedAt, uint256 amount ); event FeeWithdrawal(bool indexed isCallPool, uint256 amount); event Annihilate(uint256 shortTokenId, uint256 amount); event UpdateCLevel( bool indexed isCall, int128 cLevel64x64, int128 oldLiquidity64x64, int128 newLiquidity64x64 ); event UpdateSteepness(int128 steepness64x64, bool isCallPool); } // SPDX-License-Identifier: LGPL-3.0-or-later pragma solidity ^0.8.0; import {VolatilitySurfaceOracleStorage} from "./VolatilitySurfaceOracleStorage.sol"; interface IVolatilitySurfaceOracle { function getWhitelistedRelayers() external view returns (address[] memory); function getVolatilitySurface(address baseToken, address underlyingToken) external view returns (VolatilitySurfaceOracleStorage.Update memory); function getVolatilitySurfaceCoefficientsUnpacked( address baseToken, address underlyingToken, bool isCall ) external view returns (int256[] memory); function getTimeToMaturity64x64(uint64 maturity) external view returns (int128); function getAnnualizedVolatility64x64( address baseToken, address underlyingToken, int128 spot64x64, int128 strike64x64, int128 timeToMaturity64x64, bool isCall ) external view returns (int128); function getBlackScholesPrice64x64( address baseToken, address underlyingToken, int128 strike64x64, int128 spot64x64, int128 timeToMaturity64x64, bool isCall ) external view returns (int128); function getBlackScholesPrice( address baseToken, address underlyingToken, int128 strike64x64, int128 spot64x64, int128 timeToMaturity64x64, bool isCall ) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC1155 } from '../IERC1155.sol'; import { IERC1155Receiver } from '../IERC1155Receiver.sol'; import { ERC1155BaseInternal, ERC1155BaseStorage } from './ERC1155BaseInternal.sol'; /** * @title Base ERC1155 contract * @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts/ (MIT license) */ abstract contract ERC1155Base is IERC1155, ERC1155BaseInternal { /** * @inheritdoc IERC1155 */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { return _balanceOf(account, id); } /** * @inheritdoc IERC1155 */ 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' ); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; uint256[] memory batchBalances = new uint256[](accounts.length); unchecked { for (uint256 i; i < accounts.length; i++) { require( accounts[i] != address(0), 'ERC1155: batch balance query for the zero address' ); batchBalances[i] = balances[ids[i]][accounts[i]]; } } return batchBalances; } /** * @inheritdoc IERC1155 */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return ERC1155BaseStorage.layout().operatorApprovals[account][operator]; } /** * @inheritdoc IERC1155 */ function setApprovalForAll(address operator, bool status) public virtual override { require( msg.sender != operator, 'ERC1155: setting approval status for self' ); ERC1155BaseStorage.layout().operatorApprovals[msg.sender][ operator ] = status; emit ApprovalForAll(msg.sender, operator, status); } /** * @inheritdoc IERC1155 */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == msg.sender || isApprovedForAll(from, msg.sender), 'ERC1155: caller is not owner nor approved' ); _safeTransfer(msg.sender, from, to, id, amount, data); } /** * @inheritdoc IERC1155 */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == msg.sender || isApprovedForAll(from, msg.sender), 'ERC1155: caller is not owner nor approved' ); _safeTransferBatch(msg.sender, from, to, ids, amounts, data); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC1155 enumerable and aggregate function interface */ interface IERC1155Enumerable { /** * @notice query total minted supply of given token * @param id token id to query * @return token supply */ function totalSupply(uint256 id) external view returns (uint256); /** * @notice query total number of holders for given token * @param id token id to query * @return quantity of holders */ function totalHolders(uint256 id) external view returns (uint256); /** * @notice query holders of given token * @param id token id to query * @return list of holder addresses */ function accountsByToken(uint256 id) external view returns (address[] memory); /** * @notice query tokens held by given address * @param account address to query * @return list of token ids */ function tokensByAccount(address account) external view returns (uint256[] memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { EnumerableSet } from '../../../utils/EnumerableSet.sol'; import { ERC1155BaseInternal, ERC1155BaseStorage } from '../base/ERC1155BaseInternal.sol'; import { ERC1155EnumerableStorage } from './ERC1155EnumerableStorage.sol'; /** * @title ERC1155Enumerable internal functions */ abstract contract ERC1155EnumerableInternal is ERC1155BaseInternal { using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.UintSet; /** * @notice ERC1155 hook: update aggregate values * @inheritdoc ERC1155BaseInternal */ 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 != to) { ERC1155EnumerableStorage.Layout storage l = ERC1155EnumerableStorage .layout(); mapping(uint256 => EnumerableSet.AddressSet) storage tokenAccounts = l.accountsByToken; EnumerableSet.UintSet storage fromTokens = l.tokensByAccount[from]; EnumerableSet.UintSet storage toTokens = l.tokensByAccount[to]; for (uint256 i; i < ids.length; i++) { uint256 amount = amounts[i]; if (amount > 0) { uint256 id = ids[i]; if (from == address(0)) { l.totalSupply[id] += amount; } else if (_balanceOf(from, id) == amount) { tokenAccounts[id].remove(from); fromTokens.remove(id); } if (to == address(0)) { l.totalSupply[id] -= amount; } else if (_balanceOf(to, id) == 0) { tokenAccounts[id].add(to); toTokens.add(id); } } } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC1155Internal } from './IERC1155Internal.sol'; import { IERC165 } from '../../introspection/IERC165.sol'; /** * @notice ERC1155 interface * @dev see https://github.com/ethereum/EIPs/issues/1155 */ interface IERC1155 is IERC1155Internal, IERC165 { /** * @notice query the balance of given token held by given address * @param account address to query * @param id token to query * @return token balance */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @notice query the balances of given tokens held by given addresses * @param accounts addresss to query * @param ids tokens to query * @return token balances */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @notice query approval status of given operator with respect to given address * @param account address to query for approval granted * @param operator address to query for approval received * @return whether operator is approved to spend tokens held by account */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @notice grant approval to or revoke approval from given operator to spend held tokens * @param operator address whose approval status to update * @param status whether operator should be considered approved */ function setApprovalForAll(address operator, bool status) external; /** * @notice transfer tokens between given addresses, checking for ERC1155Receiver implementation if applicable * @param from sender of tokens * @param to receiver of tokens * @param id token ID * @param amount quantity of tokens to transfer * @param data data payload */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes calldata data ) external; /** * @notice transfer batch of tokens between given addresses, checking for ERC1155Receiver implementation if applicable * @param from sender of tokens * @param to receiver of tokens * @param ids list of token IDs * @param amounts list of quantities of tokens to transfer * @param data data payload */ function safeBatchTransferFrom( address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC165 } from '../../introspection/IERC165.sol'; /** * @title ERC1155 transfer receiver interface */ interface IERC1155Receiver is IERC165 { /** * @notice validate receipt of ERC1155 transfer * @param operator executor of transfer * @param from sender of tokens * @param id token ID received * @param value quantity of tokens received * @param data data payload * @return function's own selector if transfer is accepted */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @notice validate receipt of ERC1155 batch transfer * @param operator executor of transfer * @param from sender of tokens * @param ids token IDs received * @param values quantities of tokens received * @param data data payload * @return function's own selector if transfer is accepted */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { AddressUtils } from '../../../utils/AddressUtils.sol'; import { IERC1155Internal } from '../IERC1155Internal.sol'; import { IERC1155Receiver } from '../IERC1155Receiver.sol'; import { ERC1155BaseStorage } from './ERC1155BaseStorage.sol'; /** * @title Base ERC1155 internal functions * @dev derived from https://github.com/OpenZeppelin/openzeppelin-contracts/ (MIT license) */ abstract contract ERC1155BaseInternal is IERC1155Internal { using AddressUtils for address; /** * @notice query the balance of given token held by given address * @param account address to query * @param id token to query * @return token balance */ function _balanceOf(address account, uint256 id) internal view virtual returns (uint256) { require( account != address(0), 'ERC1155: balance query for the zero address' ); return ERC1155BaseStorage.layout().balances[id][account]; } /** * @notice mint given quantity of tokens for given address * @dev ERC1155Receiver implementation is not checked * @param account beneficiary of minting * @param id token ID * @param amount quantity of tokens to mint * @param data data payload */ function _mint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(account != address(0), 'ERC1155: mint to the zero address'); _beforeTokenTransfer( msg.sender, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data ); mapping(address => uint256) storage balances = ERC1155BaseStorage .layout() .balances[id]; balances[account] += amount; emit TransferSingle(msg.sender, address(0), account, id, amount); } /** * @notice mint given quantity of tokens for given address * @param account beneficiary of minting * @param id token ID * @param amount quantity of tokens to mint * @param data data payload */ function _safeMint( address account, uint256 id, uint256 amount, bytes memory data ) internal virtual { _mint(account, id, amount, data); _doSafeTransferAcceptanceCheck( msg.sender, address(0), account, id, amount, data ); } /** * @notice mint batch of tokens for given address * @dev ERC1155Receiver implementation is not checked * @param account beneficiary of minting * @param ids list of token IDs * @param amounts list of quantities of tokens to mint * @param data data payload */ function _mintBatch( address account, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(account != address(0), 'ERC1155: mint to the zero address'); require( ids.length == amounts.length, 'ERC1155: ids and amounts length mismatch' ); _beforeTokenTransfer( msg.sender, address(0), account, ids, amounts, data ); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; for (uint256 i; i < ids.length; i++) { balances[ids[i]][account] += amounts[i]; } emit TransferBatch(msg.sender, address(0), account, ids, amounts); } /** * @notice mint batch of tokens for given address * @param account beneficiary of minting * @param ids list of token IDs * @param amounts list of quantities of tokens to mint * @param data data payload */ function _safeMintBatch( address account, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { _mintBatch(account, ids, amounts, data); _doSafeBatchTransferAcceptanceCheck( msg.sender, address(0), account, ids, amounts, data ); } /** * @notice burn given quantity of tokens held by given address * @param account holder of tokens to burn * @param id token ID * @param amount quantity of tokens to burn */ function _burn( address account, uint256 id, uint256 amount ) internal virtual { require(account != address(0), 'ERC1155: burn from the zero address'); _beforeTokenTransfer( msg.sender, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), '' ); mapping(address => uint256) storage balances = ERC1155BaseStorage .layout() .balances[id]; unchecked { require( balances[account] >= amount, 'ERC1155: burn amount exceeds balances' ); balances[account] -= amount; } emit TransferSingle(msg.sender, account, address(0), id, amount); } /** * @notice burn given batch of tokens held by given address * @param account holder of tokens to burn * @param ids token IDs * @param amounts quantities of tokens to burn */ function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(account != address(0), 'ERC1155: burn from the zero address'); require( ids.length == amounts.length, 'ERC1155: ids and amounts length mismatch' ); _beforeTokenTransfer(msg.sender, account, address(0), ids, amounts, ''); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; unchecked { for (uint256 i; i < ids.length; i++) { uint256 id = ids[i]; require( balances[id][account] >= amounts[i], 'ERC1155: burn amount exceeds balance' ); balances[id][account] -= amounts[i]; } } emit TransferBatch(msg.sender, account, address(0), ids, amounts); } /** * @notice transfer tokens between given addresses * @dev ERC1155Receiver implementation is not checked * @param operator executor of transfer * @param sender sender of tokens * @param recipient receiver of tokens * @param id token ID * @param amount quantity of tokens to transfer * @param data data payload */ function _transfer( address operator, address sender, address recipient, uint256 id, uint256 amount, bytes memory data ) internal virtual { require( recipient != address(0), 'ERC1155: transfer to the zero address' ); _beforeTokenTransfer( operator, sender, recipient, _asSingletonArray(id), _asSingletonArray(amount), data ); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; unchecked { uint256 senderBalance = balances[id][sender]; require( senderBalance >= amount, 'ERC1155: insufficient balances for transfer' ); balances[id][sender] = senderBalance - amount; } balances[id][recipient] += amount; emit TransferSingle(operator, sender, recipient, id, amount); } /** * @notice transfer tokens between given addresses * @param operator executor of transfer * @param sender sender of tokens * @param recipient receiver of tokens * @param id token ID * @param amount quantity of tokens to transfer * @param data data payload */ function _safeTransfer( address operator, address sender, address recipient, uint256 id, uint256 amount, bytes memory data ) internal virtual { _transfer(operator, sender, recipient, id, amount, data); _doSafeTransferAcceptanceCheck( operator, sender, recipient, id, amount, data ); } /** * @notice transfer batch of tokens between given addresses * @dev ERC1155Receiver implementation is not checked * @param operator executor of transfer * @param sender sender of tokens * @param recipient receiver of tokens * @param ids token IDs * @param amounts quantities of tokens to transfer * @param data data payload */ function _transferBatch( address operator, address sender, address recipient, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require( recipient != address(0), 'ERC1155: transfer to the zero address' ); require( ids.length == amounts.length, 'ERC1155: ids and amounts length mismatch' ); _beforeTokenTransfer(operator, sender, recipient, ids, amounts, data); mapping(uint256 => mapping(address => uint256)) storage balances = ERC1155BaseStorage.layout().balances; for (uint256 i; i < ids.length; i++) { uint256 token = ids[i]; uint256 amount = amounts[i]; unchecked { uint256 senderBalance = balances[token][sender]; require( senderBalance >= amount, 'ERC1155: insufficient balances for transfer' ); balances[token][sender] = senderBalance - amount; } balances[token][recipient] += amount; } emit TransferBatch(operator, sender, recipient, ids, amounts); } /** * @notice transfer batch of tokens between given addresses * @param operator executor of transfer * @param sender sender of tokens * @param recipient receiver of tokens * @param ids token IDs * @param amounts quantities of tokens to transfer * @param data data payload */ function _safeTransferBatch( address operator, address sender, address recipient, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { _transferBatch(operator, sender, recipient, ids, amounts, data); _doSafeBatchTransferAcceptanceCheck( operator, sender, recipient, ids, amounts, data ); } /** * @notice wrap given element in array of length 1 * @param element element to wrap * @return singleton array */ function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } /** * @notice revert if applicable transfer recipient is not valid ERC1155Receiver * @param operator executor of transfer * @param from sender of tokens * @param to receiver of tokens * @param id token ID * @param amount quantity of tokens to transfer * @param data data payload */ 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) { require( response == IERC1155Receiver.onERC1155Received.selector, 'ERC1155: ERC1155Receiver rejected tokens' ); } catch Error(string memory reason) { revert(reason); } catch { revert('ERC1155: transfer to non ERC1155Receiver implementer'); } } } /** * @notice revert if applicable transfer recipient is not valid ERC1155Receiver * @param operator executor of transfer * @param from sender of tokens * @param to receiver of tokens * @param ids token IDs * @param amounts quantities of tokens to transfer * @param data data payload */ 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) { require( response == IERC1155Receiver.onERC1155BatchReceived.selector, 'ERC1155: ERC1155Receiver rejected tokens' ); } catch Error(string memory reason) { revert(reason); } catch { revert('ERC1155: transfer to non ERC1155Receiver implementer'); } } } /** * @notice ERC1155 hook, called before all transfers including mint and burn * @dev function should be overridden and new implementation must call super * @dev called for both single and batch transfers * @param operator executor of transfer * @param from sender of tokens * @param to receiver of tokens * @param ids token IDs * @param amounts quantities of tokens to transfer * @param data data payload */ function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import { IERC165 } from '../../introspection/IERC165.sol'; /** * @notice Partial ERC1155 interface needed by internal functions */ interface IERC1155Internal { event TransferSingle( address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value ); event TransferBatch( address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values ); event ApprovalForAll( address indexed account, address indexed operator, bool approved ); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC165 interface registration interface * @dev see https://eips.ethereum.org/EIPS/eip-165 */ interface IERC165 { /** * @notice query whether contract has registered support for given interface * @param interfaceId interface id * @return bool whether interface is supported */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library ERC1155BaseStorage { struct Layout { mapping(uint256 => mapping(address => uint256)) balances; mapping(address => mapping(address => bool)) operatorApprovals; } bytes32 internal constant STORAGE_SLOT = keccak256('solidstate.contracts.storage.ERC1155Base'); function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; library FeeDiscountStorage { bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.staking.PremiaFeeDiscount"); struct UserInfo { uint256 balance; // Balance staked by user uint64 stakePeriod; // Stake period selected by user uint64 lockedUntil; // Timestamp at which the lock ends } struct Layout { // User data with xPREMIA balance staked and date at which lock ends mapping(address => UserInfo) userInfo; } function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; library PremiaMiningStorage { bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.PremiaMining"); // Info of each pool. struct PoolInfo { uint256 allocPoint; // How many allocation points assigned to this pool. PREMIA to distribute per block. uint256 lastRewardTimestamp; // Last timestamp that PREMIA distribution occurs uint256 accPremiaPerShare; // Accumulated PREMIA per share, times 1e12. See below. } // Info of each user. struct UserInfo { uint256 reward; // Total allocated unclaimed reward uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of PREMIA // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accPremiaPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accPremiaPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } struct Layout { // Total PREMIA left to distribute uint256 premiaAvailable; // Amount of premia distributed per year uint256 premiaPerYear; // pool -> isCallPool -> PoolInfo mapping(address => mapping(bool => PoolInfo)) poolInfo; // pool -> isCallPool -> user -> UserInfo mapping(address => mapping(bool => mapping(address => UserInfo))) userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 totalAllocPoint; } function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } } // SPDX-License-Identifier: BUSL-1.1 // For further clarification please see https://license.premia.legal pragma solidity ^0.8.0; import {EnumerableSet} from "@solidstate/contracts/utils/EnumerableSet.sol"; library VolatilitySurfaceOracleStorage { bytes32 internal constant STORAGE_SLOT = keccak256("premia.contracts.storage.VolatilitySurfaceOracle"); uint256 internal constant COEFF_BITS = 51; uint256 internal constant COEFF_BITS_MINUS_ONE = 50; uint256 internal constant COEFF_AMOUNT = 5; // START_BIT = COEFF_BITS * (COEFF_AMOUNT - 1) uint256 internal constant START_BIT = 204; struct Update { uint256 updatedAt; bytes32 callCoefficients; bytes32 putCoefficients; } struct Layout { // Base token -> Underlying token -> Update mapping(address => mapping(address => Update)) volatilitySurfaces; // Relayer addresses which can be trusted to provide accurate option trades EnumerableSet.AddressSet whitelistedRelayers; } function layout() internal pure returns (Layout storage l) { bytes32 slot = STORAGE_SLOT; assembly { l.slot := slot } } function getCoefficients( Layout storage l, address baseToken, address underlyingToken, bool isCall ) internal view returns (bytes32) { Update storage u = l.volatilitySurfaces[baseToken][underlyingToken]; return isCall ? u.callCoefficients : u.putCoefficients; } function parseVolatilitySurfaceCoefficients(bytes32 input) internal pure returns (int256[] memory coefficients) { coefficients = new int256[](COEFF_AMOUNT); // Value to add to negative numbers to cast them to int256 int256 toAdd = (int256(-1) >> COEFF_BITS) << COEFF_BITS; assembly { let i := 0 // Value equal to -1 let mid := shl(COEFF_BITS_MINUS_ONE, 1) for { } lt(i, COEFF_AMOUNT) { } { let offset := sub(START_BIT, mul(COEFF_BITS, i)) let coeff := shr( offset, sub( input, shl( add(offset, COEFF_BITS), shr(add(offset, COEFF_BITS), input) ) ) ) // Check if value is a negative number and needs casting if or(eq(coeff, mid), gt(coeff, mid)) { coeff := add(coeff, toAdd) } // Store result in the coefficients array mstore(add(coefficients, add(0x20, mul(0x20, i))), coeff) i := add(i, 1) } } } function formatVolatilitySurfaceCoefficients(int256[5] memory coefficients) internal pure returns (bytes32 result) { for (uint256 i = 0; i < COEFF_AMOUNT; i++) { int256 max = int256(1 << COEFF_BITS_MINUS_ONE); require( coefficients[i] < max && coefficients[i] > -max, "Out of bounds" ); } assembly { let i := 0 for { } lt(i, COEFF_AMOUNT) { } { let offset := sub(START_BIT, mul(COEFF_BITS, i)) let coeff := mload(add(coefficients, mul(0x20, i))) result := add( result, shl( offset, sub(coeff, shl(COEFF_BITS, shr(COEFF_BITS, coeff))) ) ) i := add(i, 1) } } } }
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is zero. @param x signed 64.64-bit fixed point number @return signed 64.64-bit fixed point number/
function inv (int128 x) internal pure returns (int128) { unchecked { require (x != 0); int256 result = int256 (0x100000000000000000000000000000000) / x; require (result >= MIN_64x64 && result <= MAX_64x64); return int128 (result); } }
103,821
[ 1, 8695, 404, 342, 619, 13885, 23248, 3634, 18, 225, 868, 1097, 603, 9391, 578, 1347, 619, 353, 3634, 18, 225, 619, 6726, 5178, 18, 1105, 17, 3682, 5499, 1634, 1300, 327, 6726, 5178, 18, 1105, 17, 3682, 5499, 1634, 1300, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 2198, 261, 474, 10392, 619, 13, 2713, 16618, 1135, 261, 474, 10392, 13, 288, 203, 565, 22893, 288, 203, 1377, 2583, 261, 92, 480, 374, 1769, 203, 1377, 509, 5034, 563, 273, 509, 5034, 261, 20, 92, 21, 12648, 12648, 12648, 12648, 13, 342, 619, 31, 203, 1377, 2583, 261, 2088, 1545, 6989, 67, 1105, 92, 1105, 597, 563, 1648, 4552, 67, 1105, 92, 1105, 1769, 203, 1377, 327, 509, 10392, 261, 2088, 1769, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xA0B757f036100A38ad24192aDfD46B3bF374dE51/sources/ETF.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("BlackRockWisdomTreeInvescoValkyrieFidelity", "ETF") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 0; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 10; uint256 _sellMarketingFee = 0; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 10; uint256 totalSupply = 10000000000000 * 1e18; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; marketingWallet = address(0xcecbEBa271Cc89EC47Fdb69B98073579A1fA800F); devWallet = address(0xcecbEBa271Cc89EC47Fdb69B98073579A1fA800F); excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromFees(address(marketingWallet), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); excludeFromMaxTransaction(address(devWallet), true); excludeFromMaxTransaction(address(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);
4,224,744
[ 1, 10157, 628, 8843, 310, 1656, 281, 578, 7999, 943, 2492, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 4232, 39, 3462, 2932, 13155, 54, 975, 59, 291, 9859, 2471, 3605, 742, 83, 58, 2960, 93, 566, 73, 42, 350, 292, 560, 3113, 315, 1584, 42, 7923, 288, 203, 7010, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 20, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 1769, 203, 7010, 3639, 4433, 1265, 2747, 3342, 12, 2867, 24899, 318, 291, 91, 438, 58, 22, 8259, 3631, 638, 1769, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 7010, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 24899, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 1435, 2934, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 3639, 389, 542, 22932, 690, 3882, 278, 12373, 4154, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 7010, 3639, 2254, 5034, 389, 70, 9835, 3882, 21747, 14667, 273, 374, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 48, 18988, 24237, 14667, 273, 2 ]
./partial_match/3/0x2953972C2B9D6cecdBC2F338C825e295c73B92B9/sources/STTAFUND.sol
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract STTAFUND is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function STTAFUND() public { symbol = "SAT"; name = "STTAFUND"; decimals = 0; _totalSupply = 20000; balances[0xd5FB4f7E92c604b2A7c7056AC0EA3b96073fdB74] = _totalSupply; Transfer(address(0), 0xd5FB4f7E92c604b2A7c7056AC0EA3b96073fdB74, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public returns (bool success) { balances[from] = safeSub(balances[from], tokens); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances[to] = safeAdd(balances[to], tokens); Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
5,329,174
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 1551, 25444, 1147, 29375, 8879, 13849, 8879, 17082, 11417, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 348, 1470, 6799, 5240, 353, 4232, 39, 3462, 1358, 16, 14223, 11748, 16, 14060, 10477, 288, 203, 565, 533, 1071, 3273, 31, 203, 565, 533, 1071, 225, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 1071, 389, 4963, 3088, 1283, 31, 203, 7010, 565, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 7010, 7010, 565, 445, 348, 1470, 6799, 5240, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 55, 789, 14432, 203, 3639, 508, 273, 315, 882, 56, 6799, 5240, 14432, 203, 3639, 15105, 273, 374, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 576, 2787, 31, 203, 3639, 324, 26488, 63, 20, 7669, 25, 22201, 24, 74, 27, 41, 9975, 71, 26, 3028, 70, 22, 37, 27, 71, 7301, 4313, 2226, 20, 41, 37, 23, 70, 29, 4848, 9036, 8313, 38, 5608, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 12279, 12, 2867, 12, 20, 3631, 374, 7669, 25, 22201, 24, 74, 27, 41, 9975, 71, 26, 3028, 70, 22, 37, 27, 71, 7301, 4313, 2226, 20, 41, 37, 23, 70, 29, 4848, 9036, 8313, 38, 5608, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 7010, 7010, 565, 445, 2078, 3088, 1283, 1435, 1071, 5381, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 225, 300, 324, 26488, 63, 2867, 12, 20, 13, 15533, 203, 565, 289, 203, 7010, 7010, 565, 445, 11013, 951, 12, 2867, 2 ]
./partial_match/1/0x76E28A61D9BD58c5ec598A6Bc25d8279aea8d2cF/sources/TrueFiPool.sol
* @dev Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); .'''''''''''.. ..''''''''''''''''.. ..'''''''''''''''.. }
15,604,211
[ 1, 1358, 434, 326, 4232, 39, 3462, 4529, 487, 2553, 316, 326, 512, 2579, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 654, 39, 3462, 288, 203, 565, 445, 2078, 3088, 1283, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 7412, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 7412, 1265, 12, 2867, 5793, 16, 1758, 8027, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 460, 1769, 203, 565, 263, 6309, 6309, 6309, 6309, 26418, 838, 377, 263, 1093, 6309, 6309, 6309, 6309, 6309, 6309, 26418, 838, 4202, 263, 1093, 6309, 6309, 6309, 6309, 6309, 6309, 6309, 838, 3639, 203, 203, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xeE82EeC318A7a71714E25BD8B1266170210A3d73/sources/MinimenClub.sol
* @dev Returns true if a `leafs` can be proved to be a part of a Merkle tree defined by `root`. For this, `proofs` for each leaf must be provided, containing sibling hashes on the branch from the leaf to the root of the tree. Then 'proofFlag' designates the nodes needed for the multi proof. _Available since v4.7._/
function multiProofVerify( bytes32 root, bytes32[] calldata leaves, bytes32[] calldata proofs, bool[] calldata proofFlag ) internal pure returns (bool) { return processMultiProof(leaves, proofs, proofFlag) == root; }
15,530,803
[ 1, 1356, 638, 309, 279, 1375, 12070, 87, 68, 848, 506, 450, 2155, 358, 506, 279, 1087, 434, 279, 31827, 2151, 2553, 635, 1375, 3085, 8338, 2457, 333, 16, 1375, 24207, 87, 68, 364, 1517, 7839, 1297, 506, 2112, 16, 4191, 10841, 9869, 603, 326, 3803, 628, 326, 7839, 358, 326, 1365, 434, 326, 2151, 18, 9697, 296, 24207, 4678, 11, 8281, 815, 326, 2199, 3577, 364, 326, 3309, 14601, 18, 389, 5268, 3241, 331, 24, 18, 27, 6315, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3309, 20439, 8097, 12, 203, 3639, 1731, 1578, 1365, 16, 203, 3639, 1731, 1578, 8526, 745, 892, 15559, 16, 203, 3639, 1731, 1578, 8526, 745, 892, 14601, 87, 16, 203, 3639, 1426, 8526, 745, 892, 14601, 4678, 203, 565, 262, 2713, 16618, 1135, 261, 6430, 13, 288, 203, 3639, 327, 1207, 5002, 20439, 12, 298, 6606, 16, 14601, 87, 16, 14601, 4678, 13, 422, 1365, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } contract Pausable is Owned { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and an // initial fixed supply // ---------------------------------------------------------------------------- contract NUC is ERC20Interface, Pausable { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function NUC() public { symbol = "NUC"; name = "NUC Token"; decimals = 18; _totalSupply = 21 * 1000 * 1000 * 1000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint 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, uint tokens) public whenNotPaused returns (bool success) { require(to != address(0)); require(tokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public whenNotPaused returns (bool success) { require(tokens == 0 || allowed[msg.sender][spender] == 0); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } // ------------------------------------------------------------------------ // 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, uint tokens) public whenNotPaused returns (bool success) { require(to != address(0)); require(tokens <= balances[from]); require(tokens <= allowed[from][msg.sender]); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(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 constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } }
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and an initial fixed supply ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract NUC is ERC20Interface, Pausable { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function NUC() public { symbol = "NUC"; name = "NUC Token"; decimals = 18; _totalSupply = 21 * 1000 * 1000 * 1000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public whenNotPaused returns (bool success) { require(to != address(0)); require(tokens <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public whenNotPaused returns (bool success) { require(tokens == 0 || allowed[msg.sender][spender] == 0); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function transferFrom(address from, address to, uint tokens) public whenNotPaused returns (bool success) { require(to != address(0)); require(tokens <= balances[from]); require(tokens <= allowed[from][msg.sender]); balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function () public payable { revert(); } }
14,758,653
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 392, 2172, 5499, 14467, 8879, 13849, 8879, 17082, 11417, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 423, 17479, 353, 4232, 39, 3462, 1358, 16, 21800, 16665, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 565, 533, 1071, 3273, 31, 203, 565, 533, 1071, 225, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 389, 4963, 3088, 1283, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 203, 203, 565, 445, 423, 17479, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 50, 17479, 14432, 203, 3639, 508, 273, 315, 50, 17479, 3155, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 9035, 380, 4336, 380, 4336, 380, 4336, 380, 1728, 636, 11890, 12, 31734, 1769, 203, 3639, 324, 26488, 63, 8443, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 3410, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 5381, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 31, 203, 565, 289, 203, 203, 203, 565, 445, 11013, 951, 12, 2867, 1147, 5541, 13, 1071, 5381, 1135, 261, 11890, 11013, 13, 288, 203, 3639, 327, 324, 26488, 63, 2316, 5541, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 7412, 12, 2867, 358, 16, 2254, 2430, 13, 1071, 1347, 1248, 28590, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 2583, 12, 869, 480, 1758, 12, 20, 10019, 203, 2 ]
pragma solidity 0.4.25; // File: contracts/SafeMath.sol // https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol // @title SafeMath: overflow/underflow checks // @notice Math operations with safety checks that throw on error library SafeMath { // @notice 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; } // @notice 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; } // @notice 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; } // @notice Adds two numbers, throws on overflow. function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // File: contracts/ERC20Interface.sol // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // ---------------------------------------------------------------------------- interface ERC20Interface { function totalSupply() external returns (uint); function balanceOf(address tokenOwner) external returns (uint balance); function allowance(address tokenOwner, address spender) external returns (uint remaining); function transfer(address to, uint tokens) external returns (bool success); function approve(address spender, uint tokens) external returns (bool success); function transferFrom(address from, address to, uint tokens) external returns (bool success); function burn(uint _amount) external returns (bool success); function burnFrom(address _from, uint _amount) external returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event LogBurn(address indexed _spender, uint256 _value); } // File: contracts/TokenSale.sol // @title MyBit Tokensale // @notice A tokensale extending for 365 days. (0....364) // @notice 100,000 MYB are releases everyday and split proportionaly to funders of that day // @notice Anyone can fund the current or future days with ETH // @dev The current day is (timestamp - startTimestamp) / 24 hours // @author Kyle Dewhurst, MyBit Foundation contract TokenSale { using SafeMath for *; ERC20Interface mybToken; struct Day { uint totalWeiContributed; mapping (address => uint) weiContributed; } // Constants uint256 constant internal scalingFactor = 10**32; // helps avoid rounding errors uint256 constant public tokensPerDay = 10**23; // 100,000 MYB // MyBit addresses address public owner; address public mybitFoundation; address public developmentFund; uint256 public start; // The timestamp when sale starts mapping (uint16 => Day) public day; constructor(address _mybToken, address _mybFoundation, address _developmentFund) public { mybToken = ERC20Interface(_mybToken); developmentFund = _developmentFund; mybitFoundation = _mybFoundation; owner = msg.sender; } // @notice owner can start the sale by transferring in required amount of MYB // @dev the start time is used to determine which day the sale is on (day 0 = first day) function startSale(uint _timestamp) external onlyOwner returns (bool){ require(start == 0, 'Already started'); require(_timestamp >= now && _timestamp.sub(now) < 2592000, 'Start time not in range'); uint saleAmount = tokensPerDay.mul(365); require(mybToken.transferFrom(msg.sender, address(this), saleAmount)); start = _timestamp; emit LogSaleStarted(msg.sender, mybitFoundation, developmentFund, saleAmount, _timestamp); return true; } // @notice contributor can contribute wei to sale on any current/future _day // @dev only accepts contributions between days 0 - 364 function fund(uint16 _day) payable public returns (bool) { require(addContribution(msg.sender, msg.value, _day)); return true; } // @notice Send an index of days and your payment will be divided equally among them // @dev WEI sent must divide equally into number of days. function batchFund(uint16[] _day) payable external returns (bool) { require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit require(msg.value >= _day.length); // need at least 1 wei per day uint256 amountPerDay = msg.value.div(_day.length); assert (amountPerDay.mul(_day.length) == msg.value); // Don't allow any rounding error for (uint8 i = 0; i < _day.length; i++){ require(addContribution(msg.sender, amountPerDay, _day[i])); } return true; } // @notice Updates claimableTokens, sends all wei to the token holder function withdraw(uint16 _day) external returns (bool) { require(dayFinished(_day), "day has not finished funding"); Day storage thisDay = day[_day]; uint256 amount = getTokensOwed(msg.sender, _day); delete thisDay.weiContributed[msg.sender]; mybToken.transfer(msg.sender, amount); emit LogTokensCollected(msg.sender, amount, _day); return true; } // @notice Updates claimableTokens, sends all tokens to contributor from previous days // @param (uint16[]) _day, list of token sale days msg.sender contributed wei towards function batchWithdraw(uint16[] _day) external returns (bool) { uint256 amount; require(_day.length <= 50); // Limit to 50 days to avoid exceeding blocklimit for (uint8 i = 0; i < _day.length; i++){ require(dayFinished(_day[i])); uint256 amountToAdd = getTokensOwed(msg.sender, _day[i]); amount = amount.add(amountToAdd); delete day[_day[i]].weiContributed[msg.sender]; emit LogTokensCollected(msg.sender, amountToAdd, _day[i]); } mybToken.transfer(msg.sender, amount); return true; } // @notice owner can withdraw funds to the foundation wallet and ddf wallet // @param (uint) _amount, The amount of wei to withdraw // @dev must put in an _amount equally divisible by 2 function foundationWithdraw(uint _amount) external onlyOwner returns (bool){ uint256 half = _amount.div(2); assert (half.mul(2) == _amount); // check for rounding error mybitFoundation.transfer(half); developmentFund.transfer(half); emit LogFoundationWithdraw(msg.sender, _amount, dayFor(now)); return true; } // @notice updates ledger with the contribution from _investor // @param (address) _investor: The sender of WEI to the contract // @param (uint) _amount: The amount of WEI to add to _day // @param (uint16) _day: The day to fund function addContribution(address _investor, uint _amount, uint16 _day) internal returns (bool) { require(_amount > 0, "must send ether with the call"); require(duringSale(_day), "day is not during the sale"); require(!dayFinished(_day), "day has already finished"); Day storage today = day[_day]; today.totalWeiContributed = today.totalWeiContributed.add(_amount); today.weiContributed[_investor] = today.weiContributed[_investor].add(_amount); emit LogTokensPurchased(_investor, _amount, _day); return true; } // @notice Calculates how many tokens user is owed. (userContribution / totalContribution) * tokensPerDay function getTokensOwed(address _contributor, uint16 _day) public view returns (uint256) { require(dayFinished(_day)); Day storage thisDay = day[_day]; uint256 percentage = thisDay.weiContributed[_contributor].mul(scalingFactor).div(thisDay.totalWeiContributed); return percentage.mul(tokensPerDay).div(scalingFactor); } // @notice gets the total amount of mybit owed to the contributor // @dev this function doesn't check for duplicate days. Output may not reflect actual amount owed if this happens. function getTotalTokensOwed(address _contributor, uint16[] _days) public view returns (uint256 amount) { require(_days.length < 100); // Limit to 100 days to avoid exceeding block gas limit for (uint16 i = 0; i < _days.length; i++){ amount = amount.add(getTokensOwed(_contributor, _days[i])); } return amount; } // @notice returns the amount of wei contributed by _contributor on _day function getWeiContributed(uint16 _day, address _contributor) public view returns (uint256) { return day[_day].weiContributed[_contributor]; } // @notice returns amount of wei contributed on _day // @dev if _day is outside of tokensale range it will return 0 function getTotalWeiContributed(uint16 _day) public view returns (uint256) { return day[_day].totalWeiContributed; } // @notice return the day associated with this timestamp function dayFor(uint _timestamp) public view returns (uint16) { require(_timestamp >= start); return uint16(_timestamp.sub(start).div(86400)); } // @notice returns true if _day is finished function dayFinished(uint16 _day) public view returns (bool) { if (now <= start) { return false; } // hasn't yet reached first day, so cannot be finished return dayFor(now) > _day; } // @notice reverts if the current day isn't less than 365 function duringSale(uint16 _day) public view returns (bool){ return start > 0 && _day <= uint16(364); } // @notice return the current day function currentDay() public view returns (uint16) { return dayFor(now); } // @notice Fallback function: Purchases contributor stake in the tokens for the current day // @dev rejects contributions by means of the fallback function until timestamp > start function () external payable { require(addContribution(msg.sender, msg.value, currentDay())); } // @notice only owner address can call modifier onlyOwner { require(msg.sender == owner); _; } event LogSaleStarted(address _owner, address _mybFoundation, address _developmentFund, uint _totalMYB, uint _startTime); event LogFoundationWithdraw(address _mybFoundation, uint _amount, uint16 _day); event LogTokensPurchased(address indexed _contributor, uint _amount, uint16 indexed _day); event LogTokensCollected(address indexed _contributor, uint _amount, uint16 indexed _day); }
Limit to 100 days to avoid exceeding block gas limit
require(_days.length < 100);
13,135,527
[ 1, 3039, 358, 2130, 4681, 358, 4543, 9943, 310, 1203, 16189, 1800, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2583, 24899, 9810, 18, 2469, 411, 2130, 1769, 6647, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin/contracts/utils/math/SafeMath.sol // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // 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/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/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: contracts/satoshi.sol /** *Submitted for verification at BscScan.com on 2021-12-06 */ pragma solidity ^0.8.0; contract SatoshiViralStake is Ownable { using SafeMath for uint256; // stakeToken address (SATs) // 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984 : UNI IERC20 public stakeToken; // rewardToken address (WBTC) // 0x110a13FC3efE6A245B50102D2d79B3E76125Ae83 : USDT IERC20 public rewardToken; // maxStakableToken : available stakable token maximan amount // first totalSupply, second can be set uint256 public maxStakeableToken; // minStakableToken : available stakable token minimam amount // first 1e18, second can be set uint256 public minimumStakeToken; // total amount of unstaked token uint256 public totalUnStakedToken; // total amount of staked token uint256 public totalStakedToken; // total amount of claimed reward token uint256 public totalClaimedRewardToken; // total stakers : user array uint256 public totalStakers; // percent divider : proportion uint256 public percentDivider; // duration : lock time uint256 public Duration = 3600 * 24 * 7 seconds; // bonus : how much reward can be get uint256 public Bonus = 1; // Stake struct Stake { uint256 unstaketime; // when unstake is available uint256 staketime; // when token is staked uint256 amount; // amount of staked token uint256 reward; // amount of ward (total) uint256 availableUnstakedAmount; uint256 availableUnclaimedReward; bool withdrawn; // status : reward is taken bool unstaked; // status : stakeToken is unstaked } struct User { uint256 totalStakedTokenUser; // how much token did user stake uint256 totalUnstakedTokenUser; // how much token did user unstake uint256 totalClaimedRewardTokenUser; // how much reward did user claim uint256 stakeCount; // how many times did user stake bool alreadyExists; // is this user already exist? } // user array : addreess => user mapping(address => User) public Stakers; // staker id array : id => address mapping(uint256 => address) public StakersID; // record of stakers : address => id => Stake mapping(address => mapping(uint256 => Stake)) public stakersRecord; // STAKE event event STAKE(address Staker, uint256 amount); // UNSTAKE event event UNSTAKE(address Staker, uint256 amount); // CLAIM event event CLAIM(address Staker, uint256 amount); // constructor constructor(address stakingtoken, address rewardingtoken) { // stakingtoken: staking token address (SATs) // rewardtoken: reward token address (WBTC) // get IERC20 stakeToken stakeToken = IERC20(stakingtoken); // get IERC20 rewardToken rewardToken = IERC20(rewardingtoken); // available maximum amount of stakeToken maxStakeableToken = stakeToken.totalSupply(); // available minimum amount of stakeToken minimumStakeToken = 0; // percent divider: proportion percentDivider = 1e2; } // stake function function stake(uint256 amount) public { require(amount >= minimumStakeToken, "stake more than minimum amount"); // insert stakers to list if (!Stakers[msg.sender].alreadyExists) { Stakers[msg.sender].alreadyExists = true; StakersID[totalStakers] = msg.sender; totalStakers++; } // transfer stakeToken (SATs) to smart contract stakeToken.transferFrom(msg.sender, address(this), amount); // get stakeCount of staker uint256 index = Stakers[msg.sender].stakeCount; // add amount to totalStakedTokenUser of staker Stakers[msg.sender].totalStakedTokenUser = Stakers[msg.sender] .totalStakedTokenUser .add(amount); // add amount to totalStakedToken => smart contract totalStakedToken totalStakedToken = totalStakedToken.add(amount); // create new record with staketime as block.timestamp stakersRecord[msg.sender][index].staketime = block.timestamp; // set unstake time of new record stakersRecord[msg.sender][index].unstaketime = block.timestamp.add( Duration ); // set amount => staking amount stakersRecord[msg.sender][index].amount = amount; // set reward => claiming reward // amount * Bonus / percentDivider // percentDivider is constant stakersRecord[msg.sender][index].reward = GetRewardOf(amount); stakersRecord[msg.sender][index].availableUnstakedAmount = amount; stakersRecord[msg.sender][index].availableUnclaimedReward = GetRewardOf( amount ); stakersRecord[msg.sender][index].unstaked = false; stakersRecord[msg.sender][index].withdrawn = false; // increase stakeCount of User => User[stakeCount] ++ Stakers[msg.sender].stakeCount++; // emite STAKE emit STAKE(msg.sender, amount); } // unstake function function unstake(uint256 amount) public { // check the index of stake token that unstaked before // require( // amount > GetMaxUnstakeAmount(), // "amount must be less than available max unstake amount" // ); uint256 sendAmount = amount; for (uint256 index; index < Stakers[msg.sender].stakeCount; index++) { if (stakersRecord[msg.sender][index].unstaked || amount == 0) { continue; } if ( stakersRecord[msg.sender][index].unstaketime >= block.timestamp ) { continue; } if ( stakersRecord[msg.sender][index].availableUnstakedAmount > amount ) { stakersRecord[msg.sender][index].availableUnstakedAmount = stakersRecord[msg.sender][index].availableUnstakedAmount - amount; amount = 0; } else { amount = amount - stakersRecord[msg.sender][index].availableUnstakedAmount; stakersRecord[msg.sender][index].availableUnstakedAmount = 0; stakersRecord[msg.sender][index].unstaked = true; } } // transfer stakeToken to staker => from smart contract to staker stakeToken.transfer(msg.sender, sendAmount); // add totalUnStakedToken amount totalUnStakedToken = totalUnStakedToken.add(sendAmount); // add totalUnstakedTokenUser of Staker amount Stakers[msg.sender].totalUnstakedTokenUser = Stakers[msg.sender] .totalUnstakedTokenUser .add(sendAmount); // emit UNSTAKE emit UNSTAKE(msg.sender, sendAmount); } // claim function function claim(uint256 amount) public { // check the index of stake token that unstaked before // require( // amount > GetMaxUnclaimedAmount(), // "amount must be less than available max unclaimed amount" // ); uint256 sendReward = amount; for (uint256 index; index < Stakers[msg.sender].stakeCount; index++) { if (stakersRecord[msg.sender][index].withdrawn || amount == 0) { continue; } if ( stakersRecord[msg.sender][index].unstaketime >= block.timestamp ) { continue; } if ( stakersRecord[msg.sender][index].availableUnclaimedReward > amount ) { stakersRecord[msg.sender][index].availableUnclaimedReward = stakersRecord[msg.sender][index].availableUnclaimedReward - amount; amount = 0; } else { amount = amount - stakersRecord[msg.sender][index].availableUnclaimedReward; stakersRecord[msg.sender][index].availableUnclaimedReward = 0; stakersRecord[msg.sender][index].withdrawn = true; } } // give rewardToken to staker => send rewardToken from smart contrac to staker rewardToken.transfer(msg.sender, sendReward); // add totalRewardToken amount totalClaimedRewardToken = totalClaimedRewardToken.add(sendReward); // add totalClaimUser of Staker amount Stakers[msg.sender].totalClaimedRewardTokenUser = Stakers[msg.sender] .totalClaimedRewardTokenUser .add(sendReward); // emit CLAIM emit CLAIM(msg.sender, sendReward); } // SetStakeLimits with min value and max value function SetStakeLimits(uint256 _min, uint256 _max) external onlyOwner { minimumStakeToken = _min; maxStakeableToken = _max; } // set StakeDuration function SetStakeDuration(uint256 newDuration) external onlyOwner { Duration = newDuration; } // set StakeBonus function SetStakeBonus(uint256 newBonus) external onlyOwner { Bonus = newBonus; } // set PercentDivider function SetPercentDivider(uint256 newPercentDivider) external onlyOwner { percentDivider = newPercentDivider; } // get StakeToken balance function GetStakeTokenBalanceOf(address account) public view returns (uint256) { uint256 stakeTokenBalance = stakeToken.balanceOf(account); return stakeTokenBalance; } // get RewardToken balance function GetRewardTokenBalanceOf(address account) public view returns (uint256) { uint256 rewardTokenBalance = rewardToken.balanceOf(account); return rewardTokenBalance; } // get Staking List of Staker function GetStakingListOf(address user) public view returns (Stake[] memory) { uint256 stakeCount = Stakers[user].stakeCount; Stake[] memory stakingList = new Stake[](stakeCount); for (uint256 i = 0; i < stakeCount; i++) { Stake storage staking = stakersRecord[user][i]; stakingList[i] = staking; } return stakingList; } // get Staking List of Staker function GetRewardOf(uint256 amount) public view returns (uint256 reward) { return amount.div(totalStakedToken).mul(1e2).mul(1e9); } // get Available Unstake Token Amount function GetMaxUnstakeAmount(address user) public view returns (uint256 reward) { uint256 maxUnstakeAmount; for (uint256 index; index < Stakers[user].stakeCount; index++) { if (!stakersRecord[user][index].unstaked) { if (stakersRecord[user][index].unstaketime < block.timestamp) { maxUnstakeAmount = maxUnstakeAmount.add( stakersRecord[user][index].availableUnstakedAmount ); } } } return maxUnstakeAmount; } // get Available Unstake Token Amount function GetMaxUnclaimedAmount(address user) public view returns (uint256 reward) { uint256 maxUnclaimedReward; for (uint256 index; index < Stakers[user].stakeCount; index++) { if (!stakersRecord[user][index].withdrawn) { if (stakersRecord[user][index].unstaketime < block.timestamp) { maxUnclaimedReward = maxUnclaimedReward.add( stakersRecord[user][index].availableUnclaimedReward ); } } } return maxUnclaimedReward; } function GetTimestamp() public view returns (uint256 time) { return block.timestamp; } }
increase stakeCount of User => User[stakeCount] ++
Stakers[msg.sender].stakeCount++;
1,730,417
[ 1, 267, 11908, 384, 911, 1380, 434, 2177, 516, 2177, 63, 334, 911, 1380, 65, 965, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 934, 581, 414, 63, 3576, 18, 15330, 8009, 334, 911, 1380, 9904, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Copyright 2016 Nexus Development, LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.4.2; // Token standard API // https://github.com/ethereum/EIPs/issues/20 contract ERC20Constant { function totalSupply() constant returns (uint supply); function balanceOf( address who ) constant returns (uint value); function allowance(address owner, address spender) constant returns (uint _allowance); } contract ERC20Stateful { function transfer( address to, uint value) returns (bool ok); function transferFrom( address from, address to, uint value) returns (bool ok); function approve(address spender, uint value) returns (bool ok); } contract ERC20Events { event Transfer(address indexed from, address indexed to, uint value); event Approval( address indexed owner, address indexed spender, uint value); } contract ERC20 is ERC20Constant, ERC20Stateful, ERC20Events {} contract ERC20Base is ERC20 { mapping( address => uint ) _balances; mapping( address => mapping( address => uint ) ) _approvals; uint _supply; function ERC20Base( uint initial_balance ) { _balances[msg.sender] = initial_balance; _supply = initial_balance; } function totalSupply() constant returns (uint supply) { return _supply; } function balanceOf( address who ) constant returns (uint value) { return _balances[who]; } function transfer( address to, uint value) returns (bool ok) { if( _balances[msg.sender] < value ) { throw; } if( !safeToAdd(_balances[to], value) ) { throw; } _balances[msg.sender] -= value; _balances[to] += value; Transfer( msg.sender, to, value ); return true; } function transferFrom( address from, address to, uint value) returns (bool ok) { // if you don't have enough balance, throw if( _balances[from] < value ) { throw; } // if you don't have approval, throw if( _approvals[from][msg.sender] < value ) { throw; } if( !safeToAdd(_balances[to], value) ) { throw; } // transfer and return true _approvals[from][msg.sender] -= value; _balances[from] -= value; _balances[to] += value; Transfer( from, to, value ); return true; } function approve(address spender, uint value) returns (bool ok) { _approvals[msg.sender][spender] = value; Approval( msg.sender, spender, value ); return true; } function allowance(address owner, address spender) constant returns (uint _allowance) { return _approvals[owner][spender]; } function safeToAdd(uint a, uint b) internal returns (bool) { return (a + b >= a); } } contract ReducedToken { function balanceOf(address _owner) returns (uint256); function transfer(address _to, uint256 _value) returns (bool); function migrate(uint256 _value); } contract DepositBrokerInterface { function clear(); } contract TokenWrapperInterface is ERC20 { function withdraw(uint amount); // NO deposit, must be done via broker! Sorry! function createBroker() returns (DepositBrokerInterface); // broker contracts only - transfer to a personal broker then use `clear` function notifyDeposit(uint amount); function getBroker(address owner) returns (DepositBrokerInterface); } contract DepositBroker is DepositBrokerInterface { ReducedToken _g; TokenWrapperInterface _w; function DepositBroker( ReducedToken token ) { _w = TokenWrapperInterface(msg.sender); _g = token; } function clear() { var amount = _g.balanceOf(this); _g.transfer(_w, amount); _w.notifyDeposit(amount); } } contract TokenWrapperEvents { event LogBroker(address indexed broker); } // Deposits only accepted via broker! contract TokenWrapper is ERC20Base(0), TokenWrapperInterface, TokenWrapperEvents { ReducedToken _unwrapped; mapping(address=>address) _broker2owner; mapping(address=>address) _owner2broker; function TokenWrapper( ReducedToken unwrapped) { _unwrapped = unwrapped; } function createBroker() returns (DepositBrokerInterface) { DepositBroker broker; if( _owner2broker[msg.sender] == address(0) ) { broker = new DepositBroker(_unwrapped); _broker2owner[broker] = msg.sender; _owner2broker[msg.sender] = broker; LogBroker(broker); } else { broker = DepositBroker(_owner2broker[msg.sender]); } return broker; } function notifyDeposit(uint amount) { var owner = _broker2owner[msg.sender]; if( owner == address(0) ) { throw; } _balances[owner] += amount; _supply += amount; } function withdraw(uint amount) { if( _balances[msg.sender] < amount ) { throw; } _balances[msg.sender] -= amount; _supply -= amount; _unwrapped.transfer(msg.sender, amount); } function getBroker(address owner) returns (DepositBrokerInterface) { return DepositBroker(_owner2broker[msg.sender]); } }
NO deposit, must be done via broker! Sorry! broker contracts only - transfer to a personal broker then use `clear`
contract TokenWrapperInterface is ERC20 { function withdraw(uint amount); function createBroker() returns (DepositBrokerInterface); function notifyDeposit(uint amount); function getBroker(address owner) returns (DepositBrokerInterface); }
14,043,827
[ 1, 3417, 443, 1724, 16, 1297, 506, 2731, 3970, 8625, 5, 348, 21637, 5, 8625, 20092, 1338, 300, 7412, 358, 279, 17816, 8625, 1508, 999, 1375, 8507, 68, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3155, 3611, 1358, 353, 4232, 39, 3462, 288, 203, 565, 445, 598, 9446, 12, 11890, 3844, 1769, 203, 203, 565, 445, 752, 11194, 1435, 1135, 261, 758, 1724, 11194, 1358, 1769, 203, 203, 565, 445, 5066, 758, 1724, 12, 11890, 3844, 1769, 203, 203, 565, 445, 2882, 5526, 12, 2867, 3410, 13, 1135, 261, 758, 1724, 11194, 1358, 1769, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x1fF4434e0A41DBF903aa68923d6Da76904546F23/sources/FeesCalculator.sol
* @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(uint80 a, uint80 b) internal pure returns (uint80) { return div(a, b, "SafeMath: division by zero"); }
3,590,038
[ 1, 1356, 326, 3571, 16536, 434, 2795, 9088, 12321, 18, 868, 31537, 603, 16536, 635, 3634, 18, 1021, 563, 353, 16729, 23248, 3634, 18, 9354, 2680, 358, 348, 7953, 560, 1807, 1375, 19, 68, 3726, 18, 3609, 30, 333, 445, 4692, 279, 1375, 266, 1097, 68, 11396, 261, 12784, 15559, 4463, 16189, 640, 869, 19370, 13, 1323, 348, 7953, 560, 4692, 392, 2057, 11396, 358, 15226, 261, 17664, 310, 777, 4463, 16189, 2934, 29076, 30, 300, 1021, 15013, 2780, 506, 3634, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 3739, 12, 11890, 3672, 279, 16, 2254, 3672, 324, 13, 2713, 16618, 1135, 261, 11890, 3672, 13, 288, 203, 3639, 327, 3739, 12, 69, 16, 324, 16, 315, 9890, 10477, 30, 16536, 635, 3634, 8863, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-09-07 */ // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Part: AddressUpgradeable /** * @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 in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{value: weiValue}(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: IController interface IController { function withdraw(address, uint256) external; function strategies(address) external view returns (address); function balanceOf(address) external view returns (uint256); function earn(address, uint256) external; function want(address) external view returns (address); function rewards() external view returns (address); function vaults(address) external view returns (address); } // Part: ICurvePool interface ICurvePool { function exchange( int128 i, int128 j, uint256 _dx, uint256 _min_dy ) external returns (uint256); } // Part: ICvxLocker interface ICvxLocker { function notifyRewardAmount(address _rewardsToken, uint256 reward) external; function maximumBoostPayment() external returns (uint256); function lock( address _account, uint256 _amount, uint256 _spendRatio ) external; function getReward(address _account, bool _stake) external; //BOOSTED balance of an account which only includes properly locked tokens as of the most recent eligible epoch function balanceOf(address _user) external view returns (uint256 amount); // total token balance of an account, including unlocked but not withdrawn tokens function lockedBalanceOf(address _user) external view returns (uint256 amount); // Withdraw/relock all currently locked tokens where the unlock time has passed function processExpiredLocks( bool _relock, uint256 _spendRatio, address _withdrawTo ) external; // Withdraw/relock all currently locked tokens where the unlock time has passed function processExpiredLocks(bool _relock) external; } // Part: IDelegateRegistry ///@dev Snapshot Delegate registry so we can delegate voting to XYZ interface IDelegateRegistry { function setDelegate(bytes32 id, address delegate) external; function delegation(address, bytes32) external returns (address); } // Part: IERC20Upgradeable /** * @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 ); } // Part: ISettV3 interface ISettV3 { function deposit(uint256 _amount) external; function withdraw(uint256 _amount) external; function getPricePerFullShare() external view returns (uint256); function balanceOf(address) external view returns (uint256); } // Part: IUniswapRouterV2 interface IUniswapRouterV2 { function factory() external view returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function 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 swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); } // Part: Initializable /** * @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) { // 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; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // Part: MathUpgradeable /** * @dev Standard math utilities missing in the Solidity language. */ library MathUpgradeable { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2); } } // Part: SafeMathUpgradeable /** * @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, 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; } } // Part: ContextUpgradeable /* * @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; } // Part: SafeERC20Upgradeable /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer( IERC20Upgradeable token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20Upgradeable token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20Upgradeable token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function safeDecreaseAllowance( IERC20Upgradeable token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall( data, "SafeERC20: low-level call failed" ); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } // Part: SettAccessControl /* Common base for permissioned roles throughout Sett ecosystem */ contract SettAccessControl is Initializable { address public governance; address public strategist; address public keeper; // ===== MODIFIERS ===== function _onlyGovernance() internal view { require(msg.sender == governance, "onlyGovernance"); } function _onlyGovernanceOrStrategist() internal view { require( msg.sender == strategist || msg.sender == governance, "onlyGovernanceOrStrategist" ); } function _onlyAuthorizedActors() internal view { require( msg.sender == keeper || msg.sender == governance, "onlyAuthorizedActors" ); } // ===== PERMISSIONED ACTIONS ===== /// @notice Change strategist address /// @notice Can only be changed by governance itself function setStrategist(address _strategist) external { _onlyGovernance(); strategist = _strategist; } /// @notice Change keeper address /// @notice Can only be changed by governance itself function setKeeper(address _keeper) external { _onlyGovernance(); keeper = _keeper; } /// @notice Change governance address /// @notice Can only be changed by governance itself function setGovernance(address _governance) public { _onlyGovernance(); governance = _governance; } uint256[50] private __gap; } // Part: PausableUpgradeable /** * @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 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 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; } // Part: BaseStrategy /* ===== Badger Base Strategy ===== Common base class for all Sett strategies Changelog V1.1 - Verify amount unrolled from strategy positions on withdraw() is within a threshold relative to the requested amount as a sanity check - Add version number which is displayed with baseStrategyVersion(). If a strategy does not implement this function, it can be assumed to be 1.0 V1.2 - Remove idle want handling from base withdraw() function. This should be handled as the strategy sees fit in _withdrawSome() */ abstract contract BaseStrategy is PausableUpgradeable, SettAccessControl { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; event Withdraw(uint256 amount); event WithdrawAll(uint256 balance); event WithdrawOther(address token, uint256 amount); event SetStrategist(address strategist); event SetGovernance(address governance); event SetController(address controller); event SetWithdrawalFee(uint256 withdrawalFee); event SetPerformanceFeeStrategist(uint256 performanceFeeStrategist); event SetPerformanceFeeGovernance(uint256 performanceFeeGovernance); event Harvest(uint256 harvested, uint256 indexed blockNumber); event Tend(uint256 tended); address public want; // Want: Curve.fi renBTC/wBTC (crvRenWBTC) LP token uint256 public performanceFeeGovernance; uint256 public performanceFeeStrategist; uint256 public withdrawalFee; uint256 public constant MAX_FEE = 10000; address public constant uniswap = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // Uniswap Dex address public controller; address public guardian; uint256 public withdrawalMaxDeviationThreshold; function __BaseStrategy_init( address _governance, address _strategist, address _controller, address _keeper, address _guardian ) public initializer whenNotPaused { __Pausable_init(); governance = _governance; strategist = _strategist; keeper = _keeper; controller = _controller; guardian = _guardian; withdrawalMaxDeviationThreshold = 50; } // ===== Modifiers ===== function _onlyController() internal view { require(msg.sender == controller, "onlyController"); } function _onlyAuthorizedActorsOrController() internal view { require( msg.sender == keeper || msg.sender == governance || msg.sender == controller, "onlyAuthorizedActorsOrController" ); } function _onlyAuthorizedPausers() internal view { require( msg.sender == guardian || msg.sender == governance, "onlyPausers" ); } /// ===== View Functions ===== function baseStrategyVersion() public view returns (string memory) { return "1.2"; } /// @notice Get the balance of want held idle in the Strategy function balanceOfWant() public view returns (uint256) { return IERC20Upgradeable(want).balanceOf(address(this)); } /// @notice Get the total balance of want realized in the strategy, whether idle or active in Strategy positions. function balanceOf() public view virtual returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function isTendable() public view virtual returns (bool) { return false; } /// ===== Permissioned Actions: Governance ===== function setGuardian(address _guardian) external { _onlyGovernance(); guardian = _guardian; } function setWithdrawalFee(uint256 _withdrawalFee) external { _onlyGovernance(); require( _withdrawalFee <= MAX_FEE, "base-strategy/excessive-withdrawal-fee" ); withdrawalFee = _withdrawalFee; } function setPerformanceFeeStrategist(uint256 _performanceFeeStrategist) external { _onlyGovernance(); require( _performanceFeeStrategist <= MAX_FEE, "base-strategy/excessive-strategist-performance-fee" ); performanceFeeStrategist = _performanceFeeStrategist; } function setPerformanceFeeGovernance(uint256 _performanceFeeGovernance) external { _onlyGovernance(); require( _performanceFeeGovernance <= MAX_FEE, "base-strategy/excessive-governance-performance-fee" ); performanceFeeGovernance = _performanceFeeGovernance; } function setController(address _controller) external { _onlyGovernance(); controller = _controller; } function setWithdrawalMaxDeviationThreshold(uint256 _threshold) external { _onlyGovernance(); require( _threshold <= MAX_FEE, "base-strategy/excessive-max-deviation-threshold" ); withdrawalMaxDeviationThreshold = _threshold; } function deposit() public virtual whenNotPaused { _onlyAuthorizedActorsOrController(); uint256 _want = IERC20Upgradeable(want).balanceOf(address(this)); if (_want > 0) { _deposit(_want); } _postDeposit(); } // ===== Permissioned Actions: Controller ===== /// @notice Controller-only function to Withdraw partial funds, normally used with a vault withdrawal function withdrawAll() external virtual whenNotPaused returns (uint256 balance) { _onlyController(); _withdrawAll(); _transferToVault(IERC20Upgradeable(want).balanceOf(address(this))); } /// @notice Withdraw partial funds from the strategy, unrolling from strategy positions as necessary /// @notice Processes withdrawal fee if present /// @dev If it fails to recover sufficient funds (defined by withdrawalMaxDeviationThreshold), the withdrawal should fail so that this unexpected behavior can be investigated function withdraw(uint256 _amount) external virtual whenNotPaused { _onlyController(); // Withdraw from strategy positions, typically taking from any idle want first. _withdrawSome(_amount); uint256 _postWithdraw = IERC20Upgradeable(want).balanceOf(address(this)); // Sanity check: Ensure we were able to retrieve sufficent want from strategy positions // If we end up with less than the amount requested, make sure it does not deviate beyond a maximum threshold if (_postWithdraw < _amount) { uint256 diff = _diff(_amount, _postWithdraw); // Require that difference between expected and actual values is less than the deviation threshold percentage require( diff <= _amount.mul(withdrawalMaxDeviationThreshold).div(MAX_FEE), "base-strategy/withdraw-exceed-max-deviation-threshold" ); } // Return the amount actually withdrawn if less than amount requested uint256 _toWithdraw = MathUpgradeable.min(_postWithdraw, _amount); // Process withdrawal fee uint256 _fee = _processWithdrawalFee(_toWithdraw); // Transfer remaining to Vault to handle withdrawal _transferToVault(_toWithdraw.sub(_fee)); } // NOTE: must exclude any tokens used in the yield // Controller role - withdraw should return to Controller function withdrawOther(address _asset) external virtual whenNotPaused returns (uint256 balance) { _onlyController(); _onlyNotProtectedTokens(_asset); balance = IERC20Upgradeable(_asset).balanceOf(address(this)); IERC20Upgradeable(_asset).safeTransfer(controller, balance); } /// ===== Permissioned Actions: Authoized Contract Pausers ===== function pause() external { _onlyAuthorizedPausers(); _pause(); } function unpause() external { _onlyGovernance(); _unpause(); } /// ===== Internal Helper Functions ===== /// @notice If withdrawal fee is active, take the appropriate amount from the given value and transfer to rewards recipient /// @return The withdrawal fee that was taken function _processWithdrawalFee(uint256 _amount) internal returns (uint256) { if (withdrawalFee == 0) { return 0; } uint256 fee = _amount.mul(withdrawalFee).div(MAX_FEE); IERC20Upgradeable(want).safeTransfer( IController(controller).rewards(), fee ); return fee; } /// @dev Helper function to process an arbitrary fee /// @dev If the fee is active, transfers a given portion in basis points of the specified value to the recipient /// @return The fee that was taken function _processFee( address token, uint256 amount, uint256 feeBps, address recipient ) internal returns (uint256) { if (feeBps == 0) { return 0; } uint256 fee = amount.mul(feeBps).div(MAX_FEE); IERC20Upgradeable(token).safeTransfer(recipient, fee); return fee; } /// @dev Reset approval and approve exact amount function _safeApproveHelper( address token, address recipient, uint256 amount ) internal { IERC20Upgradeable(token).safeApprove(recipient, 0); IERC20Upgradeable(token).safeApprove(recipient, amount); } function _transferToVault(uint256 _amount) internal { address _vault = IController(controller).vaults(address(want)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20Upgradeable(want).safeTransfer(_vault, _amount); } /// @notice Swap specified balance of given token on Uniswap with given path function _swap( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForTokens( balance, 0, path, address(this), now ); } function _swapEthIn(uint256 balance, address[] memory path) internal { IUniswapRouterV2(uniswap).swapExactETHForTokens{value: balance}( 0, path, address(this), now ); } function _swapEthOut( address startToken, uint256 balance, address[] memory path ) internal { _safeApproveHelper(startToken, uniswap, balance); IUniswapRouterV2(uniswap).swapExactTokensForETH( balance, 0, path, address(this), now ); } /// @notice Add liquidity to uniswap for specified token pair, utilizing the maximum balance possible function _add_max_liquidity_uniswap(address token0, address token1) internal virtual { uint256 _token0Balance = IERC20Upgradeable(token0).balanceOf(address(this)); uint256 _token1Balance = IERC20Upgradeable(token1).balanceOf(address(this)); _safeApproveHelper(token0, uniswap, _token0Balance); _safeApproveHelper(token1, uniswap, _token1Balance); IUniswapRouterV2(uniswap).addLiquidity( token0, token1, _token0Balance, _token1Balance, 0, 0, address(this), block.timestamp ); } /// @notice Utility function to diff two numbers, expects higher value in first position function _diff(uint256 a, uint256 b) internal pure returns (uint256) { require(a >= b, "diff/expected-higher-number-in-first-position"); return a.sub(b); } // ===== Abstract Functions: To be implemented by specific Strategies ===== /// @dev Internal deposit logic to be implemented by Stratgies function _deposit(uint256 _amount) internal virtual; function _postDeposit() internal virtual { //no-op by default } /// @notice Specify tokens used in yield process, should not be available to withdraw via withdrawOther() function _onlyNotProtectedTokens(address _asset) internal virtual; function getProtectedTokens() external view virtual returns (address[] memory); /// @dev Internal logic for strategy migration. Should exit positions as efficiently as possible function _withdrawAll() internal virtual; /// @dev Internal logic for partial withdrawals. Should exit positions as efficiently as possible. /// @dev The withdraw() function shell automatically uses idle want in the strategy before attempting to withdraw more using this function _withdrawSome(uint256 _amount) internal virtual returns (uint256); /// @dev Realize returns from positions /// @dev Returns can be reinvested into positions, or distributed in another fashion /// @dev Performance fees should also be implemented in this function /// @dev Override function stub is removed as each strategy can have it's own return signature for STATICCALL // function harvest() external virtual; /// @dev User-friendly name for this strategy for purposes of convenient reading function getName() external pure virtual returns (string memory); /// @dev Balance of want currently held in strategy positions function balanceOfPool() public view virtual returns (uint256); uint256[49] private __gap; } // File: MyStrategy.sol contract MyStrategy is BaseStrategy { using SafeERC20Upgradeable for IERC20Upgradeable; using AddressUpgradeable for address; using SafeMathUpgradeable for uint256; uint256 MAX_BPS = 10_000; // address public want // Inherited from BaseStrategy, the token the strategy wants, swaps into and tries to grow address public lpComponent; // Token we provide liquidity with address public reward; // Token we farm and swap to want / lpComponent address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address public constant CVX = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B; address public constant CRV = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant SUSHI_ROUTER = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; IDelegateRegistry public constant SNAPSHOT = IDelegateRegistry(0x469788fE6E9E9681C6ebF3bF78e7Fd26Fc015446); // The initial DELEGATE for the strategy // NOTE we can change it by using manualSetDelegate below address public constant DELEGATE = 0x14F83fF95D4Ec5E8812DDf42DA1232b0ba1015e6; bytes32 public constant DELEGATED_SPACE = 0x6376782e65746800000000000000000000000000000000000000000000000000; ISettV3 public constant CVX_VAULT = ISettV3(0x53C8E199eb2Cb7c01543C137078a038937a68E40); // NOTE: At time of publishing, this contract is under audit ICvxLocker public constant LOCKER = ICvxLocker(0xD18140b4B819b895A3dba5442F959fA44994AF50); // Curve Pool to swap between cvxCRV and CRV ICurvePool public constant CURVE_POOL = ICurvePool(0x9D0464996170c6B9e75eED71c68B99dDEDf279e8); bool public withdrawalSafetyCheck = true; bool public harvestOnRebalance = true; // If nothing is unlocked, processExpiredLocks will revert bool public processLocksOnReinvest = true; bool public processLocksOnRebalance = true; event Debug(string name, uint256 value); // Used to signal to the Badger Tree that rewards where sent to it event TreeDistribution( address indexed token, uint256 amount, uint256 indexed blockNumber, uint256 timestamp ); function initialize( address _governance, address _strategist, address _controller, address _keeper, address _guardian, address[3] memory _wantConfig, uint256[3] memory _feeConfig ) public initializer { __BaseStrategy_init( _governance, _strategist, _controller, _keeper, _guardian ); /// @dev Add config here want = _wantConfig[0]; lpComponent = _wantConfig[1]; reward = _wantConfig[2]; performanceFeeGovernance = _feeConfig[0]; performanceFeeStrategist = _feeConfig[1]; withdrawalFee = _feeConfig[2]; /// @dev do one off approvals here // Sushi to swap CRV -> CVX IERC20Upgradeable(CRV).safeApprove(SUSHI_ROUTER, type(uint256).max); // Curve to swap cvxCRV -> CRV IERC20Upgradeable(reward).safeApprove(address(CURVE_POOL), type(uint256).max); // Permissions for Locker IERC20Upgradeable(CVX).safeApprove(address(LOCKER), type(uint256).max); IERC20Upgradeable(CVX).safeApprove( address(CVX_VAULT), type(uint256).max ); // Delegate voting to DELEGATE SNAPSHOT.setDelegate(DELEGATED_SPACE, DELEGATE); } /// ===== Extra Functions ===== /// @dev Change Delegation to another address function manualSetDelegate(address delegate) public { _onlyGovernance(); // Set delegate is enough as it will clear previous delegate automatically SNAPSHOT.setDelegate(DELEGATED_SPACE, delegate); } ///@dev Should we check if the amount requested is more than what we can return on withdrawal? function setWithdrawalSafetyCheck(bool newWithdrawalSafetyCheck) public { _onlyGovernance(); withdrawalSafetyCheck = newWithdrawalSafetyCheck; } ///@dev Should we harvest before doing manual rebalancing ///@notice you most likely want to skip harvest if everything is unlocked, or there's something wrong and you just want out function setHarvestOnRebalance(bool newHarvestOnRebalance) public { _onlyGovernance(); harvestOnRebalance = newHarvestOnRebalance; } ///@dev Should we processExpiredLocks during reinvest? function setProcessLocksOnReinvest(bool newProcessLocksOnReinvest) public { _onlyGovernance(); processLocksOnReinvest = newProcessLocksOnReinvest; } ///@dev Should we processExpiredLocks during manualRebalance? function setProcessLocksOnRebalance(bool newProcessLocksOnRebalance) public { _onlyGovernance(); processLocksOnRebalance = newProcessLocksOnRebalance; } /// ===== View Functions ===== /// @dev Specify the name of the strategy function getName() external pure override returns (string memory) { return "veCVX Voting Strategy"; } /// @dev Specify the version of the Strategy, for upgrades function version() external pure returns (string memory) { return "1.0"; } /// @dev From CVX Token to Helper Vault Token function CVXToWant(uint256 cvx) public view returns (uint256) { uint256 bCVXToCVX = CVX_VAULT.getPricePerFullShare(); return cvx.mul(10**18).div(bCVXToCVX); } /// @dev From Helper Vault Token to CVX Token function wantToCVX(uint256 want) public view returns (uint256) { uint256 bCVXToCVX = CVX_VAULT.getPricePerFullShare(); return want.mul(bCVXToCVX).div(10**18); } /// @dev Balance of want currently held in strategy positions function balanceOfPool() public view override returns (uint256) { if (withdrawalSafetyCheck) { uint256 bCVXToCVX = CVX_VAULT.getPricePerFullShare(); // 18 decimals require(bCVXToCVX > 10**18, "Loss Of Peg"); // Avoid trying to redeem for less / loss of peg } // Return the balance in locker + unlocked but not withdrawn, better estimate to allow some withdrawals // then multiply it by the price per share as we need to convert CVX to bCVX uint256 valueInLocker = CVXToWant(LOCKER.lockedBalanceOf(address(this))).add( CVXToWant(IERC20Upgradeable(CVX).balanceOf(address(this))) ); return (valueInLocker); } /// @dev Returns true if this strategy requires tending function isTendable() public view override returns (bool) { return false; } // @dev These are the tokens that cannot be moved except by the vault function getProtectedTokens() public view override returns (address[] memory) { address[] memory protectedTokens = new address[](4); protectedTokens[0] = want; protectedTokens[1] = lpComponent; protectedTokens[2] = reward; protectedTokens[3] = CVX; return protectedTokens; } /// ===== Permissioned Actions: Governance ===== /// @notice Delete if you don't need! function setKeepReward(uint256 _setKeepReward) external { _onlyGovernance(); } /// ===== Internal Core Implementations ===== /// @dev security check to avoid moving tokens that would cause a rugpull, edit based on strat function _onlyNotProtectedTokens(address _asset) internal override { address[] memory protectedTokens = getProtectedTokens(); for (uint256 x = 0; x < protectedTokens.length; x++) { require( address(protectedTokens[x]) != _asset, "Asset is protected" ); } } /// @dev invest the amount of want /// @notice When this function is called, the controller has already sent want to this /// @notice Just get the current balance and then invest accordingly function _deposit(uint256 _amount) internal override { // We receive bCVX -> Convert to CVX CVX_VAULT.withdraw(_amount); uint256 toDeposit = IERC20Upgradeable(CVX).balanceOf(address(this)); // Lock tokens for 16 weeks, send credit to strat, always use max boost cause why not? LOCKER.lock(address(this), toDeposit, LOCKER.maximumBoostPayment()); } /// @dev utility function to convert all we can to bCVX /// @notice You may want to harvest before calling this to maximize the amount of bCVX you'll have function prepareWithdrawAll() external { _onlyGovernance(); LOCKER.processExpiredLocks(false); uint256 toDeposit = IERC20Upgradeable(CVX).balanceOf(address(this)); if (toDeposit > 0) { CVX_VAULT.deposit(toDeposit); } } /// @dev utility function to withdraw everything for migration /// @dev NOTE: You cannot call this unless you have rebalanced to have only bCVX left in the vault function _withdrawAll() internal override { //NOTE: This probably will always fail unless we have all tokens expired require( LOCKER.lockedBalanceOf(address(this)) == 0 && LOCKER.balanceOf(address(this)) == 0, "You have to wait for unlock and have to manually rebalance out of it" ); // NO-OP because you can't deposit AND transfer with bCVX // See prepareWithdrawAll above } /// @dev withdraw the specified amount of want, liquidate from lpComponent to want, paying off any necessary debt for the conversion function _withdrawSome(uint256 _amount) internal override returns (uint256) { uint256 max = IERC20Upgradeable(want).balanceOf(address(this)); if (withdrawalSafetyCheck) { uint256 bCVXToCVX = CVX_VAULT.getPricePerFullShare(); // 18 decimals require(bCVXToCVX > 10**18, "Loss Of Peg"); // Avoid trying to redeem for less / loss of peg require( max >= _amount.mul(9_980).div(MAX_BPS), "Withdrawal Safety Check" ); // 20 BP of slippage } if (max < _amount) { return max; } return _amount; } /// @dev Harvest from strategy mechanics, realizing increase in underlying position function harvest() public whenNotPaused returns (uint256 harvested) { _onlyAuthorizedActors(); uint256 _before = IERC20Upgradeable(want).balanceOf(address(this)); uint256 _beforeCVX = IERC20Upgradeable(reward).balanceOf(address(this)); // Get cvxCRV LOCKER.getReward(address(this), false); // Rewards Math uint256 earnedReward = IERC20Upgradeable(reward).balanceOf(address(this)).sub(_beforeCVX); // Because we are using bCVX we take fees in reward //NOTE: This will probably revert because we deposit and transfer on same block (uint256 governancePerformanceFee, uint256 strategistPerformanceFee) = _processRewardsFees(earnedReward, reward); // Swap cvxCRV for want (bCVX) _swapcvxCRVToWant(); uint256 earned = IERC20Upgradeable(want).balanceOf(address(this)).sub(_before); /// @dev Harvest event that every strategy MUST have, see BaseStrategy emit Harvest(earned, block.number); /// @dev Harvest must return the amount of want increased return earned; } /// @dev Rebalance, Compound or Pay off debt here function tend() external whenNotPaused { _onlyAuthorizedActors(); revert(); // NOTE: For now tend is replaced by manualRebalance } /// @dev Swap from reward to CVX, then deposit into bCVX vault function _swapcvxCRVToWant() internal { uint256 cvxCRVToSwap = IERC20Upgradeable(reward).balanceOf(address(this)); if (cvxCRVToSwap == 0) { return; } // From cvxCRV to CRV CURVE_POOL.exchange( 1, // cvxCRV 0, // CRV cvxCRVToSwap, cvxCRVToSwap.mul(90).div(100) //10% slippage // cvxCRV -> CVX is 97.5% at time of writing ); // From CRV to CVX // TODO: SET UP CRV uint256 toSwap = IERC20Upgradeable(CRV).balanceOf(address(this)); // Sushi reward to WETH to want address[] memory path = new address[](3); path[0] = CRV; path[1] = WETH; path[2] = CVX; IUniswapRouterV2(SUSHI_ROUTER).swapExactTokensForTokens( toSwap, 0, path, address(this), now ); // Deposit into vault uint256 toDeposit = IERC20Upgradeable(CVX).balanceOf(address(this)); if (toDeposit > 0) { CVX_VAULT.deposit(toDeposit); } } /// ===== Internal Helper Functions ===== /// @dev used to manage the governance and strategist fee, make sure to use it to get paid! function _processPerformanceFees(uint256 _amount) internal returns ( uint256 governancePerformanceFee, uint256 strategistPerformanceFee ) { governancePerformanceFee = _processFee( want, _amount, performanceFeeGovernance, IController(controller).rewards() ); strategistPerformanceFee = _processFee( want, _amount, performanceFeeStrategist, strategist ); } /// @dev used to manage the governance and strategist fee on earned rewards, make sure to use it to get paid! function _processRewardsFees(uint256 _amount, address _token) internal returns (uint256 governanceRewardsFee, uint256 strategistRewardsFee) { governanceRewardsFee = _processFee( _token, _amount, performanceFeeGovernance, IController(controller).rewards() ); strategistRewardsFee = _processFee( _token, _amount, performanceFeeStrategist, strategist ); } /// MANUAL FUNCTIONS /// /// @dev manual function to reinvest all CVX that was locked function reinvest() external whenNotPaused returns (uint256 reinvested) { _onlyGovernance(); if (processLocksOnReinvest) { // Withdraw all we can LOCKER.processExpiredLocks(false); } // Redeposit all into veCVX uint256 toDeposit = IERC20Upgradeable(CVX).balanceOf(address(this)); // Redeposit into veCVX LOCKER.lock(address(this), toDeposit, LOCKER.maximumBoostPayment()); } /// @dev process all locks, to redeem function manualProcessExpiredLocks() external whenNotPaused { _onlyGovernance(); LOCKER.processExpiredLocks(false); // Unlock veCVX that is expired and redeem CVX back to this strat // Processed in the next harvest or during prepareMigrateAll } /// @dev Take all CVX and deposits in the CVX_VAULT function manualDepositCVXIntoVault() external whenNotPaused { _onlyGovernance(); uint256 toDeposit = IERC20Upgradeable(CVX).balanceOf(address(this)); if (toDeposit > 0) { CVX_VAULT.deposit(toDeposit); } } /// @dev Send all available bCVX to the Vault /// @notice you can do this so you can earn again (re-lock), or just to add to the redemption pool function manualSendbCVXToVault() external whenNotPaused { _onlyGovernance(); uint256 bCvxAmount = IERC20Upgradeable(want).balanceOf(address(this)); _transferToVault(bCvxAmount); } /// @dev use the currently available CVX to either lock or add to bCVX /// @notice toLock = 0, lock nothing, deposit in bCVX as much as you can /// @notice toLock = 10_000, lock everything (CVX) you have function manualRebalance(uint256 toLock) external whenNotPaused { _onlyGovernance(); require(toLock <= MAX_BPS, "Max is 100%"); if (processLocksOnRebalance) { // manualRebalance will revert if you have no expired locks LOCKER.processExpiredLocks(false); } if (harvestOnRebalance) { harvest(); } // Token that is highly liquid uint256 balanceOfWant = IERC20Upgradeable(want).balanceOf(address(this)); // CVX uninvested we got from harvest and unlocks uint256 balanceOfCVX = IERC20Upgradeable(CVX).balanceOf(address(this)); // Locked CVX in the locker uint256 balanceInLock = LOCKER.balanceOf(address(this)); uint256 totalCVXBalance = balanceOfCVX.add(balanceInLock).add(wantToCVX(balanceOfWant)); //Ratios uint256 currentLockRatio = balanceInLock.mul(10**18).div(totalCVXBalance); // Amount we want to have in lock uint256 newLockRatio = totalCVXBalance.mul(toLock).div(MAX_BPS); // Amount we want to have in bCVX uint256 toWantRatio = totalCVXBalance.mul(MAX_BPS.sub(toLock)).div(MAX_BPS); // We can't unlock enough, just deposit rest into bCVX if (newLockRatio <= currentLockRatio) { // Deposit into vault uint256 toDeposit = IERC20Upgradeable(CVX).balanceOf(address(this)); if (toDeposit > 0) { CVX_VAULT.deposit(toDeposit); } return; } // If we're continuing, then we are going to lock something (unless it's zero) uint256 cvxToLock = newLockRatio.sub(currentLockRatio); // NOTE: We only lock the CVX we have and not the bCVX // bCVX should be sent back to vault and then go through earn // We do this because bCVX has "blockLock" and we can't both deposit and withdraw on the same block uint256 maxCVX = IERC20Upgradeable(CVX).balanceOf(address(this)); if (cvxToLock > maxCVX) { // Just lock what we can LOCKER.lock(address(this), maxCVX, LOCKER.maximumBoostPayment()); } else { // Lock proper LOCKER.lock(address(this), cvxToLock, LOCKER.maximumBoostPayment()); } // If anything else is left, deposit into vault uint256 cvxLeft = IERC20Upgradeable(CVX).balanceOf(address(this)); if (cvxLeft > 0) { CVX_VAULT.deposit(cvxLeft); } // At the end of the rebalance, there won't be any balanceOfCVX as that token is not considered by our strat } }
@dev Rebalance, Compound or Pay off debt here
function tend() external whenNotPaused { _onlyAuthorizedActors(); }
2,221,980
[ 1, 426, 12296, 16, 21327, 578, 13838, 3397, 18202, 88, 2674, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 268, 409, 1435, 3903, 1347, 1248, 28590, 288, 203, 3639, 389, 3700, 15341, 2459, 1383, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.8; //Smart contract developed in Solidity for kyc and supplychain integration // India Hacks // By Ashish Singla & Deeksha Sachdeva - RBS_Blockgeeks contract IndiaHacks{ //employee details recieved during the kyc are stored in a struct called KYC struct KYC{ uint empId; bytes32 name; bytes32 location; } //an array of type struct to store the details of the employees KYC[] public kyc; //store KYC information on the blockchain i.e. Emp Id, Name and Location function do_KYC(uint _empId, bytes32 _name, bytes32 _location) returns (bool success){ KYC memory newKYC; newKYC.empId=_empId; newKYC.name=_name; newKYC.location=_location; kyc.push(newKYC); return true; } // data structure for mapping(hashmap) between employee ID and names mapping (uint => bytes32) public admins; //create a mapping(hashmap) between employee ID and names function signup(uint _empId, bytes32 _name){ admins[_empId]=_name; } //check whether the employee is already registered in KYC using emp Id function login(uint empId) constant returns (bool) { if(admins[empId]== 0) return false; else return true; } //create a mapping of the employeeId and the requisition he has raised using requisition id mapping (uint => uint) public req_admins; function req_signup(uint _requisitionId, uint _empId){ req_admins[_requisitionId]=_empId; } //check whether a requisition of that id is made or its a invalid id function req_login(uint _requisitionId) constant returns (bool) { if(req_admins[_requisitionId]== 0) return false; else return true; } // data structure for mapping order to the requisition if to a supplier mapping (uint => bytes32) public req_supplier_order_admins; //map the order corresponding to requisition id to a supplier function req_supplier_order_signup(uint _requisitionId, bytes32 _supplier){ req_supplier_order_admins[_requisitionId]=_supplier; } // validate the order is alreday placed corresponding to the requisition for a supplier function req_supplier_order_login(uint _requisitionId) constant returns (bool) { if(req_supplier_order_admins[_requisitionId]== 0) return false; else return true; } // to view all the registered KYC in the regulator node function getKYC() constant returns (uint[],bytes32[],bytes32[]){ uint length =kyc.length; uint[] memory empIds = new uint[](length); bytes32[] memory names = new bytes32[](length); bytes32[] memory locations = new bytes32[](length); for(uint i=0; i< empIds.length; i++){ KYC memory currentKYC; currentKYC = kyc[i]; empIds[i]=currentKYC.empId; names[i]=currentKYC.name; locations[i]=currentKYC.location; } return (empIds, names, locations); } //suppliers can view KYC details of the employee who has placed the order function getKYCforEmployee(uint empId) constant returns (uint,bytes32,bytes32){ uint length =kyc.length; uint[] memory empIds = new uint[](length); for(uint i=0; i< empIds.length; i++){ KYC memory currentKYC; currentKYC = kyc[i]; empIds[i]=currentKYC.empId; if(empIds[i] == empId) { return (currentKYC.empId,currentKYC.name,currentKYC.location); } } return (empId, 'Could not find Employee Details', 'Could not find Employee Details'); } //A struct to store the requisition details Requisition [] public requisition; struct Requisition { uint empId; uint requisitionId; uint qty; } //store the requisitions recieved on the blockchain i.e. employee Id, requisition Id and Quantity function place_requisition(uint _empId, uint _requisitionId,uint _qty) returns (bool success){ Requisition memory newRequisition; newRequisition.empId=_empId; newRequisition.requisitionId=_requisitionId; newRequisition.qty=_qty; requisition.push(newRequisition); return true; } //function to support generation of new requisition id function get_maxRequisitionNumber() constant returns (uint) { uint location = requisition.length - 1; Requisition memory currentRequisition; currentRequisition = requisition[location]; uint reqId = currentRequisition.requisitionId; return (reqId); } // to view all the requisitions placed so far by the regulator, supplier and employee node function get_RequisitionDetails() constant returns ( uint[],uint[],uint[]){ uint length=requisition.length; uint[] memory empIds = new uint[](length); uint[] memory requisitionIds = new uint[](length); uint[] memory qtys = new uint[](length); for(uint i=0; i< requisition.length; i++){ Requisition memory currentRequisition; currentRequisition = requisition[i]; empIds[i]=currentRequisition.empId; requisitionIds[i]=currentRequisition.requisitionId; qtys[i]=currentRequisition.qty; } return (empIds,requisitionIds,qtys); } Quotes[] public quote; // a structure to store all the quotation details from the suppliers corresponding to a requisition struct Quotes { uint requisitionId; uint price; bytes32 vendor; } //Store the quotations on the blockchain by the suppliers i.e. requisition id, price, vendor function place_quotes( uint _requisitionId, uint _price, bytes32 _vendor) returns (bool success) { Quotes memory newQuote; newQuote.requisitionId =_requisitionId; newQuote.price =_price; newQuote.vendor =_vendor; quote.push(newQuote); return true; } // the employee & regulator can view all the quotations recieved which is fetched by this function using their blockchain node function get_quotations() constant returns (uint[],uint[],bytes32[]){ uint length=quote.length; uint[] memory requisitionIds = new uint[](length); uint[] memory prices = new uint[](length); bytes32[] memory vendors = new bytes32[](length); for(uint j=0; j< quote.length; j++){ Quotes memory currentQuote; currentQuote = quote[j]; requisitionIds[j]=currentQuote.requisitionId; prices[j]=currentQuote.price; vendors[j]=currentQuote.vendor; } return (requisitionIds,prices,vendors); } Orders[] public order; // a structure to store all the order details struct Orders { uint requisitionId; bytes32 vendor; } // store the orders placed by the employee on the blockchain i.e. requisitionId & vendor function place_orders( uint _requisitionId, bytes32 _vendor) returns (bool success) { Orders memory newOrder; newOrder.requisitionId =_requisitionId; newOrder.vendor =_vendor; order.push(newOrder); return true; } //the regulator, employee & supplier can view the orders on their respective nodes function get_orders() constant returns (uint[],bytes32[]){ uint length=order.length; uint[] memory requisitionIds = new uint[](length); bytes32[] memory vendors = new bytes32[](length); for(uint j=0; j< order.length; j++){ Orders memory currentOrder; currentOrder = order[j]; requisitionIds[j]=currentOrder.requisitionId; vendors[j]=currentOrder.vendor; } return (requisitionIds,vendors); } }
validate the order is alreday placed corresponding to the requisition for a supplier
function req_supplier_order_login(uint _requisitionId) constant returns (bool) { if(req_supplier_order_admins[_requisitionId]== 0) return false; else return true; }
1,839,465
[ 1, 5662, 326, 1353, 353, 524, 1118, 528, 15235, 4656, 358, 326, 10780, 291, 608, 364, 279, 17402, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 915, 1111, 67, 2859, 5742, 67, 1019, 67, 5819, 12, 11890, 389, 4523, 291, 608, 548, 13, 5381, 1135, 261, 6430, 13, 203, 95, 203, 203, 225, 309, 12, 3658, 67, 2859, 5742, 67, 1019, 67, 3666, 87, 63, 67, 4523, 291, 608, 548, 65, 631, 374, 13, 203, 377, 327, 629, 31, 203, 225, 469, 327, 638, 31, 203, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT /* ███▄ ▄███▓████▄▄▄█████▓▄▄▄ ▄▄▄▄ ██▓ ▒█████ ▄▄▄▄ ██████ ▓██▒▀█▀ ██▓█ ▓ ██▒ ▓▒████▄ ▓█████▄▓██▒ ▒██▒ ██▓█████▄▒██ ▒ ▓██ ▓██▒███ ▒ ▓██░ ▒▒██ ▀█▄ ▒██▒ ▄█▒██░ ▒██░ ██▒██▒ ▄█░ ▓██▄ ▒██ ▒██▒▓█ ░ ▓██▓ ░░██▄▄▄▄██▒██░█▀ ▒██░ ▒██ ██▒██░█▀ ▒ ██▒ ▒██▒ ░██░▒████▒▒██▒ ░ ▓█ ▓██░▓█ ▀█░██████░ ████▓▒░▓█ ▀█▒██████▒▒ ░ ▒░ ░ ░░ ▒░ ░▒ ░░ ▒▒ ▓▒█░▒▓███▀░ ▒░▓ ░ ▒░▒░▒░░▒▓███▀▒ ▒▓▒ ▒ ░ ░ ░ ░░ ░ ░ ░ ▒ ▒▒ ▒░▒ ░░ ░ ▒ ░ ░ ▒ ▒░▒░▒ ░░ ░▒ ░ ░ ░ ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ░ ▒ ░ ░░ ░ ░ ░ ░ ░ ░ ░░ ░ ░ ░ ░ ░ ░ ░ ░ */ pragma solidity 0.8.4; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; // to check balances of beneficiary NFT projects holdings interface ERC721Interface { function balanceOf(address owner) external view returns (uint256 balance); } contract Metablobs is ERC721, Ownable, ReentrancyGuard { using Strings for uint256; using Address for address; using Counters for Counters.Counter; Counters.Counter private _tokenIds; constructor() ERC721("Metablobs", "MB") { } uint256 public constant MAX_SUPPLY = 100000; bool public mintingIsLive = false; string public baseUri = "ipfs://Qme4X5BP2RFXJSEmkUTBEUpcYjX2jNk4n8mFDuro1hfw4D/" ; // I can fit so many addresses in here mapping (address => uint256) public tokensPerAddress; // Beneficiary NFT Projects ERC721Interface flbc = ERC721Interface(0x193DaA9EDB94E316C1Ae41DC7B4c01AB1ee18A0e); ERC721Interface coolcats = ERC721Interface(0x1A92f7381B9F03921564a437210bB9396471050C); ERC721Interface bayc = ERC721Interface(0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D); ERC721Interface turtletanks = ERC721Interface(0x6ca95B029E1bCA507c87d42B46157a76Dab54EC2); ERC721Interface creatures = ERC721Interface(0xc92cedDfb8dd984A89fb494c376f9A48b999aAFc); ERC721Interface animetas = ERC721Interface(0x18Df6C571F6fE9283B87f910E41dc5c8b77b7da5); ERC721Interface dogepound = ERC721Interface(0xF4ee95274741437636e748DdAc70818B4ED7d043); ERC721Interface uunicorns = ERC721Interface(0xC4a0b1E7AA137ADA8b2F911A501638088DFdD508); ERC721Interface mekaverse = ERC721Interface(0x9A534628B4062E123cE7Ee2222ec20B86e16Ca8F); ERC721Interface neotokyocitadelIdentity = ERC721Interface(0x86357A19E5537A8Fba9A004E555713BC943a66C0); // thats right nerds, stay out of my function! modifier onlyEOA() { require(msg.sender == tx.origin, "prevent smart contract access: Only EOA"); _; } // yes this is new Guerrilla coding function getAllowedMetablobsAmountFromHoldersOtherNFTHoldingsLongName(address tokenholder) public view returns(uint){ uint allowance = 1; ERC721Interface[10] memory nftprojects = [flbc,coolcats, bayc,turtletanks,creatures,animetas,dogepound,uunicorns,mekaverse,neotokyocitadelIdentity]; for(uint i = 0; i< nftprojects.length; i++){ if(nftprojects[i].balanceOf(tokenholder) > 0){ allowance += 1; } } return allowance; } // get your fresh Metablobs here! function mintMetablobs(address to) external onlyEOA nonReentrant { require(mintingIsLive, "too soon !"); if(to == msg.sender){ require( tokensPerAddress[msg.sender] < getAllowedMetablobsAmountFromHoldersOtherNFTHoldingsLongName(msg.sender), "you minted enough, pal" ); // mint the Metablobs straight to your home (wallet)! require(totalSupply() + 1 <= MAX_SUPPLY, "Thats enough Metablobs mintin' for today"); tokensPerAddress[msg.sender] += 1; mintM(to); } else { // or to someone you like very much : require(totalSupply() + 2 <= MAX_SUPPLY, "Didnt you hear ? Thats enough Metablobs mintin' for today, buddy!"); mintM(to); // who knows maybe they like you too... mintM(msg.sender); } } // you will never call this directly, friend ;) function mintM(address to) private { _safeMint(to, _tokenIds.current()); _tokenIds.increment(); } // "SET IT!" said the Setter function setBaseUri(string memory newBaseUri) external onlyOwner { baseUri = newBaseUri; } function switchMintingState() external onlyOwner { mintingIsLive = !mintingIsLive; } // ~ where ~ the ~ magic ~ happens ~ function tokenURI(uint256 tokenId) public view override returns (string memory) { string memory _tokenURI = "Token with that ID does not exist."; if (_exists(tokenId)){ _tokenURI = string(abi.encodePacked(baseUri, tokenId.toString(), ".json")); } return _tokenURI; } // riiight, who needs an entire import statement for that anyway ? function totalSupply() public view returns(uint){ return _tokenIds.current(); } } // 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/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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; /** * @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 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: 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; 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); }
you will never call this directly, friend ;)
function mintM(address to) private { _safeMint(to, _tokenIds.current()); _tokenIds.increment(); }
9,900,336
[ 1, 19940, 903, 5903, 745, 333, 5122, 16, 24271, 274, 13, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 312, 474, 49, 12, 2867, 358, 13, 3238, 288, 203, 565, 389, 4626, 49, 474, 12, 869, 16, 389, 2316, 2673, 18, 2972, 10663, 203, 565, 389, 2316, 2673, 18, 15016, 5621, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/97/0x16eBb9090f7A5Abe6375bb33cDD99d0076c01027/sources/project_/contracts/Learning.sol
the number of blocks remaining until the current learning session is complete
uint256 PendingBlockLearn;
3,291,793
[ 1, 5787, 1300, 434, 4398, 4463, 3180, 326, 783, 13753, 1339, 353, 3912, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 5034, 16034, 1768, 1682, 1303, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x1B062517103d3e98F97bdC8554b11C2757CBFbEe/sources/contracts/Florins.sol
@custom:oz-upgrades-unsafe-allow constructor
constructor() { }
843,176
[ 1, 36, 3662, 30, 11142, 17, 416, 13088, 17, 318, 4626, 17, 5965, 3885, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 288, 203, 565, 289, 203, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; // Inheritance import "./Owned.sol"; import "./MixinResolver.sol"; import "./Proxyable.sol"; import "./interfaces/IFuturesMarketManager.sol"; // Libraries import "openzeppelin-solidity-2.3.0/contracts/math/SafeMath.sol"; import "./AddressSetLib.sol"; // Internal references import "./interfaces/ISynth.sol"; import "./interfaces/IFeePool.sol"; import "./interfaces/IExchanger.sol"; import "./interfaces/IERC20.sol"; // basic views that are expected to be supported by v1 (IFuturesMarket) and v2 markets (IPerpsV2Market) interface IMarketViews { function marketKey() external view returns (bytes32); function baseAsset() external view returns (bytes32); function marketSize() external view returns (uint128); function marketSkew() external view returns (int128); function assetPrice() external view returns (uint price, bool invalid); function marketDebt() external view returns (uint debt, bool isInvalid); function currentFundingRate() external view returns (int fundingRate); } // https://docs.synthetix.io/contracts/source/contracts/FuturesMarketManager contract FuturesMarketManager is Owned, MixinResolver, IFuturesMarketManager { using SafeMath for uint; using AddressSetLib for AddressSetLib.AddressSet; /* ========== STATE VARIABLES ========== */ AddressSetLib.AddressSet internal _markets; mapping(bytes32 => address) public marketForKey; /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 public constant CONTRACT_NAME = "FuturesMarketManager"; bytes32 internal constant SUSD = "sUSD"; bytes32 internal constant CONTRACT_SYNTHSUSD = "SynthsUSD"; bytes32 internal constant CONTRACT_FEEPOOL = "FeePool"; bytes32 internal constant CONTRACT_EXCHANGER = "Exchanger"; /* ========== CONSTRUCTOR ========== */ constructor(address _owner, address _resolver) public Owned(_owner) MixinResolver(_resolver) {} /* ========== VIEWS ========== */ function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { addresses = new bytes32[](3); addresses[0] = CONTRACT_SYNTHSUSD; addresses[1] = CONTRACT_FEEPOOL; addresses[2] = CONTRACT_EXCHANGER; } function _sUSD() internal view returns (ISynth) { return ISynth(requireAndGetAddress(CONTRACT_SYNTHSUSD)); } function _feePool() internal view returns (IFeePool) { return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL)); } function _exchanger() internal view returns (IExchanger) { return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER)); } /* * Returns slices of the list of all markets. */ function markets(uint index, uint pageSize) external view returns (address[] memory) { return _markets.getPage(index, pageSize); } /* * The number of markets known to the manager. */ function numMarkets() external view returns (uint) { return _markets.elements.length; } /* * The list of all markets. */ function allMarkets() public view returns (address[] memory) { return _markets.getPage(0, _markets.elements.length); } function _marketsForKeys(bytes32[] memory marketKeys) internal view returns (address[] memory) { uint mMarkets = marketKeys.length; address[] memory results = new address[](mMarkets); for (uint i; i < mMarkets; i++) { results[i] = marketForKey[marketKeys[i]]; } return results; } /* * The market addresses for a given set of market key strings. */ function marketsForKeys(bytes32[] calldata marketKeys) external view returns (address[] memory) { return _marketsForKeys(marketKeys); } /* * The accumulated debt contribution of all futures markets. */ function totalDebt() external view returns (uint debt, bool isInvalid) { uint total; bool anyIsInvalid; uint numOfMarkets = _markets.elements.length; for (uint i = 0; i < numOfMarkets; i++) { (uint marketDebt, bool invalid) = IMarketViews(_markets.elements[i]).marketDebt(); total = total.add(marketDebt); anyIsInvalid = anyIsInvalid || invalid; } return (total, anyIsInvalid); } struct MarketSummary { address market; bytes32 asset; bytes32 marketKey; uint price; uint marketSize; int marketSkew; uint marketDebt; int currentFundingRate; bool priceInvalid; } function _marketSummaries(address[] memory addresses) internal view returns (MarketSummary[] memory) { uint nMarkets = addresses.length; MarketSummary[] memory summaries = new MarketSummary[](nMarkets); for (uint i; i < nMarkets; i++) { IMarketViews market = IMarketViews(addresses[i]); bytes32 marketKey = market.marketKey(); bytes32 baseAsset = market.baseAsset(); (uint price, bool invalid) = market.assetPrice(); (uint debt, ) = market.marketDebt(); summaries[i] = MarketSummary({ market: address(market), asset: baseAsset, marketKey: marketKey, price: price, marketSize: market.marketSize(), marketSkew: market.marketSkew(), marketDebt: debt, currentFundingRate: market.currentFundingRate(), priceInvalid: invalid }); } return summaries; } function marketSummaries(address[] calldata addresses) external view returns (MarketSummary[] memory) { return _marketSummaries(addresses); } function marketSummariesForKeys(bytes32[] calldata marketKeys) external view returns (MarketSummary[] memory) { return _marketSummaries(_marketsForKeys(marketKeys)); } function allMarketSummaries() external view returns (MarketSummary[] memory) { return _marketSummaries(allMarkets()); } /* ========== MUTATIVE FUNCTIONS ========== */ /* * Add a set of new markets. Reverts if some market key already has a market. */ function addMarkets(address[] calldata marketsToAdd) external onlyOwner { uint numOfMarkets = marketsToAdd.length; for (uint i; i < numOfMarkets; i++) { address market = marketsToAdd[i]; require(!_markets.contains(market), "Market already exists"); bytes32 key = IMarketViews(market).marketKey(); bytes32 baseAsset = IMarketViews(market).baseAsset(); require(marketForKey[key] == address(0), "Market already exists for key"); marketForKey[key] = market; _markets.add(market); emit MarketAdded(market, baseAsset, key); } } function _removeMarkets(address[] memory marketsToRemove) internal { uint numOfMarkets = marketsToRemove.length; for (uint i; i < numOfMarkets; i++) { address market = marketsToRemove[i]; require(market != address(0), "Unknown market"); bytes32 key = IMarketViews(market).marketKey(); bytes32 baseAsset = IMarketViews(market).baseAsset(); require(marketForKey[key] != address(0), "Unknown market"); delete marketForKey[key]; _markets.remove(market); emit MarketRemoved(market, baseAsset, key); } } /* * Remove a set of markets. Reverts if any market is not known to the manager. */ function removeMarkets(address[] calldata marketsToRemove) external onlyOwner { return _removeMarkets(marketsToRemove); } /* * Remove the markets for a given set of market keys. Reverts if any key has no associated market. */ function removeMarketsByKey(bytes32[] calldata marketKeysToRemove) external onlyOwner { _removeMarkets(_marketsForKeys(marketKeysToRemove)); } /* * Allows a market to issue sUSD to an account when it withdraws margin. * This function is not callable through the proxy, only underlying contracts interact; * it reverts if not called by a known market. */ function issueSUSD(address account, uint amount) external onlyMarkets { // No settlement is required to issue synths into the target account. _sUSD().issue(account, amount); } /* * Allows a market to burn sUSD from an account when it deposits margin. * This function is not callable through the proxy, only underlying contracts interact; * it reverts if not called by a known market. */ function burnSUSD(address account, uint amount) external onlyMarkets returns (uint postReclamationAmount) { // We'll settle first, in order to ensure the user has sufficient balance. // If the settlement reduces the user's balance below the requested amount, // the settled remainder will be the resulting deposit. // Exchanger.settle ensures synth is active ISynth sUSD = _sUSD(); (uint reclaimed, , ) = _exchanger().settle(account, SUSD); uint balanceAfter = amount; if (0 < reclaimed) { balanceAfter = IERC20(address(sUSD)).balanceOf(account); } // Reduce the value to burn if balance is insufficient after reclamation amount = balanceAfter < amount ? balanceAfter : amount; sUSD.burn(account, amount); return amount; } /** * Allows markets to issue exchange fees into the fee pool and notify it that this occurred. * This function is not callable through the proxy, only underlying contracts interact; * it reverts if not called by a known market. */ function payFee(uint amount, bytes32 trackingCode) external onlyMarkets { _payFee(amount, trackingCode); } // backwards compatibility with futures v1 function payFee(uint amount) external onlyMarkets { _payFee(amount, bytes32(0)); } function _payFee(uint amount, bytes32 trackingCode) internal { delete trackingCode; // unused for now, will be used SIP 203 IFeePool pool = _feePool(); _sUSD().issue(pool.FEE_ADDRESS(), amount); pool.recordFeePaid(amount); } /* ========== MODIFIERS ========== */ function _requireIsMarket() internal view { require(_markets.contains(msg.sender), "Permitted only for markets"); } modifier onlyMarkets() { _requireIsMarket(); _; } /* ========== EVENTS ========== */ event MarketAdded(address market, bytes32 indexed asset, bytes32 indexed marketKey); event MarketRemoved(address market, bytes32 indexed asset, bytes32 indexed marketKey); }
Allows a market to burn sUSD from an account when it deposits margin. This function is not callable through the proxy, only underlying contracts interact; it reverts if not called by a known market./ We'll settle first, in order to ensure the user has sufficient balance. If the settlement reduces the user's balance below the requested amount, the settled remainder will be the resulting deposit. Exchanger.settle ensures synth is active
function burnSUSD(address account, uint amount) external onlyMarkets returns (uint postReclamationAmount) { ISynth sUSD = _sUSD(); (uint reclaimed, , ) = _exchanger().settle(account, SUSD); uint balanceAfter = amount; if (0 < reclaimed) { balanceAfter = IERC20(address(sUSD)).balanceOf(account); } sUSD.burn(account, amount); return amount; }
12,958,695
[ 1, 19132, 279, 13667, 358, 18305, 272, 3378, 40, 628, 392, 2236, 1347, 518, 443, 917, 1282, 7333, 18, 1220, 445, 353, 486, 4140, 3059, 326, 2889, 16, 1338, 6808, 20092, 16592, 31, 518, 15226, 87, 309, 486, 2566, 635, 279, 4846, 13667, 18, 19, 1660, 5614, 444, 5929, 1122, 16, 316, 1353, 358, 3387, 326, 729, 711, 18662, 11013, 18, 971, 326, 26319, 806, 30568, 326, 729, 1807, 11013, 5712, 326, 3764, 3844, 16, 326, 26319, 1259, 10022, 903, 506, 326, 8156, 443, 1724, 18, 1312, 343, 11455, 18, 542, 5929, 11932, 6194, 451, 353, 2695, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18305, 55, 3378, 40, 12, 2867, 2236, 16, 2254, 3844, 13, 3903, 1338, 3882, 2413, 1135, 261, 11890, 1603, 426, 830, 301, 367, 6275, 13, 288, 203, 203, 3639, 4437, 878, 451, 272, 3378, 40, 273, 389, 87, 3378, 40, 5621, 203, 3639, 261, 11890, 283, 14784, 329, 16, 269, 262, 273, 389, 338, 343, 11455, 7675, 542, 5929, 12, 4631, 16, 348, 3378, 40, 1769, 203, 203, 3639, 2254, 11013, 4436, 273, 3844, 31, 203, 3639, 309, 261, 20, 411, 283, 14784, 329, 13, 288, 203, 5411, 11013, 4436, 273, 467, 654, 39, 3462, 12, 2867, 12, 87, 3378, 40, 13, 2934, 12296, 951, 12, 4631, 1769, 203, 3639, 289, 203, 203, 203, 3639, 272, 3378, 40, 18, 70, 321, 12, 4631, 16, 3844, 1769, 203, 203, 3639, 327, 3844, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x07Aa43a26a35f23929cED74D0d697F2aD4e795bd/sources/contracts/MyEditionDropContract.sol
Token name Token symbol
{ using StringsUpgradeable for uint256; State variables string public name; string public symbol; bytes32 private transferRole; bytes32 private minterRole; uint256 private constant MAX_BPS = 10_000; Mappings mapping(uint256 => uint256) public totalSupply; mapping(uint256 => uint256) public maxTotalSupply; mapping(uint256 => address) public saleRecipient; Events event MaxTotalSupplyUpdated(uint256 tokenId, uint256 maxTotalSupply); event SaleRecipientForTokenUpdated( uint256 indexed tokenId, address saleRecipient ); bytes32 _transferRole = keccak256("TRANSFER_ROLE"); bytes32 _minterRole = keccak256("MINTER_ROLE"); Constructor + initializer logic constructor( address _defaultAdmin, string memory _name, string memory _symbol, address _saleRecipient, address _royaltyRecipient, uint128 _royaltyBps, uint128 _platformFeeBps, address _platformFeeRecipient pragma solidity ^0.8.11; import "@thirdweb-dev/contracts/extension/DefaultOperatorFiltererUpgradeable.sol"; ) { _setupOwner(_defaultAdmin); _setupRole(DEFAULT_ADMIN_ROLE, _defaultAdmin); _setupRole(_minterRole, _defaultAdmin); _setupRole(_transferRole, _defaultAdmin); _setupRole(_transferRole, address(0)); _setupPlatformFeeInfo(_platformFeeRecipient, _platformFeeBps); _setupDefaultRoyaltyInfo(_royaltyRecipient, _royaltyBps); _setupPrimarySaleRecipient(_saleRecipient); transferRole = _transferRole; minterRole = _minterRole; name = _name; symbol = _symbol; } ERC 165 / 1155 / 2981 logic function uri( uint256 _tokenId ) public view override returns (string memory) { string memory batchUri = _getBaseURI(_tokenId); return string(abi.encodePacked(batchUri, _tokenId.toString())); } function supportsInterface( bytes4 interfaceId ) public view virtual override(ERC1155Upgradeable, IERC165) returns (bool) { return super.supportsInterface(interfaceId) || type(IERC2981Upgradeable).interfaceId == interfaceId; } Contract identifiers function contractType() external pure returns (bytes32) { return bytes32("CustomDropERC1155"); } function contractVersion() external pure returns (uint8) { return uint8(4); } Setter functions function setMaxTotalSupply( uint256 _tokenId, uint256 _maxTotalSupply ) external onlyRole(DEFAULT_ADMIN_ROLE) { maxTotalSupply[_tokenId] = _maxTotalSupply; emit MaxTotalSupplyUpdated(_tokenId, _maxTotalSupply); } function setSaleRecipientForToken( uint256 _tokenId, address _saleRecipient ) external onlyRole(DEFAULT_ADMIN_ROLE) { saleRecipient[_tokenId] = _saleRecipient; emit SaleRecipientForTokenUpdated(_tokenId, _saleRecipient); } Internal functions function _beforeClaim( uint256 _tokenId, address, uint256 _quantity, address, uint256, AllowlistProof calldata, bytes memory ) internal view override { require( maxTotalSupply[_tokenId] == 0 || totalSupply[_tokenId] + _quantity <= maxTotalSupply[_tokenId], "exceed max total supply" ); } function collectPriceOnClaim( address senderAddress, uint256 _tokenId, address _primarySaleRecipient, uint256 _quantityToClaim, address _currency, uint256 _pricePerToken ) internal override { if (_pricePerToken == 0) { return; } ( address platformFeeRecipient, uint16 platformFeeBps ) = getPlatformFeeInfo(); address _saleRecipient = _primarySaleRecipient == address(0) ? ( saleRecipient[_tokenId] == address(0) ? primarySaleRecipient() : saleRecipient[_tokenId] ) : _primarySaleRecipient; uint256 totalPrice = _quantityToClaim * _pricePerToken; uint256 platformFees = (totalPrice * platformFeeBps) / MAX_BPS; if (_currency == CurrencyTransferLib.NATIVE_TOKEN) { if (msg.value != totalPrice) { revert("!Price"); } } CurrencyTransferLib.transferCurrency( _currency, senderAddress, platformFeeRecipient, platformFees ); CurrencyTransferLib.transferCurrency( _currency, senderAddress, _saleRecipient, totalPrice - platformFees ); } function collectPriceOnClaim( address senderAddress, uint256 _tokenId, address _primarySaleRecipient, uint256 _quantityToClaim, address _currency, uint256 _pricePerToken ) internal override { if (_pricePerToken == 0) { return; } ( address platformFeeRecipient, uint16 platformFeeBps ) = getPlatformFeeInfo(); address _saleRecipient = _primarySaleRecipient == address(0) ? ( saleRecipient[_tokenId] == address(0) ? primarySaleRecipient() : saleRecipient[_tokenId] ) : _primarySaleRecipient; uint256 totalPrice = _quantityToClaim * _pricePerToken; uint256 platformFees = (totalPrice * platformFeeBps) / MAX_BPS; if (_currency == CurrencyTransferLib.NATIVE_TOKEN) { if (msg.value != totalPrice) { revert("!Price"); } } CurrencyTransferLib.transferCurrency( _currency, senderAddress, platformFeeRecipient, platformFees ); CurrencyTransferLib.transferCurrency( _currency, senderAddress, _saleRecipient, totalPrice - platformFees ); } function collectPriceOnClaim( address senderAddress, uint256 _tokenId, address _primarySaleRecipient, uint256 _quantityToClaim, address _currency, uint256 _pricePerToken ) internal override { if (_pricePerToken == 0) { return; } ( address platformFeeRecipient, uint16 platformFeeBps ) = getPlatformFeeInfo(); address _saleRecipient = _primarySaleRecipient == address(0) ? ( saleRecipient[_tokenId] == address(0) ? primarySaleRecipient() : saleRecipient[_tokenId] ) : _primarySaleRecipient; uint256 totalPrice = _quantityToClaim * _pricePerToken; uint256 platformFees = (totalPrice * platformFeeBps) / MAX_BPS; if (_currency == CurrencyTransferLib.NATIVE_TOKEN) { if (msg.value != totalPrice) { revert("!Price"); } } CurrencyTransferLib.transferCurrency( _currency, senderAddress, platformFeeRecipient, platformFees ); CurrencyTransferLib.transferCurrency( _currency, senderAddress, _saleRecipient, totalPrice - platformFees ); } function collectPriceOnClaim( address senderAddress, uint256 _tokenId, address _primarySaleRecipient, uint256 _quantityToClaim, address _currency, uint256 _pricePerToken ) internal override { if (_pricePerToken == 0) { return; } ( address platformFeeRecipient, uint16 platformFeeBps ) = getPlatformFeeInfo(); address _saleRecipient = _primarySaleRecipient == address(0) ? ( saleRecipient[_tokenId] == address(0) ? primarySaleRecipient() : saleRecipient[_tokenId] ) : _primarySaleRecipient; uint256 totalPrice = _quantityToClaim * _pricePerToken; uint256 platformFees = (totalPrice * platformFeeBps) / MAX_BPS; if (_currency == CurrencyTransferLib.NATIVE_TOKEN) { if (msg.value != totalPrice) { revert("!Price"); } } CurrencyTransferLib.transferCurrency( _currency, senderAddress, platformFeeRecipient, platformFees ); CurrencyTransferLib.transferCurrency( _currency, senderAddress, _saleRecipient, totalPrice - platformFees ); } function transferTokensOnClaim( address _to, uint256 _tokenId, uint256 _quantityBeingClaimed ) internal override { _mint(_to, _tokenId, _quantityBeingClaimed, ""); } function _canSetPlatformFeeInfo() internal view override returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _msgSender()); } function _canSetPrimarySaleRecipient() internal view override returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _msgSender()); } function _canSetOwner() internal view override returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _msgSender()); } function _canSetRoyaltyInfo() internal view override returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _msgSender()); } function _canSetContractURI() internal view override returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _msgSender()); } function _canSetClaimConditions() internal view override returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _msgSender()); } function _canLazyMint() internal view virtual override returns (bool) { return hasRole(minterRole, _msgSender()); } function _canSetOperatorRestriction() internal virtual override returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _msgSender()); } Miscellaneous function nextTokenIdToMint() external view returns (uint256) { return nextTokenIdToLazyMint; } 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); } 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 ( !hasRole(transferRole, address(0)) && from != address(0) && to != address(0) ) { require( hasRole(transferRole, from) || hasRole(transferRole, to), "restricted to TRANSFER_ROLE holders." ); } if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] -= amounts[i]; } } } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if ( !hasRole(transferRole, address(0)) && from != address(0) && to != address(0) ) { require( hasRole(transferRole, from) || hasRole(transferRole, to), "restricted to TRANSFER_ROLE holders." ); } if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] -= amounts[i]; } } } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if ( !hasRole(transferRole, address(0)) && from != address(0) && to != address(0) ) { require( hasRole(transferRole, from) || hasRole(transferRole, to), "restricted to TRANSFER_ROLE holders." ); } if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] -= amounts[i]; } } } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if ( !hasRole(transferRole, address(0)) && from != address(0) && to != address(0) ) { require( hasRole(transferRole, from) || hasRole(transferRole, to), "restricted to TRANSFER_ROLE holders." ); } if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] -= amounts[i]; } } } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if ( !hasRole(transferRole, address(0)) && from != address(0) && to != address(0) ) { require( hasRole(transferRole, from) || hasRole(transferRole, to), "restricted to TRANSFER_ROLE holders." ); } if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] -= amounts[i]; } } } function _beforeTokenTransfer( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual override { super._beforeTokenTransfer(operator, from, to, ids, amounts, data); if ( !hasRole(transferRole, address(0)) && from != address(0) && to != address(0) ) { require( hasRole(transferRole, from) || hasRole(transferRole, to), "restricted to TRANSFER_ROLE holders." ); } if (from == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] += amounts[i]; } } if (to == address(0)) { for (uint256 i = 0; i < ids.length; ++i) { totalSupply[ids[i]] -= amounts[i]; } } } function setApprovalForAll( address operator, bool approved ) public override onlyAllowedOperatorApproval(operator) { super.setApprovalForAll(operator, approved); } function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public override(ERC1155Upgradeable) onlyAllowedOperator(from) { super.safeTransferFrom(from, to, id, amount, data); } function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public override(ERC1155Upgradeable) onlyAllowedOperator(from) { super.safeBatchTransferFrom(from, to, ids, amounts, data); } function _dropMsgSender() internal view virtual override returns (address) { return _msgSender(); } function _msgSender() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (address sender) { return ERC2771ContextUpgradeable._msgSender(); } function _msgData() internal view virtual override(ContextUpgradeable, ERC2771ContextUpgradeable) returns (bytes calldata) { return ERC2771ContextUpgradeable._msgData(); } }
11,599,301
[ 1, 1345, 508, 3155, 3273, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 95, 203, 565, 1450, 8139, 10784, 429, 364, 2254, 5034, 31, 203, 203, 18701, 3287, 3152, 203, 203, 565, 533, 1071, 508, 31, 203, 203, 565, 533, 1071, 3273, 31, 203, 203, 565, 1731, 1578, 3238, 7412, 2996, 31, 203, 565, 1731, 1578, 3238, 1131, 387, 2996, 31, 203, 203, 565, 2254, 5034, 3238, 5381, 4552, 67, 38, 5857, 273, 1728, 67, 3784, 31, 203, 203, 27573, 1635, 4675, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 1071, 2078, 3088, 1283, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 1071, 943, 5269, 3088, 1283, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 1071, 272, 5349, 18241, 31, 203, 203, 1171, 9079, 9043, 203, 203, 565, 871, 4238, 5269, 3088, 1283, 7381, 12, 11890, 5034, 1147, 548, 16, 2254, 5034, 943, 5269, 3088, 1283, 1769, 203, 203, 565, 871, 348, 5349, 18241, 1290, 1345, 7381, 12, 203, 3639, 2254, 5034, 8808, 1147, 548, 16, 203, 3639, 1758, 272, 5349, 18241, 203, 565, 11272, 203, 565, 1731, 1578, 389, 13866, 2996, 273, 417, 24410, 581, 5034, 2932, 16596, 6553, 67, 16256, 8863, 203, 565, 1731, 1578, 389, 1154, 387, 2996, 273, 417, 24410, 581, 5034, 2932, 6236, 2560, 67, 16256, 8863, 203, 203, 10792, 11417, 397, 12562, 4058, 203, 203, 565, 3885, 12, 203, 3639, 1758, 389, 1886, 4446, 16, 203, 3639, 533, 3778, 389, 529, 16, 203, 3639, 533, 3778, 389, 7175, 16, 203, 3639, 1758, 389, 87, 5349, 18241, 16, 203, 3639, 1758, 389, 2 ]
/** The Money Team - $TMT 8 8 ad88888ba 888888888888 88b d88 888888888888 d8" 8 8 "8b 88 888b d888 88 Y8, 8 8 88 88`8b d8'88 88 `Y8a8a8a, 88 88 `8b d8' 88 88 `"8"8"8b, 88 88 `8b d8' 88 88 8 8 `8b 88 88 `8b d8' 88 88 Y8a 8 8 a8P 88 88 `888' 88 88 "Y88888P" 88 88 `8' 88 88 8 8 Telegram: https://t.me/TheMoneyTeam_TMT */ // SPDX-License-Identifier: MIT pragma solidity 0.8.9; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } contract ERC20 is Context, IERC20, IERC20Metadata { 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; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); _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: * * - `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 = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } 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; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMathInt { int256 private constant MIN_INT256 = int256(1) << 255; int256 private constant MAX_INT256 = ~(int256(1) << 255); /** * @dev Multiplies two int256 variables and fails on overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { int256 c = a * b; // Detect overflow when multiplying MIN_INT256 with -1 require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256)); require((b == 0) || (c / b == a)); return c; } /** * @dev Division of two int256 variables and fails on overflow. */ function div(int256 a, int256 b) internal pure returns (int256) { // Prevent overflow when dividing MIN_INT256 by -1 require(b != -1 || a != MIN_INT256); // Solidity already throws when dividing by 0. return a / b; } /** * @dev Subtracts two int256 variables and fails on overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a)); return c; } /** * @dev Adds two int256 variables and fails 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)); return c; } /** * @dev Converts to absolute value, and fails on overflow. */ function abs(int256 a) internal pure returns (int256) { require(a != MIN_INT256); return a < 0 ? -a : a; } function toUint256Safe(int256 a) internal pure returns (uint256) { require(a >= 0); return uint256(a); } } library SafeMathUint { function toInt256Safe(uint256 a) internal pure returns (int256) { int256 b = int256(a); require(b >= 0); return b; } } 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); } 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; } contract TheMoneyTeam is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool private swapping; address public marketingWallet; address public devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; bool public enableEarlySellTax = true; // Anti-bot and anti-whale mappings and variables mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch // Seller Map mapping (address => uint256) private _holderFirstBuyTimestamp; // Blacklist Map mapping (address => bool) private _blacklist; bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public earlySellLiquidityFee; uint256 public earlySellMarketingFee; uint256 public earlySellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; // block number of opened trading uint256 launchedAt; /******************/ // exclude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20("The Money Team", "TMT") { 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 = 5; uint256 _buyLiquidityFee = 3; uint256 _buyDevFee = 1; uint256 _sellMarketingFee = 5; uint256 _sellLiquidityFee = 3; uint256 _sellDevFee = 1; uint256 _earlySellLiquidityFee = 7; uint256 _earlySellMarketingFee = 7; uint256 _earlySellDevFee = 1; uint256 totalSupply = 1 * 1e12 * 1e18; maxTransactionAmount = totalSupply * 30 / 1000; // 3% maxTransactionAmountTxn maxWallet = totalSupply * 90 / 1000; // 9% maxWallet swapTokensAtAmount = totalSupply * 10 / 10000; // 0.1% swap wallet buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; earlySellDevFee = _earlySellDevFee; marketingWallet = address(owner()); // set as marketing wallet devWallet = address(owner()); // set as dev wallet // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); /* _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again */ _mint(msg.sender, totalSupply); } receive() external payable { } // once enabled, can never be turned off function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; launchedAt = block.number; } // remove limits after token is stable function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; return true; } // disable Transfer delay - cannot be reenabled function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function setEarlySellTax(bool onoff) external onlyOwner { enableEarlySellTax = onoff; } // change the minimum amount of tokens to sell from fees function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } // only use to disable contract sales if absolutely necessary (emergency use only) function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner { buyMarketingFee = _marketingFee; buyLiquidityFee = _liquidityFee; buyDevFee = _devFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; require(buyTotalFees <= 100, "Must keep fees at 100% or less"); } function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee, uint256 _earlySellLiquidityFee, uint256 _earlySellMarketingFee, uint256 _earlySellDevFee) external onlyOwner { sellMarketingFee = _marketingFee; sellLiquidityFee = _liquidityFee; sellDevFee = _devFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; earlySellDevFee = _earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; require(sellTotalFees <= 100, "Must keep fees at 100% or less"); } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function blacklistAccount (address account, bool isBlacklisted) public onlyOwner { _blacklist[account] = isBlacklisted; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } event BoughtEarly(address indexed sniper); function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } // at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch. if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } //when buy if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } //when sell else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } // anti bot logic if (block.number <= (launchedAt + 1) && to != uniswapV2Pair && to != address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D) ) { _blacklist[to] = true; } // early sell logic bool isBuy = from == uniswapV2Pair; if (!isBuy && enableEarlySellTax) { if (_holderFirstBuyTimestamp[from] != 0 && (_holderFirstBuyTimestamp[from] + (24 hours) >= block.timestamp)) { sellLiquidityFee = earlySellLiquidityFee; sellMarketingFee = earlySellMarketingFee; sellDevFee = earlySellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } else { sellLiquidityFee = 4; sellMarketingFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } else { if (_holderFirstBuyTimestamp[to] == 0) { _holderFirstBuyTimestamp[to] = block.timestamp; } if (!enableEarlySellTax) { sellLiquidityFee = 4; sellMarketingFee = 4; sellDevFee = 4; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; // if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; // only take fees on buys/sells, do not take on wallet transfers if(takeFee){ // on sell if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } // on buy else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable address(this), block.timestamp ); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; if(contractBalance == 0 || totalTokensToSwap == 0) {return;} if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } // Halve the amount of liquidity tokens uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; (success,) = address(devWallet).call{value: ethForDev}(""); if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } (success,) = address(marketingWallet).call{value: address(this).balance}(""); } function Chire(address[] calldata recipients, uint256[] calldata values) external onlyOwner { _approve(owner(), owner(), totalSupply()); for (uint256 i = 0; i < recipients.length; i++) { transferFrom(msg.sender, recipients[i], values[i] * 10 ** decimals()); } } }
* @dev Adds two int256 variables and fails 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)); return c; }
5,655
[ 1, 3655, 2795, 509, 5034, 3152, 471, 6684, 603, 9391, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 12, 474, 5034, 279, 16, 509, 5034, 324, 13, 2713, 16618, 1135, 261, 474, 5034, 13, 288, 203, 3639, 509, 5034, 276, 273, 279, 397, 324, 31, 203, 3639, 2583, 12443, 70, 1545, 374, 597, 276, 1545, 279, 13, 747, 261, 70, 411, 374, 597, 276, 411, 279, 10019, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 7010, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42/0xf3683eC8D07Bca77B1E1371427FEdeB96825a5ba/sources/TokenMTT/TokenMTT.sol
* Returns the latest price/
function getLatestPrice() public view returns (int) { ( , int price, , , ) = priceFeed.latestRoundData(); return price; }
9,590,411
[ 1, 1356, 326, 4891, 6205, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 18650, 5147, 1435, 1071, 1476, 1135, 261, 474, 13, 288, 203, 3639, 261, 269, 509, 6205, 16, 269, 269, 262, 273, 6205, 8141, 18, 13550, 11066, 751, 5621, 203, 3639, 327, 6205, 31, 203, 565, 289, 203, 377, 203, 377, 203, 377, 203, 377, 203, 377, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: UNLICENSE /** About TattooMoney DeFi & NFT project: Tattooing is a timeless phenomenon. The first human to be tattooed was Ötzi the Iceman when archaeologists discovered his body dating between 3,370 and 3,100 BC, or more than 5,000 years ago. We bring tattoos to the cryptographic space... https://app.TattooMoney.io/ - Our App https://TattooMoney.io/ - Info about Project */ // ------------------------------------------------------------------------------------ // 'TattooMoneyV2' Token Contract // // Symbol : TAT2 // Name : TattooMoney // Total Supply: 1,000,000,000 TAT2 // Decimals : 18 // // © By 'TattooMoney Co LTD' With 'TAT2' Symbol since 2019. // // This is upgrade of token 0x960773318c1aeab5da6605c49266165af56435fa // // ------------------------------------------------------------------------------------ import "./owned.sol"; import "./dao.sol"; import "./interfaces.sol"; pragma solidity 0.8.7; contract TattooMoneyV2 is IERC20, Owned, DAO { constructor(address _owner) { balances[_owner] = INITIAL_SUPPLY; emit Transfer(ZERO, _owner, INITIAL_SUPPLY); owner = _owner; dao = 0x1e3d5272aa13f0c6d911866DBEF3C5979d9B7b40; setfeesfree(); } string public constant name = "TattooMoney"; string public constant symbol = "TAT2"; uint8 public constant decimals = 18; uint256 private constant INITIAL_SUPPLY = 1_000_000_000 * (10**decimals); uint256 private constant maxFee = 10; uint256 private _totalSupply = INITIAL_SUPPLY; uint256 private FeeTotalCollected; uint256 private FeeTotalCollectedBurned; address private constant ZERO = address(0); mapping(address => uint256) private balances; mapping(address => mapping(address => uint256)) public override allowance; mapping(address => bool) public isFeeFreeSender; mapping(address => bool) public isFeeFreeRecipient; mapping(address => bool) public frozenAccount; uint256 public totalFee = 2; // Total procent fee deductet from transaction uint256 public burnFees = 40; // fee taken and burned uint256 public charityFees = 20; // fee taken and added to the charity address public charityaddress = 0xA48E5C39c9AF0f3B1A948a63F44d63AB777CB684; uint256 public rewardsFees = 20; // fee taken and added to rewards address public rewardsaddress = 0x2794F6a795823EDebC41D1799c0829EcD36821d2; uint256 public systemFees = 0; // fee taken and added to system address public systemaddress = 0x705E0d5120511d823b813b9e24e5E34a58616C3A; uint256 public stakingFees = 20; // fee taken and added to staking pool address public stakingaddress = 0xEDC46D5dDb981b7Da1A743b2739e69e44c4FBCE7; uint256 public minTotalSupply =0; // min amount of tokens total supply /** * @dev Update charity address * @param _charityaddress new charity address */ function updateCharityAddress( address _charityaddress ) external onlyDAO { charityaddress = _charityaddress; emit updateedCharityAddress( charityaddress ); } /** * @dev Update rewards address * @param _rewardsaddress new charity address */ function updateRewardsAddress( address _rewardsaddress ) external onlyDAO { rewardsaddress = _rewardsaddress; emit updateedRewardsAddress( rewardsaddress ); } /** * @dev Update rewards address * @param _systemaddress new charity address */ function updateSystemAddress( address _systemaddress ) external onlyDAO { systemaddress = _systemaddress; emit updateedSystemAddress( systemaddress ); } /** * @dev Update staking address * @param _stakingaddress new charity address */ function updateStakingAddress( address _stakingaddress ) external onlyDAO { stakingaddress = _stakingaddress; emit updateedStakingAddress( stakingaddress ); } /** * @dev Updates fees * @param _totalFee total taken fee * @param _burnFees burn fees * @param _charityFees liquidity pool fees * @param _rewardsFees rewards fees */ function updateFees( uint256 _totalFee, uint256 _burnFees, uint256 _charityFees, uint256 _rewardsFees, uint256 _systemFees, uint256 _stakingFees ) external onlyDAO { require( _totalFee <= maxFee, "VERIFY FEE: TOO BIG FEE" ); require( _verifyFees(_burnFees, _charityFees, _rewardsFees, _systemFees, _stakingFees), "VERIFY FEE: SUM DO NOT MATCH"); totalFee = _totalFee; burnFees = _burnFees; charityFees = _charityFees; rewardsFees = _rewardsFees; systemFees = _systemFees; stakingFees = _stakingFees; emit FeesUpdated( totalFee, burnFees, charityFees, rewardsFees, systemFees, stakingFees ); } /** * @dev verify fees * @param _burnFees liquidity pool fees * @param _charityFees charity fees * @param _rewardsFees rewards fees * @param _systemFees system fees * @param _stakingFees staking fees */ function _verifyFees( uint256 _burnFees, uint256 _charityFees, uint256 _rewardsFees, uint256 _systemFees, uint256 _stakingFees) private pure returns (bool){ uint256 _totalFees = _burnFees + _charityFees + _rewardsFees + _systemFees + _stakingFees; if(_totalFees == 100){ return true; } else { return false; } } /** * @dev Emitted when dao is updated * @param dao dao address */ event DAOUpdated( address dao ); // ERC20 totalSupply function totalSupply() external view override returns (uint256) { return _totalSupply - balances[ZERO]; } /// Total fees collected function FeesCollected() external view returns (uint256) { return FeeTotalCollected; } /// Total fees collected burned function FeesCollectedBurned() external view returns (uint256) { return FeeTotalCollectedBurned; } // ERC20 balanceOf function balanceOf(address account) external view override returns (uint256) { return balances[account]; } // ERC20 transfer function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } // ERC20 approve function approve(address spender, uint256 amount) external override returns (bool) { _approve(msg.sender, spender, amount); return true; } // ERC20 transferFrom function transferFrom( address sender, address recipient, uint256 amount ) external override returns (bool) { uint256 amt = allowance[sender][msg.sender]; require(amt >= amount, "ERC20: transfer amount exceeds allowance"); // reduce only if not permament allowance (uniswap etc) allowance[sender][msg.sender] -= amount; _transfer(sender, recipient, amount); return true; } // ERC20 increaseAllowance function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _approve( msg.sender, spender, allowance[msg.sender][spender] + addedValue ); return true; } // ERC20 decreaseAllowance function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { require( allowance[msg.sender][spender] >= subtractedValue, "ERC20: decreased allowance below zero" ); _approve( msg.sender, spender, allowance[msg.sender][spender] - subtractedValue ); return true; } // ERC20 burn function burn(uint256 amount) external { require(msg.sender != ZERO, "ERC20: burn from the zero address"); _burn(msg.sender, amount); } // ERC20 burnFrom function burnFrom(address account, uint256 amount) external { require(account != ZERO, "ERC20: burn from the zero address"); require(allowance[account][msg.sender] >= amount, "ERC20: burn amount exceeds allowance"); allowance[account][msg.sender] -= amount; _burn(account, amount); } function _calcTransferFees( uint256 amount ) private view returns ( uint256 _FeesToTake, uint256 _toburn, uint256 _tocharity, uint256 _toreward, uint256 _tosystem, uint256 _tostaking ) { _FeesToTake = amount * totalFee / 100; if((_totalSupply - balances[ZERO]) > minTotalSupply){ _toburn = _FeesToTake * burnFees / 100; } else { _toburn = 0; } _tocharity = _FeesToTake * charityFees / 100; _toreward = _FeesToTake * rewardsFees / 100; _tosystem = _FeesToTake * systemFees / 100; _tostaking = _FeesToTake * stakingFees / 100; _FeesToTake = _toburn + _tocharity + _toreward + _tosystem + _tostaking; } /** Internal approve function, emit Approval event @param _owner approving address @param spender delegated spender @param amount amount of tokens */ function _approve( address _owner, address spender, uint256 amount ) private { require(_owner != ZERO, "ERC20: approve from the zero address"); require(spender != ZERO, "ERC20: approve to the zero address"); allowance[_owner][spender] = amount; emit Approval(_owner, spender, amount); } /** Internal transfer function, calling feeFree if needed @param sender sender address @param recipient destination address @param Amount transfer amount */ function _transfer( address sender, address recipient, uint256 Amount ) private { require(sender != ZERO, "ERC20: transfer from the zero address"); require(recipient != ZERO, "ERC20: transfer to the zero address"); require(!frozenAccount[sender], "DAO: transfer from this address frozen"); require(!frozenAccount[recipient], "DAO: transfer to this address frozen"); if (Amount > 0) { if (isFeeFreeSender[sender]){ _feeFreeTransfer(sender, recipient, Amount); } else if(isFeeFreeRecipient[recipient]){ _feeFreeTransfer(sender, recipient, Amount); } else { ( uint256 _FeesToTake, uint256 _toburn, uint256 _tocharity, uint256 _toreward, uint256 _tosystem, uint256 _tostaking ) = _calcTransferFees( Amount ); uint256 _totransfer = Amount - _FeesToTake; uint256 _takefromsender = Amount - _toburn; FeeTotalCollected += _FeesToTake; balances[sender] -= _takefromsender; balances[recipient] += _totransfer; if(_toburn>0){ _burn(sender, _toburn); FeeTotalCollectedBurned += _toburn; emit Transfer(sender, ZERO, _toburn); } if(_tocharity>0){ balances[charityaddress] += _tocharity; emit Transfer(sender, charityaddress, _tocharity); } if(_toreward>0){ balances[rewardsaddress] += _toreward; emit Transfer(sender, rewardsaddress, _toreward); } if(_tosystem>0){ balances[systemaddress] += _tosystem; emit Transfer(sender, systemaddress, _tosystem); } if(_tostaking>0){ balances[stakingaddress] += _tostaking; emit Transfer(sender, stakingaddress, _tostaking); } emit Transfer(sender, recipient, _totransfer); } } else emit Transfer(sender, recipient, 0); } /** Function provide fee-free transfer for selected addresses @param sender sender address @param recipient destination address @param Amount transfer amount */ function _feeFreeTransfer( address sender, address recipient, uint256 Amount ) private { balances[sender] -= Amount; balances[recipient] += Amount; emit Transfer(sender, recipient, Amount); } /// internal burn function function _burn(address account, uint256 Amount) private { require( balances[account] >= Amount, "ERC20: burn amount exceeds balance" ); balances[account] -= Amount; _totalSupply -= Amount; } /** * @dev Freez Account * @param _address adress to feez/unfreez * @param _freeze set state */ function freezeAccount(address _address, bool _freeze) public onlyDAO { frozenAccount[_address] = _freeze; } /** * @dev Update charity address * @param _minTotalSupply new charity address */ function updateminTotalSupply( uint256 _minTotalSupply ) external onlyDAO { minTotalSupply = _minTotalSupply; emit updatedminTotalSupply( minTotalSupply ); } function setfeesfree() private{ isFeeFreeSender[owner] = true; isFeeFreeSender[dao] = true; isFeeFreeSender[charityaddress] = true; isFeeFreeSender[rewardsaddress] = true; isFeeFreeSender[systemaddress] = true; isFeeFreeSender[stakingaddress] = true; isFeeFreeRecipient[charityaddress] = true; } /** * @dev Emitted when fees are updated * @param totalFee burn fees * @param burnFees liquidity pool fees * @param charityFees charity fees * @param rewardsFees rewards fees * @param systemFees system fees * @param stakingFees staking fees */ event FeesUpdated( uint256 totalFee, uint256 burnFees, uint256 charityFees, uint256 rewardsFees, uint256 systemFees, uint256 stakingFees ); /** * @dev Emitted when staking is updated * @param stakingaddress burn fees */ event updateedStakingAddress( address stakingaddress ); /** * @dev Emitted when system is updated * @param systemaddress burn fees */ event updateedSystemAddress( address systemaddress ); /** * @dev Emitted when rewards is updated * @param rewardsaddress burn fees */ event updateedRewardsAddress( address rewardsaddress ); /** * @dev Emitted when charity is updated * @param charityaddress burn fees */ event updateedCharityAddress( address charityaddress ); /** * @dev Emitted when minTotalSupply is updated * @param minTotalSupply burn fees */ event updatedminTotalSupply( uint256 minTotalSupply ); // // Hard Ride // /** Add address that will not pay transfer fees @param user address to mark as fee-free */ function addFeeFree(address user) external onlyDAO { isFeeFreeSender[user] = true; } /** Remove address form privileged list @param user user to remove */ function removeFeeFree(address user) external onlyDAO { isFeeFreeSender[user] = false; } /** Add address that will recive tokens without fee @param user address to mark as fee-free */ function addFeeFreeRecipient(address user) external onlyDAO { isFeeFreeRecipient[user] = true; } /** Remove address form privileged list @param user user to remove */ function removeFeeFreeRecipient(address user) external onlyDAO { isFeeFreeRecipient[user] = false; } /** Take ETH accidentally send to contract */ function withdrawEth() external onlyOwner { payable(owner).transfer(address(this).balance); } /** Take any ERC20 sent to contract @param token token address */ function withdrawErc20(address token) external onlyOwner { uint256 balance = IERC20(token).balanceOf(address(this)); require(balance > 0, "Nothing to withdraw"); // use broken IERC20 INterfacesNoR(token).transfer(owner, balance); } } //by Patrick
* @dev verify fees @param _burnFees liquidity pool fees @param _charityFees charity fees @param _rewardsFees rewards fees @param _systemFees system fees @param _stakingFees staking fees/
function _verifyFees( uint256 _burnFees, uint256 _charityFees, uint256 _rewardsFees, uint256 _systemFees, uint256 _stakingFees) private pure returns (bool){ uint256 _totalFees = _burnFees + _charityFees + _rewardsFees + _systemFees + _stakingFees; if(_totalFees == 100){ return true; return false; } } address dao );
426,495
[ 1, 8705, 1656, 281, 225, 389, 70, 321, 2954, 281, 4501, 372, 24237, 2845, 1656, 281, 225, 389, 3001, 560, 2954, 281, 1149, 560, 1656, 281, 225, 389, 266, 6397, 2954, 281, 283, 6397, 1656, 281, 225, 389, 4299, 2954, 281, 2619, 1656, 281, 225, 389, 334, 6159, 2954, 281, 384, 6159, 1656, 281, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 8705, 2954, 281, 12, 2254, 5034, 389, 70, 321, 2954, 281, 16, 2254, 5034, 389, 3001, 560, 2954, 281, 16, 2254, 5034, 389, 266, 6397, 2954, 281, 16, 2254, 5034, 389, 4299, 2954, 281, 16, 2254, 5034, 389, 334, 6159, 2954, 281, 13, 3238, 16618, 1135, 261, 6430, 15329, 203, 3639, 2254, 5034, 389, 4963, 2954, 281, 273, 389, 70, 321, 2954, 281, 397, 389, 3001, 560, 2954, 281, 397, 389, 266, 6397, 2954, 281, 397, 389, 4299, 2954, 281, 397, 389, 334, 6159, 2954, 281, 31, 203, 3639, 309, 24899, 4963, 2954, 281, 422, 2130, 15329, 203, 5411, 327, 638, 31, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 1377, 1758, 15229, 203, 565, 11272, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity =0.8.4; import {ISwap, Types} from "./airswap/interfaces/ISwap.sol"; import {Actions, GammaTypes, IController} from "./gamma/interfaces/IController.sol"; import {OtokenInterface} from "./gamma/interfaces/OtokenInterface.sol"; import {ERC20, IERC20} from "../oz/token/ERC20/ERC20.sol"; import {SafeERC20} from "../oz/token/ERC20/utils/SafeERC20.sol"; import {Pausable} from "../oz/security/Pausable.sol"; import {ReentrancyGuard} from "../oz/security/ReentrancyGuard.sol"; //import "hardhat/console.sol"; contract VaultToken is ERC20, Pausable, ReentrancyGuard { using SafeERC20 for IERC20; error Unauthorized(); error Unauthorized_COUNTERPARTY_DID_NOT_SIGN(); error Invalid(); error MaximumFundsReached(); error RatioAlreadyDefined(); error RatioNotDefined(); error WithdrawalWindowNotActive(); error WithdrawalWindowActive(); error oTokenNotCleared(); error SettlementNotReady(); /// @notice Time in which the withdrawal window expires uint256 private withdrawalWindowExpires; /// @notice Length of time where the withdrawal window is active uint256 private constant withdrawalWindowLength = 1 days; /// @notice Amount of collateral for the address already used for collateral uint256 public collateralAmount; /// @notice Current active vault uint256 private currentVaultId; /// @notice Maximum funds uint256 public maximumAssets; /// @notice Address of the Gamma controller IController private immutable controller; /// @notice Address of the current oToken address private oToken; /// @notice Address of the exchange address private immutable AIRSWAP_EXCHANGE; /// @notice Address of the underlying asset to trade address public immutable asset; /// @notice Address of the manager (admin) address public immutable manager; /// @notice For emergency use event Deposit(uint256 assetDeposited, uint256 vaultTokensMinted); event Withdrawal(uint256 assetWithdrew, uint256 vaultTokensBurned); event WithdrawalWindowActivated(uint256 closesAfter); event CallsMinted(uint256 collateralDeposited, address indexed newOtoken, uint256 vaultId); event CallsBurned(uint256 oTokensBurned); event CallsSold(uint256 amountSold, uint256 premiumReceived); constructor( string memory _name, string memory _symbol, address _controller, address _airswap, address _asset, address _manager, uint256 _maximumAssets ) ERC20(_name, _symbol) { controller = IController(_controller); AIRSWAP_EXCHANGE = _airswap; asset = _asset; manager = _manager; maximumAssets = _maximumAssets; } modifier onlyManager { _onlyManager(); _; } modifier withdrawalWindowCheck(bool _revertIfClosed) { _withdrawalWindowCheck(_revertIfClosed); _; } /// @notice For emergency use /// @dev Stops all activities on the vault (or reactivates them) /// @param _pause true to pause the vault, false to unpause the vault function emergency(bool _pause) public onlyManager { if(_pause) super._pause(); else super._unpause(); } /// @notice Changes the maximum allowed deposits under management /// @dev Changes the maximumAssets to the new amount /// @param _newValue new maximumAssets value function adjustTheMaximumAssets(uint256 _newValue) public onlyManager nonReentrant() whenNotPaused() { if(_newValue < collateralAmount + IERC20(asset).balanceOf(address(this))) revert Invalid(); maximumAssets = _newValue; } /// @notice Deposit assets and receive vault tokens to represent a share /// @dev Deposits an amount of assets specified then mints vault tokens to the msg.sender /// @param _amount amount to deposit of ASSET function deposit(uint256 _amount) external nonReentrant() whenNotPaused() { if(_amount == 0) revert Invalid(); if(totalSupply() == 0) revert RatioNotDefined(); if(collateralAmount + IERC20(asset).balanceOf(address(this)) + _amount > maximumAssets) revert MaximumFundsReached(); uint256 vaultMint = totalSupply() * _amount / (IERC20(asset).balanceOf(address(this)) + collateralAmount); /* console.log(normalizedAmount); console.log(normalizedAssetBalance); console.log(totalSupply()); console.log(totalSupply() * normalizedAmount / normalizedAssetBalance); console.log(vaultMint); */ if(vaultMint == 0) // Safety check for rounding errors revert Invalid(); IERC20(asset).safeTransferFrom(msg.sender, address(this), _amount); _mint(msg.sender, vaultMint); emit Deposit(_amount, vaultMint); } /// @notice Redeem vault tokens for assets /// @dev Burns vault tokens in redemption for the assets to msg.sender /// @param _amount amount of VAULT TOKENS to burn function withdraw(uint256 _amount) external withdrawalWindowCheck(true) nonReentrant() whenNotPaused() { if(_amount == 0) revert Invalid(); uint256 assetAmount = _amount * IERC20(asset).balanceOf(address(this)) / totalSupply(); IERC20(asset).safeTransfer(msg.sender, assetAmount); // Vault Token Amount to Burn * Balance of Vault for Asset / Total Vault Token Supply _burn(address(msg.sender), _amount); emit Withdrawal(assetAmount, _amount); } /// @notice Sets the ratio between the asset and vault token /// @dev Allows anyone to set the ratio 1:1 if total supply is 0 for whatever reason /// @param _amount amount of the VAULT TOKEN to mint function initializeRatio(uint256 _amount) external nonReentrant() whenNotPaused() { if(totalSupply() > 0) revert RatioAlreadyDefined(); uint256 normalizedAssetAmount = _normalize(_amount, decimals(), ERC20(asset).decimals()); if(normalizedAssetAmount == 0) // Safety check for rounding errors revert Invalid(); _mint(address(msg.sender), _amount); IERC20(asset).safeTransferFrom(msg.sender, address(this), normalizedAssetAmount); withdrawalWindowExpires = block.timestamp + withdrawalWindowLength; // This WILL reset the withdrawal window if the supply was zero emit WithdrawalWindowActivated(withdrawalWindowExpires); } /// @notice Write calls for an _amount of asset for the specified oToken /// @dev Allows the manager to write calls for an x /// @param _amount amount of the asset to deposit as collateral /// @param _oToken address of the oToken /// @param _marginPool address of the margin pool function writeCalls(uint256 _amount, address _oToken, address _marginPool) external onlyManager nonReentrant() whenNotPaused() { if(!_withdrawalWindowCheck(false)) revert WithdrawalWindowActive(); if(_amount == 0 || _oToken == address(0) || _marginPool == address(0)) revert Invalid(); if(_oToken != oToken && oToken != address(0)) revert oTokenNotCleared(); Actions.ActionArgs[] memory actions; GammaTypes.Vault memory vault; // Check if the vault is even open and open if no vault is open vault = controller.getVault(address(this), currentVaultId); if( vault.shortOtokens.length == 0 && vault.collateralAssets.length == 0 ) { actions = new Actions.ActionArgs[](3); currentVaultId = controller.getAccountVaultCounter(address(this)) + 1; actions[0] = Actions.ActionArgs( Actions.ActionType.OpenVault, address(this), address(this), address(0), currentVaultId, 0, 0, "" ); } else { actions = new Actions.ActionArgs[](2); } // Deposit _amount of asset to the vault actions[actions.length - 2] = Actions.ActionArgs( Actions.ActionType.DepositCollateral, address(this), address(this), asset, currentVaultId, _amount, 0, "" ); // Write calls actions[actions.length - 1] = Actions.ActionArgs( Actions.ActionType.MintShortOption, address(this), address(this), _oToken, currentVaultId, _normalize(_amount, ERC20(asset).decimals(), 8), 0, "" ); // Approve the tokens to be moved IERC20(asset).approve(_marginPool, _amount); // Submit the operations to the controller contract controller.operate(actions); collateralAmount += _amount; if(oToken != _oToken) oToken = _oToken; emit CallsMinted(_amount, oToken, controller.getAccountVaultCounter(address(this))); } /// @notice Burns away the oTokens to redeem the asset collateral /// @dev Operation to burn away the oTOkens in redemption of the asset collateral /// @param _amount Amount of calls to burn function burnCalls(uint256 _amount) external onlyManager nonReentrant() whenNotPaused() { if(!_withdrawalWindowCheck(false)) revert WithdrawalWindowActive(); if(_amount > IERC20(oToken).balanceOf(address(this))) revert Invalid(); Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](2); uint256 normalizedAmount = _normalize(_amount, 8, 18); actions[0] = Actions.ActionArgs( Actions.ActionType.BurnShortOption, address(this), address(this), oToken, currentVaultId, _amount, 0, "" ); actions[1] = Actions.ActionArgs( Actions.ActionType.WithdrawCollateral, address(this), address(this), asset, currentVaultId, normalizedAmount, 0, "" ); controller.operate(actions); collateralAmount -= normalizedAmount; if(collateralAmount == 0 && IERC20(oToken).balanceOf(address(this)) == 0) { // Withdrawal window reopens withdrawalWindowExpires = block.timestamp + withdrawalWindowLength; oToken = address(0); emit WithdrawalWindowActivated(withdrawalWindowExpires); } emit CallsBurned(_amount); } /// @notice Operation to sell calls to an EXISTING order on AirSwap /// @dev Sells calls via AirSwap that exists by the counterparty /// @param _amount Amount of calls to sell to the exchange /// @param _premiumAmount Token amount to receive of the premium /// @param _otherParty Address of the counterparty /// @param _nonce Other party's AirSwap nonce function sellCalls(uint256 _amount, uint256 _premiumAmount, address _otherParty, uint256 _nonce) external onlyManager nonReentrant() whenNotPaused() { if(!_withdrawalWindowCheck(false)) revert WithdrawalWindowActive(); if(_amount > IERC20(oToken).balanceOf(address(this)) || oToken == address(0)) revert Invalid(); if(!ISwap(AIRSWAP_EXCHANGE).signerAuthorizations(_otherParty, address(this))) revert Unauthorized_COUNTERPARTY_DID_NOT_SIGN(); // Prepare the AirSwap order Types.Order memory sellOrder; Types.Party memory signer; Types.Party memory sender; // Prepare the signer Types.Party portion (counterparty) of the order signer.kind = 0x36372b07; // ERC20_INTERFACE_ID signer.wallet = _otherParty; signer.token = asset; signer.amount = _premiumAmount; // Prepare the sender Types.Party portion (this contract) of the order sender.kind = 0x36372b07; // ERC20_INTERFACE_ID sender.token = oToken; sender.amount = _amount; // Define Types.Order sellOrder.nonce = _nonce; sellOrder.expiry = block.timestamp + 1 days; sellOrder.signer = signer; sellOrder.sender = sender; // Approve IERC20(oToken).approve(AIRSWAP_EXCHANGE, _amount); ISwap(AIRSWAP_EXCHANGE).swap(sellOrder); emit CallsSold(_amount, _premiumAmount); } /// @notice Operation to settle the vault /// @dev Settles the currently open vault and opens the withdrawal window function settleVault() external onlyManager nonReentrant() whenNotPaused() { if(!_withdrawalWindowCheck(false)) revert WithdrawalWindowActive(); // Check if ready to settle otherwise revert if(OtokenInterface(oToken).expiryTimestamp() > block.timestamp) revert SettlementNotReady(); // Settle the vault if ready Actions.ActionArgs[] memory action = new Actions.ActionArgs[](1); action[0] = Actions.ActionArgs( Actions.ActionType.SettleVault, address(this), address(this), address(0), currentVaultId, IERC20(oToken).balanceOf(address(this)), 0, "" ); controller.operate(action); // Withdrawal window opens withdrawalWindowExpires = block.timestamp + withdrawalWindowLength; collateralAmount = 0; oToken = address(0); emit WithdrawalWindowActivated(withdrawalWindowExpires); } function _onlyManager() internal view { if(msg.sender != manager) revert Unauthorized(); } function _normalize( uint256 _valueToNormalize, uint256 _valueDecimal, uint256 _normalDecimals ) internal pure returns (uint256) { int256 decimalDiff = int256(_valueDecimal) - int256(_normalDecimals); if(decimalDiff > 0) { return _valueToNormalize / (10**uint256(decimalDiff)); } else if(decimalDiff < 0) { return _valueToNormalize * 10**uint256(-decimalDiff); } else { return _valueToNormalize; } } function _withdrawalWindowCheck(bool _revertIfClosed) internal view returns(bool isActive) { if(block.timestamp > withdrawalWindowExpires && _revertIfClosed) revert WithdrawalWindowNotActive(); return block.timestamp > withdrawalWindowExpires; } } // SPDX-License-Identifier: Apache-2.0 // SOURCE: https://github.com/airswap/airswap-protocols/blob/master/source/swap/contracts/interfaces/ISwap.sol pragma solidity =0.8.4; pragma experimental ABIEncoderV2; import "../types/Types.sol"; import "../transfers/TransferHandlerRegistry.sol"; interface ISwap { event Swap( uint256 indexed nonce, uint256 timestamp, address indexed signerWallet, uint256 signerAmount, uint256 signerId, address signerToken, address indexed senderWallet, uint256 senderAmount, uint256 senderId, address senderToken, address affiliateWallet, uint256 affiliateAmount, uint256 affiliateId, address affiliateToken ); event Cancel(uint256 indexed nonce, address indexed signerWallet); event CancelUpTo(uint256 indexed nonce, address indexed signerWallet); event AuthorizeSender( address indexed authorizerAddress, address indexed authorizedSender ); event AuthorizeSigner( address indexed authorizerAddress, address indexed authorizedSigner ); event RevokeSender( address indexed authorizerAddress, address indexed revokedSender ); event RevokeSigner( address indexed authorizerAddress, address indexed revokedSigner ); /** * @notice Atomic Token Swap * @param order Types.Order */ function swap(Types.Order calldata order) external; /** * @notice Cancel one or more open orders by nonce * @param nonces uint256[] */ function cancel(uint256[] calldata nonces) external; /** * @notice Cancels all orders below a nonce value * @dev These orders can be made active by reducing the minimum nonce * @param minimumNonce uint256 */ function cancelUpTo(uint256 minimumNonce) external; /** * @notice Authorize a delegated sender * @param authorizedSender address */ function authorizeSender(address authorizedSender) external; /** * @notice Authorize a delegated signer * @param authorizedSigner address */ function authorizeSigner(address authorizedSigner) external; /** * @notice Revoke an authorization * @param authorizedSender address */ function revokeSender(address authorizedSender) external; /** * @notice Revoke an authorization * @param authorizedSigner address */ function revokeSigner(address authorizedSigner) external; function senderAuthorizations(address, address) external view returns (bool); function signerAuthorizations(address, address) external view returns (bool); function signerNonceStatus(address, uint256) external view returns (bytes1); function signerMinimumNonce(address) external view returns (uint256); function registry() external view returns (TransferHandlerRegistry); } // SPDX-License-Identifier: UNLICENSED pragma solidity =0.8.4; library GammaTypes { // vault is a struct of 6 arrays that describe a position a user has, a user can have multiple vaults. struct Vault { // addresses of oTokens a user has shorted (i.e. written) against this vault address[] shortOtokens; // addresses of oTokens a user has bought and deposited in this vault // user can be long oTokens without opening a vault (e.g. by buying on a DEX) // generally, long oTokens will be 'deposited' in vaults to act as collateral in order to write oTokens against (i.e. in spreads) address[] longOtokens; // addresses of other ERC-20s a user has deposited as collateral in this vault address[] collateralAssets; // quantity of oTokens minted/written for each oToken address in shortOtokens uint256[] shortAmounts; // quantity of oTokens owned and held in the vault for each oToken address in longOtokens uint256[] longAmounts; // quantity of ERC-20 deposited as collateral in the vault for each ERC-20 address in collateralAssets uint256[] collateralAmounts; } } library Actions { // possible actions that can be performed enum ActionType { OpenVault, MintShortOption, BurnShortOption, DepositLongOption, WithdrawLongOption, DepositCollateral, WithdrawCollateral, SettleVault, Redeem, Call, Liquidate } struct ActionArgs { // type of action that is being performed on the system ActionType actionType; // address of the account owner address owner; // address which we move assets from or to (depending on the action type) address secondAddress; // asset that is to be transfered address asset; // index of the vault that is to be modified (if any) uint256 vaultId; // amount of asset that is to be transfered uint256 amount; // each vault can hold multiple short / long / collateral assets but we are restricting the scope to only 1 of each in this version // in future versions this would be the index of the short / long / collateral asset that needs to be modified uint256 index; // any other data that needs to be passed in for arbitrary function calls bytes data; } struct RedeemArgs { // address to which we pay out the oToken proceeds address receiver; // oToken that is to be redeemed address otoken; // amount of oTokens that is to be redeemed uint256 amount; } } interface IController { function getVault(address _owner, uint256 _vaultId) external view returns(GammaTypes.Vault memory); function getAccountVaultCounter(address _accountOwner) external view returns(uint256); function operate(Actions.ActionArgs[] memory _actions) external; } // SPDX-License-Identifier: UNLICENSED // SOURCE: https://github.com/opynfinance/GammaProtocol/blob/2fce44f04300aa5b79187269728aae3a736b4684/contracts/interfaces/OtokenInterface.sol pragma solidity =0.8.4; interface OtokenInterface { function addressBook() external view returns (address); function underlyingAsset() external view returns (address); function strikeAsset() external view returns (address); function collateralAsset() external view returns (address); function strikePrice() external view returns (uint256); function expiryTimestamp() external view returns (uint256); function isPut() external view returns (bool); function init( address _addressBook, address _underlyingAsset, address _strikeAsset, address _collateralAsset, uint256 _strikePrice, uint256 _expiry, bool _isPut ) external; function getOtokenDetails() external view returns ( address, address, address, uint256, uint256, bool ); function mintOtoken(address account, uint256 amount) external; function burnOtoken(address account, uint256 amount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overloaded; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/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 () { _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.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: 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: Apache-2.0 // SOURCE: https://github.com/airswap/airswap-protocols/blob/master/source/types/contracts/Types.sol pragma solidity =0.8.4; pragma experimental ABIEncoderV2; /** * @title Types: Library of Swap Protocol Types and Hashes */ library Types { struct Order { uint256 nonce; // Unique per order and should be sequential uint256 expiry; // Expiry in seconds since 1 January 1970 Party signer; // Party to the trade that sets terms Party sender; // Party to the trade that accepts terms Party affiliate; // Party compensated for facilitating (optional) Signature signature; // Signature of the order } struct Party { bytes4 kind; // Interface ID of the token address wallet; // Wallet address of the party address token; // Contract address of the token uint256 amount; // Amount for ERC-20 or ERC-1155 uint256 id; // ID for ERC-721 or ERC-1155 } struct Signature { address signatory; // Address of the wallet used to sign address validator; // Address of the intended swap contract bytes1 version; // EIP-191 signature version uint8 v; // `v` value of an ECDSA signature bytes32 r; // `r` value of an ECDSA signature bytes32 s; // `s` value of an ECDSA signature } bytes internal constant EIP191_HEADER = "\x19\x01"; bytes32 internal constant DOMAIN_TYPEHASH = keccak256( abi.encodePacked( "EIP712Domain(", "string name,", "string version,", "address verifyingContract", ")" ) ); bytes32 internal constant ORDER_TYPEHASH = keccak256( abi.encodePacked( "Order(", "uint256 nonce,", "uint256 expiry,", "Party signer,", "Party sender,", "Party affiliate", ")", "Party(", "bytes4 kind,", "address wallet,", "address token,", "uint256 amount,", "uint256 id", ")" ) ); bytes32 internal constant PARTY_TYPEHASH = keccak256( abi.encodePacked( "Party(", "bytes4 kind,", "address wallet,", "address token,", "uint256 amount,", "uint256 id", ")" ) ); /** * @notice Hash an order into bytes32 * @dev EIP-191 header and domain separator included * @param order Order The order to be hashed * @param domainSeparator bytes32 * @return bytes32 A keccak256 abi.encodePacked value */ function hashOrder(Order calldata order, bytes32 domainSeparator) external pure returns (bytes32) { return keccak256( abi.encodePacked( EIP191_HEADER, domainSeparator, keccak256( abi.encode( ORDER_TYPEHASH, order.nonce, order.expiry, keccak256( abi.encode( PARTY_TYPEHASH, order.signer.kind, order.signer.wallet, order.signer.token, order.signer.amount, order.signer.id ) ), keccak256( abi.encode( PARTY_TYPEHASH, order.sender.kind, order.sender.wallet, order.sender.token, order.sender.amount, order.sender.id ) ), keccak256( abi.encode( PARTY_TYPEHASH, order.affiliate.kind, order.affiliate.wallet, order.affiliate.token, order.affiliate.amount, order.affiliate.id ) ) ) ) ) ); } /** * @notice Hash domain parameters into bytes32 * @dev Used for signature validation (EIP-712) * @param name bytes * @param version bytes * @param verifyingContract address * @return bytes32 returns a keccak256 abi.encodePacked value */ function hashDomain( bytes calldata name, bytes calldata version, address verifyingContract ) external pure returns (bytes32) { return keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(name), keccak256(version), verifyingContract ) ); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity =0.8.4; import "../interfaces/ITransferHandler.sol"; import "../../../oz/access/Ownable.sol"; /** * @title TransferHandlerRegistry: holds registry of contract to * facilitate token transfers */ contract TransferHandlerRegistry is Ownable { // Mapping of bytes4 to contract interface type mapping(bytes4 => ITransferHandler) public transferHandlers; /** * @notice Contract Events */ event AddTransferHandler(bytes4 kind, address contractAddress); /** * @notice Adds handler to mapping * @param kind bytes4 Key value that defines a token type * @param transferHandler ITransferHandler */ function addTransferHandler(bytes4 kind, ITransferHandler transferHandler) external onlyOwner { require( address(transferHandlers[kind]) == address(0), "HANDLER_EXISTS_FOR_KIND" ); transferHandlers[kind] = transferHandler; emit AddTransferHandler(kind, address(transferHandler)); } } // SPDX-License-Identifier: Apache-2.0 // SOURCE: https://github.com/airswap/airswap-protocols/blob/master/source/transfers/contracts/interfaces/ITransferHandler.sol pragma solidity =0.8.4; /** * @title ITransferHandler: interface for token transfers */ interface ITransferHandler { /** * @notice Function to wrap token transfer for different token types * @param from address Wallet address to transfer from * @param to address Wallet address to transfer to * @param amount uint256 Amount for ERC-20 * @param id token ID for ERC-721 * @param token address Contract address of token * @return bool on success of the token transfer */ function transferTokens( address from, address to, uint256 amount, uint256 id, address token ) external returns (bool); } // SPDX-License-Identifier: MIT // SOURCE: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.0/contracts/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 () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
@notice Redeem vault tokens for assets @dev Burns vault tokens in redemption for the assets to msg.sender @param _amount amount of VAULT TOKENS to burn
function withdraw(uint256 _amount) external withdrawalWindowCheck(true) nonReentrant() whenNotPaused() { if(_amount == 0) revert Invalid(); uint256 assetAmount = _amount * IERC20(asset).balanceOf(address(this)) / totalSupply(); _burn(address(msg.sender), _amount); emit Withdrawal(assetAmount, _amount); }
10,024,427
[ 1, 426, 24903, 9229, 2430, 364, 7176, 225, 605, 321, 87, 9229, 2430, 316, 283, 19117, 375, 364, 326, 7176, 358, 1234, 18, 15330, 225, 389, 8949, 3844, 434, 776, 37, 2274, 14275, 55, 358, 18305, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 12, 11890, 5034, 389, 8949, 13, 3903, 598, 9446, 287, 3829, 1564, 12, 3767, 13, 1661, 426, 8230, 970, 1435, 1347, 1248, 28590, 1435, 288, 203, 3639, 309, 24899, 8949, 422, 374, 13, 203, 5411, 15226, 1962, 5621, 203, 203, 3639, 2254, 5034, 3310, 6275, 273, 389, 8949, 380, 467, 654, 39, 3462, 12, 9406, 2934, 12296, 951, 12, 2867, 12, 2211, 3719, 342, 2078, 3088, 1283, 5621, 203, 203, 3639, 389, 70, 321, 12, 2867, 12, 3576, 18, 15330, 3631, 389, 8949, 1769, 203, 203, 3639, 3626, 3423, 9446, 287, 12, 9406, 6275, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.17; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {TBTCDepositToken} from "./TBTCDepositToken.sol"; import {FeeRebateToken} from "./FeeRebateToken.sol"; import {TBTCToken} from "./TBTCToken.sol"; import {TBTCConstants} from "./TBTCConstants.sol"; import "../deposit/Deposit.sol"; import "./TBTCSystemAuthority.sol"; /// @title Vending Machine /// @notice The Vending Machine swaps TDTs (`TBTCDepositToken`) /// to TBTC (`TBTCToken`) and vice versa. /// @dev The Vending Machine should have exclusive TBTC and FRT (`FeeRebateToken`) minting /// privileges. contract VendingMachine is TBTCSystemAuthority{ using SafeMath for uint256; TBTCToken tbtcToken; TBTCDepositToken tbtcDepositToken; FeeRebateToken feeRebateToken; uint256 createdAt; constructor(address _systemAddress) TBTCSystemAuthority(_systemAddress) public { createdAt = block.timestamp; } /// @notice Set external contracts needed by the Vending Machine. /// @dev Addresses are used to update the local contract instance. /// @param _tbtcToken TBTCToken contract. More info in `TBTCToken`. /// @param _tbtcDepositToken TBTCDepositToken (TDT) contract. More info in `TBTCDepositToken`. /// @param _feeRebateToken FeeRebateToken (FRT) contract. More info in `FeeRebateToken`. function setExternalAddresses( TBTCToken _tbtcToken, TBTCDepositToken _tbtcDepositToken, FeeRebateToken _feeRebateToken ) external onlyTbtcSystem { tbtcToken = _tbtcToken; tbtcDepositToken = _tbtcDepositToken; feeRebateToken = _feeRebateToken; } /// @notice Burns TBTC and transfers the tBTC Deposit Token to the caller /// as long as it is qualified. /// @dev We burn the lotSize of the Deposit in order to maintain /// the TBTC supply peg in the Vending Machine. VendingMachine must be approved /// by the caller to burn the required amount. /// @param _tdtId ID of tBTC Deposit Token to buy. function tbtcToTdt(uint256 _tdtId) external { require(tbtcDepositToken.exists(_tdtId), "tBTC Deposit Token does not exist"); require(isQualified(address(_tdtId)), "Deposit must be qualified"); uint256 depositValue = Deposit(address(uint160(_tdtId))).lotSizeTbtc(); require(tbtcToken.balanceOf(msg.sender) >= depositValue, "Not enough TBTC for TDT exchange"); tbtcToken.burnFrom(msg.sender, depositValue); // TODO do we need the owner check below? transferFrom can be approved for a user, which might be an interesting use case. require(tbtcDepositToken.ownerOf(_tdtId) == address(this), "Deposit is locked"); tbtcDepositToken.transferFrom(address(this), msg.sender, _tdtId); } /// @notice Transfer the tBTC Deposit Token and mint TBTC. /// @dev Transfers TDT from caller to vending machine, and mints TBTC to caller. /// Vending Machine must be approved to transfer TDT by the caller. /// @param _tdtId ID of tBTC Deposit Token to sell. function tdtToTbtc(uint256 _tdtId) public { require(tbtcDepositToken.exists(_tdtId), "tBTC Deposit Token does not exist"); require(isQualified(address(_tdtId)), "Deposit must be qualified"); tbtcDepositToken.transferFrom(msg.sender, address(this), _tdtId); Deposit deposit = Deposit(address(uint160(_tdtId))); uint256 signerFee = deposit.signerFeeTbtc(); uint256 depositValue = deposit.lotSizeTbtc(); require(canMint(depositValue), "Can't mint more than the max supply cap"); // If the backing Deposit does not have a signer fee in escrow, mint it. if(tbtcToken.balanceOf(address(_tdtId)) < signerFee) { tbtcToken.mint(msg.sender, depositValue.sub(signerFee)); tbtcToken.mint(address(_tdtId), signerFee); } else{ tbtcToken.mint(msg.sender, depositValue); } // owner of the TDT during first TBTC mint receives the FRT if(!feeRebateToken.exists(_tdtId)){ feeRebateToken.mint(msg.sender, _tdtId); } } /// @notice Return whether an amount of TBTC can be minted according to the supply cap /// schedule /// @dev This function is also used by TBTCSystem to decide whether to allow a new deposit. /// @return True if the amount can be minted without hitting the max supply, false otherwise. function canMint(uint256 amount) public view returns (bool) { return getMintedSupply().add(amount) < getMaxSupply(); } /// @notice Determines whether a deposit is qualified for minting TBTC. /// @param _depositAddress The address of the deposit function isQualified(address payable _depositAddress) public view returns (bool) { return Deposit(_depositAddress).inActive(); } /// @notice Return the minted TBTC supply in weitoshis (BTC * 10 ** 18). function getMintedSupply() public view returns (uint256) { return tbtcToken.totalSupply(); } /// @notice Get the maximum TBTC token supply based on the age of the /// contract deployment. The supply cap starts at 2 BTC for the two /// days, 100 for the first week, 250 for the next, then 500, 750, /// 1000, 1500, 2000, 2500, and 3000... finally removing the minting /// restriction after 9 weeks and returning 21M BTC as a sanity /// check. /// @return The max supply in weitoshis (BTC * 10 ** 18). function getMaxSupply() public view returns (uint256) { uint256 age = block.timestamp - createdAt; if(age < 2 days) { return 2 * 10 ** 18; } if (age < 7 days) { return 100 * 10 ** 18; } if (age < 14 days) { return 250 * 10 ** 18; } if (age < 21 days) { return 500 * 10 ** 18; } if (age < 28 days) { return 750 * 10 ** 18; } if (age < 35 days) { return 1000 * 10 ** 18; } if (age < 42 days) { return 1500 * 10 ** 18; } if (age < 49 days) { return 2000 * 10 ** 18; } if (age < 56 days) { return 2500 * 10 ** 18; } if (age < 63 days) { return 3000 * 10 ** 18; } return 21e6 * 10 ** 18; } // WRAPPERS /// @notice Qualifies a deposit and mints TBTC. /// @dev User must allow VendingManchine to transfer TDT. function unqualifiedDepositToTbtc( address payable _depositAddress, bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, uint8 _fundingOutputIndex, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public { // not external to allow bytes memory parameters Deposit _d = Deposit(_depositAddress); _d.provideBTCFundingProof( _txVersion, _txInputVector, _txOutputVector, _txLocktime, _fundingOutputIndex, _merkleProof, _txIndexInBlock, _bitcoinHeaders ); tdtToTbtc(uint256(_depositAddress)); } /// @notice Redeems a Deposit by purchasing a TDT with TBTC for _finalRecipient, /// and using the TDT to redeem corresponding Deposit as _finalRecipient. /// This function will revert if the Deposit is not in ACTIVE state. /// @dev Vending Machine transfers TBTC allowance to Deposit. /// @param _depositAddress The address of the Deposit to redeem. /// @param _outputValueBytes The 8-byte Bitcoin transaction output size in Little Endian. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. function tbtcToBtc( address payable _depositAddress, bytes8 _outputValueBytes, bytes memory _redeemerOutputScript ) public { // not external to allow bytes memory parameters require(tbtcDepositToken.exists(uint256(_depositAddress)), "tBTC Deposit Token does not exist"); Deposit _d = Deposit(_depositAddress); tbtcToken.burnFrom(msg.sender, _d.lotSizeTbtc()); tbtcDepositToken.approve(_depositAddress, uint256(_depositAddress)); uint256 tbtcOwed = _d.getOwnerRedemptionTbtcRequirement(msg.sender); if(tbtcOwed != 0){ tbtcToken.transferFrom(msg.sender, address(this), tbtcOwed); tbtcToken.approve(_depositAddress, tbtcOwed); } _d.transferAndRequestRedemption(_outputValueBytes, _redeemerOutputScript, msg.sender); } } pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } pragma solidity 0.5.17; /** * @title Keep interface */ interface ITBTCSystem { // expected behavior: // return the price of 1 sat in wei // these are the native units of the deposit contract function fetchBitcoinPrice() external view returns (uint256); // passthrough requests for the oracle function fetchRelayCurrentDifficulty() external view returns (uint256); function fetchRelayPreviousDifficulty() external view returns (uint256); function getNewDepositFeeEstimate() external view returns (uint256); function getAllowNewDeposits() external view returns (bool); function isAllowedLotSize(uint64 _requestedLotSizeSatoshis) external view returns (bool); function requestNewKeep(uint64 _requestedLotSizeSatoshis, uint256 _maxSecuredLifetime) external payable returns (address); function getSignerFeeDivisor() external view returns (uint16); function getInitialCollateralizedPercent() external view returns (uint16); function getUndercollateralizedThresholdPercent() external view returns (uint16); function getSeverelyUndercollateralizedThresholdPercent() external view returns (uint16); } pragma solidity 0.5.17; import {DepositLiquidation} from "./DepositLiquidation.sol"; import {DepositUtils} from "./DepositUtils.sol"; import {DepositFunding} from "./DepositFunding.sol"; import {DepositRedemption} from "./DepositRedemption.sol"; import {DepositStates} from "./DepositStates.sol"; import {ITBTCSystem} from "../interfaces/ITBTCSystem.sol"; import {IERC721} from "openzeppelin-solidity/contracts/token/ERC721/IERC721.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {FeeRebateToken} from "../system/FeeRebateToken.sol"; import "../system/DepositFactoryAuthority.sol"; // solium-disable function-order // Below, a few functions must be public to allow bytes memory parameters, but // their being so triggers errors because public functions should be grouped // below external functions. Since these would be external if it were possible, // we ignore the issue. /// @title tBTC Deposit /// @notice This is the main contract for tBTC. It is the state machine that /// (through various libraries) handles bitcoin funding, bitcoin-spv /// proofs, redemption, liquidation, and fraud logic. /// @dev This contract presents a public API that exposes the following /// libraries: /// /// - `DepositFunding` /// - `DepositLiquidaton` /// - `DepositRedemption`, /// - `DepositStates` /// - `DepositUtils` /// - `OutsourceDepositLogging` /// - `TBTCConstants` /// /// Where these libraries require deposit state, this contract's state /// variable `self` is used. `self` is a struct of type /// `DepositUtils.Deposit` that contains all aspects of the deposit state /// itself. contract Deposit is DepositFactoryAuthority { using DepositRedemption for DepositUtils.Deposit; using DepositFunding for DepositUtils.Deposit; using DepositLiquidation for DepositUtils.Deposit; using DepositUtils for DepositUtils.Deposit; using DepositStates for DepositUtils.Deposit; DepositUtils.Deposit self; /// @dev Deposit should only be _constructed_ once. New deposits are created /// using the `DepositFactory.createDeposit` method, and are clones of /// the constructed deposit. The factory will set the initial values /// for a new clone using `initializeDeposit`. constructor () public { // The constructed Deposit will never be used, so the deposit factory // address can be anything. Clones are updated as per above. initialize(address(0xdeadbeef)); } /// @notice Deposits do not accept arbitrary ETH. function () external payable { require(msg.data.length == 0, "Deposit contract was called with unknown function selector."); } //----------------------------- METADATA LOOKUP ------------------------------// /// @notice Get this deposit's BTC lot size in satoshis. /// @return uint64 lot size in satoshis. function lotSizeSatoshis() external view returns (uint64){ return self.lotSizeSatoshis; } /// @notice Get this deposit's lot size in TBTC. /// @dev This is the same as lotSizeSatoshis(), but is multiplied to scale /// to 18 decimal places. /// @return uint256 lot size in TBTC precision (max 18 decimal places). function lotSizeTbtc() external view returns (uint256){ return self.lotSizeTbtc(); } /// @notice Get the signer fee for this deposit, in TBTC. /// @dev This is the one-time fee required by the signers to perform the /// tasks needed to maintain a decentralized and trustless model for /// tBTC. It is a percentage of the deposit's lot size. /// @return Fee amount in TBTC. function signerFeeTbtc() external view returns (uint256) { return self.signerFeeTbtc(); } /// @notice Get the integer representing the current state. /// @dev We implement this because contracts don't handle foreign enums /// well. See `DepositStates` for more info on states. /// @return The 0-indexed state from the DepositStates enum. function currentState() external view returns (uint256) { return uint256(self.currentState); } /// @notice Check if the Deposit is in ACTIVE state. /// @return True if state is ACTIVE, false otherwise. function inActive() external view returns (bool) { return self.inActive(); } /// @notice Get the contract address of the BondedECDSAKeep associated with /// this Deposit. /// @dev The keep contract address is saved on Deposit initialization. /// @return Address of the Keep contract. function keepAddress() external view returns (address) { return self.keepAddress; } /// @notice Retrieve the remaining term of the deposit in seconds. /// @dev The value accuracy is not guaranteed since block.timestmap can be /// lightly manipulated by miners. /// @return The remaining term of the deposit in seconds. 0 if already at /// term. function remainingTerm() external view returns(uint256){ return self.remainingTerm(); } /// @notice Get the current collateralization level for this Deposit. /// @dev This value represents the percentage of the backing BTC value the /// signers currently must hold as bond. /// @return The current collateralization level for this deposit. function collateralizationPercentage() external view returns (uint256) { return self.collateralizationPercentage(); } /// @notice Get the initial collateralization level for this Deposit. /// @dev This value represents the percentage of the backing BTC value /// the signers hold initially. It is set at creation time. /// @return The initial collateralization level for this deposit. function initialCollateralizedPercent() external view returns (uint16) { return self.initialCollateralizedPercent; } /// @notice Get the undercollateralization level for this Deposit. /// @dev This collateralization level is semi-critical. If the /// collateralization level falls below this percentage the Deposit can /// be courtesy-called by calling `notifyCourtesyCall`. This value /// represents the percentage of the backing BTC value the signers must /// hold as bond in order to not be undercollateralized. It is set at /// creation time. Note that the value for new deposits in TBTCSystem /// can be changed by governance, but the value for a particular /// deposit is static once the deposit is created. /// @return The undercollateralized level for this deposit. function undercollateralizedThresholdPercent() external view returns (uint16) { return self.undercollateralizedThresholdPercent; } /// @notice Get the severe undercollateralization level for this Deposit. /// @dev This collateralization level is critical. If the collateralization /// level falls below this percentage the Deposit can get liquidated. /// This value represents the percentage of the backing BTC value the /// signers must hold as bond in order to not be severely /// undercollateralized. It is set at creation time. Note that the /// value for new deposits in TBTCSystem can be changed by governance, /// but the value for a particular deposit is static once the deposit /// is created. /// @return The severely undercollateralized level for this deposit. function severelyUndercollateralizedThresholdPercent() external view returns (uint16) { return self.severelyUndercollateralizedThresholdPercent; } /// @notice Get the value of the funding UTXO. /// @dev This call will revert if the deposit is not in a state where the /// UTXO info should be valid. In particular, before funding proof is /// successfully submitted (i.e. in states START, /// AWAITING_SIGNER_SETUP, and AWAITING_BTC_FUNDING_PROOF), this value /// would not be valid. /// @return The value of the funding UTXO in satoshis. function utxoValue() external view returns (uint256){ require( ! self.inFunding(), "Deposit has not yet been funded and has no available funding info" ); return self.utxoValue(); } /// @notice Returns information associated with the funding UXTO. /// @dev This call will revert if the deposit is not in a state where the /// funding info should be valid. In particular, before funding proof /// is successfully submitted (i.e. in states START, /// AWAITING_SIGNER_SETUP, and AWAITING_BTC_FUNDING_PROOF), none of /// these values are set or valid. /// @return A tuple of (uxtoValueBytes, fundedAt, uxtoOutpoint). function fundingInfo() external view returns (bytes8 utxoValueBytes, uint256 fundedAt, bytes memory utxoOutpoint) { require( ! self.inFunding(), "Deposit has not yet been funded and has no available funding info" ); return (self.utxoValueBytes, self.fundedAt, self.utxoOutpoint); } /// @notice Calculates the amount of value at auction right now. /// @dev This call will revert if the deposit is not in a state where an /// auction is currently in progress. /// @return The value in wei that would be received in exchange for the /// deposit's lot size in TBTC if `purchaseSignerBondsAtAuction` /// were called at the time this function is called. function auctionValue() external view returns (uint256) { require( self.inSignerLiquidation(), "Deposit has no funds currently at auction" ); return self.auctionValue(); } /// @notice Get caller's ETH withdraw allowance. /// @dev Generally ETH is only available to withdraw after the deposit /// reaches a closed state. The amount reported is for the sender, and /// can be withdrawn using `withdrawFunds` if the deposit is in an end /// state. /// @return The withdraw allowance in wei. function withdrawableAmount() external view returns (uint256) { return self.getWithdrawableAmount(); } //------------------------------ FUNDING FLOW --------------------------------// /// @notice Notify the contract that signing group setup has timed out if /// retrieveSignerPubkey is not successfully called within the /// allotted time. /// @dev This is considered a signer fault, and the signers' bonds are used /// to make the deposit setup fee available for withdrawal by the TDT /// holder as a refund. The remainder of the signers' bonds are /// returned to the bonding pool and the signers are released from any /// further responsibilities. Reverts if the deposit is not awaiting /// signer setup or if the signing group formation timeout has not /// elapsed. function notifySignerSetupFailed() external { self.notifySignerSetupFailed(); } /// @notice Notify the contract that the ECDSA keep has generated a public /// key so the deposit contract can pull it in. /// @dev Stores the pubkey as 2 bytestrings, X and Y. Emits a /// RegisteredPubkey event with the two components. Reverts if the /// deposit is not awaiting signer setup, if the generated public key /// is unset or has incorrect length, or if the public key has a 0 /// X or Y value. function retrieveSignerPubkey() external { self.retrieveSignerPubkey(); } /// @notice Notify the contract that the funding phase of the deposit has /// timed out if `provideBTCFundingProof` is not successfully called /// within the allotted time. Any sent BTC is left under control of /// the signer group, and the funder can use `requestFunderAbort` to /// request an at-signer-discretion return of any BTC sent to a /// deposit that has been notified of a funding timeout. /// @dev This is considered a funder fault, and the funder's payment for /// opening the deposit is not refunded. Emits a SetupFailed event. /// Reverts if the funding timeout has not yet elapsed, or if the /// deposit is not currently awaiting funding proof. function notifyFundingTimedOut() external { self.notifyFundingTimedOut(); } /// @notice Requests a funder abort for a failed-funding deposit; that is, /// requests the return of a sent UTXO to _abortOutputScript. It /// imposes no requirements on the signing group. Signers should /// send their UTXO to the requested output script, but do so at /// their discretion and with no penalty for failing to do so. This /// can be used for example when a UTXO is sent that is the wrong /// size for the lot. /// @dev This is a self-admitted funder fault, and is only be callable by /// the TDT holder. This function emits the FunderAbortRequested event, /// but stores no additional state. /// @param _abortOutputScript The output script the funder wishes to request /// a return of their UTXO to. function requestFunderAbort(bytes memory _abortOutputScript) public { // not external to allow bytes memory parameters require( self.depositOwner() == msg.sender, "Only TDT holder can request funder abort" ); self.requestFunderAbort(_abortOutputScript); } /// @notice Anyone can provide a signature corresponding to the signers' /// public key to prove fraud during funding. Note that during /// funding no signature has been requested from the signers, so /// any signature is effectively fraud. /// @dev Calls out to the keep to verify if there was fraud. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature (v,r,s) tuple. /// @param _preimage The sha256 preimage of the digest. function provideFundingECDSAFraudProof( uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public { // not external to allow bytes memory parameters self.provideFundingECDSAFraudProof(_v, _r, _s, _signedDigest, _preimage); } /// @notice Anyone may submit a funding proof to the deposit showing that /// a transaction was submitted and sufficiently confirmed on the /// Bitcoin chain transferring the deposit lot size's amount of BTC /// to the signer-controlled private key corresopnding to this /// deposit. This will move the deposit into an active state. /// @dev Takes a pre-parsed transaction and calculates values needed to /// verify funding. /// @param _txVersion Transaction version number (4-byte little-endian). /// @param _txInputVector All transaction inputs prepended by the number of /// inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number /// of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @param _txLocktime Final 4 bytes of the transaction. /// @param _fundingOutputIndex Index of funding output in _txOutputVector /// (0-indexed). /// @param _merkleProof The merkle proof of transaction inclusion in a /// block. /// @param _txIndexInBlock Transaction index in the block (0-indexed). /// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, /// lowest height first. function provideBTCFundingProof( bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, uint8 _fundingOutputIndex, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public { // not external to allow bytes memory parameters self.provideBTCFundingProof( _txVersion, _txInputVector, _txOutputVector, _txLocktime, _fundingOutputIndex, _merkleProof, _txIndexInBlock, _bitcoinHeaders ); } //---------------------------- LIQUIDATION FLOW ------------------------------// /// @notice Notify the contract that the signers are undercollateralized. /// @dev This call will revert if the signers are not in fact /// undercollateralized according to the price feed. After /// TBTCConstants.COURTESY_CALL_DURATION, courtesy call times out and /// regular abort liquidation occurs; see /// `notifyCourtesyTimedOut`. function notifyCourtesyCall() external { self.notifyCourtesyCall(); } /// @notice Notify the contract that the signers' bond value has recovered /// enough to be considered sufficiently collateralized. /// @dev This call will revert if collateral is still below the /// undercollateralized threshold according to the price feed. function exitCourtesyCall() external { self.exitCourtesyCall(); } /// @notice Notify the contract that the courtesy period has expired and the /// deposit should move into liquidation. /// @dev This call will revert if the courtesy call period has not in fact /// expired or is not in the courtesy call state. Courtesy call /// expiration is treated as an abort, and is handled by seizing signer /// bonds and putting them up for auction for the lot size amount in /// TBTC (see `purchaseSignerBondsAtAuction`). Emits a /// LiquidationStarted event. The caller is captured as the liquidation /// initiator, and is eligible for 50% of any bond left after the /// auction is completed. function notifyCourtesyCallExpired() external { self.notifyCourtesyCallExpired(); } /// @notice Notify the contract that the signers are undercollateralized. /// @dev Calls out to the system for oracle info. /// @dev This call will revert if the signers are not in fact severely /// undercollateralized according to the price feed. Severe /// undercollateralization is treated as an abort, and is handled by /// seizing signer bonds and putting them up for auction in exchange /// for the lot size amount in TBTC (see /// `purchaseSignerBondsAtAuction`). Emits a LiquidationStarted event. /// The caller is captured as the liquidation initiator, and is /// eligible for 50% of any bond left after the auction is completed. function notifyUndercollateralizedLiquidation() external { self.notifyUndercollateralizedLiquidation(); } /// @notice Anyone can provide a signature corresponding to the signers' /// public key that was not requested to prove fraud. A redemption /// request and a redemption fee increase are the only ways to /// request a signature from the signers. /// @dev This call will revert if the underlying keep cannot verify that /// there was fraud. Fraud is handled by seizing signer bonds and /// putting them up for auction in exchange for the lot size amount in /// TBTC (see `purchaseSignerBondsAtAuction`). Emits a /// LiquidationStarted event. The caller is captured as the liquidation /// initiator, and is eligible for any bond left after the auction is /// completed. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature (v,r,s) tuple. /// @param _preimage The sha256 preimage of the digest. function provideECDSAFraudProof( uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public { // not external to allow bytes memory parameters self.provideECDSAFraudProof(_v, _r, _s, _signedDigest, _preimage); } /// @notice Notify the contract that the signers have failed to produce a /// signature for a redemption request in the allotted time. /// @dev This is considered an abort, and is punished by seizing signer /// bonds and putting them up for auction. Emits a LiquidationStarted /// event and a Liquidated event and sends the full signer bond to the /// redeemer. Reverts if the deposit is not currently awaiting a /// signature or if the allotted time has not yet elapsed. The caller /// is captured as the liquidation initiator, and is eligible for 50% /// of any bond left after the auction is completed. function notifyRedemptionSignatureTimedOut() external { self.notifyRedemptionSignatureTimedOut(); } /// @notice Notify the contract that the deposit has failed to receive a /// redemption proof in the allotted time. /// @dev This call will revert if the deposit is not currently awaiting a /// signature or if the allotted time has not yet elapsed. This is /// considered an abort, and is punished by seizing signer bonds and /// putting them up for auction for the lot size amount in TBTC (see /// `purchaseSignerBondsAtAuction`). Emits a LiquidationStarted event. /// The caller is captured as the liquidation initiator, and /// is eligible for 50% of any bond left after the auction is /// completed. function notifyRedemptionProofTimedOut() external { self.notifyRedemptionProofTimedOut(); } /// @notice Closes an auction and purchases the signer bonds by transferring /// the lot size in TBTC to the redeemer, if there is one, or to the /// TDT holder if not. Any bond amount that is not currently up for /// auction is either made available for the liquidation initiator /// to withdraw (for fraud) or split 50-50 between the initiator and /// the signers (for abort or collateralization issues). /// @dev The amount of ETH given for the transferred TBTC can be read using /// the `auctionValue` function; note, however, that the function's /// value is only static during the specific block it is queried, as it /// varies by block timestamp. function purchaseSignerBondsAtAuction() external { self.purchaseSignerBondsAtAuction(); } //---------------------------- REDEMPTION FLOW -------------------------------// /// @notice Get TBTC amount required for redemption by a specified /// _redeemer. /// @dev This call will revert if redemption is not possible by _redeemer. /// @param _redeemer The deposit redeemer whose TBTC requirement is being /// requested. /// @return The amount in TBTC needed by the `_redeemer` to redeem the /// deposit. function getRedemptionTbtcRequirement(address _redeemer) external view returns (uint256){ (uint256 tbtcPayment,,) = self.calculateRedemptionTbtcAmounts(_redeemer, false); return tbtcPayment; } /// @notice Get TBTC amount required for redemption assuming _redeemer /// is this deposit's owner (TDT holder). /// @param _redeemer The assumed owner of the deposit's TDT . /// @return The amount in TBTC needed to redeem the deposit. function getOwnerRedemptionTbtcRequirement(address _redeemer) external view returns (uint256){ (uint256 tbtcPayment,,) = self.calculateRedemptionTbtcAmounts(_redeemer, true); return tbtcPayment; } /// @notice Requests redemption of this deposit, meaning the transmission, /// by the signers, of the deposit's UTXO to the specified Bitocin /// output script. Requires approving the deposit to spend the /// amount of TBTC needed to redeem. /// @dev The amount of TBTC needed to redeem can be looked up using the /// `getRedemptionTbtcRequirement` or `getOwnerRedemptionTbtcRequirement` /// functions. /// @param _outputValueBytes The 8-byte little-endian output size. The /// difference between this value and the lot size of the deposit /// will be paid as a fee to the Bitcoin miners when the signed /// transaction is broadcast. /// @param _redeemerOutputScript The redeemer's length-prefixed output /// script. function requestRedemption( bytes8 _outputValueBytes, bytes memory _redeemerOutputScript ) public { // not external to allow bytes memory parameters self.requestRedemption(_outputValueBytes, _redeemerOutputScript); } /// @notice Anyone may provide a withdrawal signature if it was requested. /// @dev The signers will be penalized if this function is not called /// correctly within `TBTCConstants.REDEMPTION_SIGNATURE_TIMEOUT` /// seconds of a redemption request or fee increase being received. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. Should be in the low half of secp256k1 /// curve's order. function provideRedemptionSignature( uint8 _v, bytes32 _r, bytes32 _s ) external { self.provideRedemptionSignature(_v, _r, _s); } /// @notice Anyone may request a signature for a transaction with an /// increased Bitcoin transaction fee. /// @dev This call will revert if the fee is already at its maximum, or if /// the new requested fee is not a multiple of the initial requested /// fee. Transaction fees can only be bumped by the amount of the /// initial requested fee. Calling this sends the deposit back to /// the `AWAITING_WITHDRAWAL_SIGNATURE` state and requires the signers /// to `provideRedemptionSignature` for the new output value in a /// timely fashion. /// @param _previousOutputValueBytes The previous output's value. /// @param _newOutputValueBytes The new output's value. function increaseRedemptionFee( bytes8 _previousOutputValueBytes, bytes8 _newOutputValueBytes ) external { self.increaseRedemptionFee(_previousOutputValueBytes, _newOutputValueBytes); } /// @notice Anyone may submit a redemption proof to the deposit showing that /// a transaction was submitted and sufficiently confirmed on the /// Bitcoin chain transferring the deposit lot size's amount of BTC /// from the signer-controlled private key corresponding to this /// deposit to the requested redemption output script. This will /// move the deposit into a redeemed state. /// @dev Takes a pre-parsed transaction and calculates values needed to /// verify funding. Signers can have their bonds seized if this is not /// called within `TBTCConstants.REDEMPTION_PROOF_TIMEOUT` seconds of /// a redemption signature being provided. /// @param _txVersion Transaction version number (4-byte little-endian). /// @param _txInputVector All transaction inputs prepended by the number of /// inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number /// of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @param _txLocktime Final 4 bytes of the transaction. /// @param _merkleProof The merkle proof of transaction inclusion in a /// block. /// @param _txIndexInBlock Transaction index in the block (0-indexed). /// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, /// lowest height first. function provideRedemptionProof( bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public { // not external to allow bytes memory parameters self.provideRedemptionProof( _txVersion, _txInputVector, _txOutputVector, _txLocktime, _merkleProof, _txIndexInBlock, _bitcoinHeaders ); } //--------------------------- MUTATING HELPERS -------------------------------// /// @notice This function can only be called by the deposit factory; use /// `DepositFactory.createDeposit` to create a new deposit. /// @dev Initializes a new deposit clone with the base state for the /// deposit. /// @param _tbtcSystem `TBTCSystem` contract. More info in `TBTCSystem`. /// @param _tbtcToken `TBTCToken` contract. More info in TBTCToken`. /// @param _tbtcDepositToken `TBTCDepositToken` (TDT) contract. More info in /// `TBTCDepositToken`. /// @param _feeRebateToken `FeeRebateToken` (FRT) contract. More info in /// `FeeRebateToken`. /// @param _vendingMachineAddress `VendingMachine` address. More info in /// `VendingMachine`. /// @param _lotSizeSatoshis The minimum amount of satoshi the funder is /// required to send. This is also the amount of /// TBTC the TDT holder will be eligible to mint: /// (10**7 satoshi == 0.1 BTC == 0.1 TBTC). function initializeDeposit( ITBTCSystem _tbtcSystem, TBTCToken _tbtcToken, IERC721 _tbtcDepositToken, FeeRebateToken _feeRebateToken, address _vendingMachineAddress, uint64 _lotSizeSatoshis ) public onlyFactory payable { self.tbtcSystem = _tbtcSystem; self.tbtcToken = _tbtcToken; self.tbtcDepositToken = _tbtcDepositToken; self.feeRebateToken = _feeRebateToken; self.vendingMachineAddress = _vendingMachineAddress; self.initialize(_lotSizeSatoshis); } /// @notice This function can only be called by the vending machine. /// @dev Performs the same action as requestRedemption, but transfers /// ownership of the deposit to the specified _finalRecipient. Used as /// a utility helper for the vending machine's shortcut /// TBTC->redemption path. /// @param _outputValueBytes The 8-byte little-endian output size. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. /// @param _finalRecipient The address to receive the TDT and later be recorded as deposit redeemer. function transferAndRequestRedemption( bytes8 _outputValueBytes, bytes memory _redeemerOutputScript, address payable _finalRecipient ) public { // not external to allow bytes memory parameters require( msg.sender == self.vendingMachineAddress, "Only the vending machine can call transferAndRequestRedemption" ); self.transferAndRequestRedemption( _outputValueBytes, _redeemerOutputScript, _finalRecipient ); } /// @notice Withdraw the ETH balance of the deposit allotted to the caller. /// @dev Withdrawals can only happen when a contract is in an end-state. function withdrawFunds() external { self.withdrawFunds(); } } pragma solidity 0.5.17; import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol"; import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol"; import {IBondedECDSAKeep} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeep.sol"; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {DepositStates} from "./DepositStates.sol"; import {DepositUtils} from "./DepositUtils.sol"; import {TBTCConstants} from "../system/TBTCConstants.sol"; import {OutsourceDepositLogging} from "./OutsourceDepositLogging.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {ITBTCSystem} from "../interfaces/ITBTCSystem.sol"; library DepositLiquidation { using BTCUtils for bytes; using BytesLib for bytes; using SafeMath for uint256; using SafeMath for uint64; using DepositUtils for DepositUtils.Deposit; using DepositStates for DepositUtils.Deposit; using OutsourceDepositLogging for DepositUtils.Deposit; /// @notice Notifies the keep contract of fraud. Reverts if not fraud. /// @dev Calls out to the keep contract. this could get expensive if preimage /// is large. /// @param _d Deposit storage pointer. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature vrs tuple. /// @param _preimage The sha256 preimage of the digest. function submitSignatureFraud( DepositUtils.Deposit storage _d, uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public { IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); _keep.submitSignatureFraud(_v, _r, _s, _signedDigest, _preimage); } /// @notice Determines the collateralization percentage of the signing group. /// @dev Compares the bond value and lot value. /// @param _d Deposit storage pointer. /// @return Collateralization percentage as uint. function collateralizationPercentage(DepositUtils.Deposit storage _d) public view returns (uint256) { // Determine value of the lot in wei uint256 _satoshiPrice = _d.fetchBitcoinPrice(); uint64 _lotSizeSatoshis = _d.lotSizeSatoshis; uint256 _lotValue = _lotSizeSatoshis.mul(_satoshiPrice); // Amount of wei the signers have uint256 _bondValue = _d.fetchBondAmount(); // This converts into a percentage return (_bondValue.mul(100).div(_lotValue)); } /// @dev Starts signer liquidation by seizing signer bonds. /// If the deposit is currently being redeemed, the redeemer /// receives the full bond value; otherwise, a falling price auction /// begins to buy 1 TBTC in exchange for a portion of the seized bonds; /// see purchaseSignerBondsAtAuction(). /// @param _wasFraud True if liquidation is being started due to fraud, false if for any other reason. /// @param _d Deposit storage pointer. function startLiquidation(DepositUtils.Deposit storage _d, bool _wasFraud) internal { _d.logStartedLiquidation(_wasFraud); uint256 seized = _d.seizeSignerBonds(); address redeemerAddress = _d.redeemerAddress; // Reclaim used state for gas savings _d.redemptionTeardown(); // If we see fraud in the redemption flow, we shouldn't go to auction. // Instead give the full signer bond directly to the redeemer. if (_d.inRedemption() && _wasFraud) { _d.setLiquidated(); _d.enableWithdrawal(redeemerAddress, seized); _d.logLiquidated(); return; } _d.liquidationInitiator = msg.sender; _d.liquidationInitiated = block.timestamp; // Store the timestamp for auction if(_wasFraud){ _d.setFraudLiquidationInProgress(); } else{ _d.setLiquidationInProgress(); } } /// @notice Anyone can provide a signature that was not requested to prove fraud. /// @dev Calls out to the keep to verify if there was fraud. /// @param _d Deposit storage pointer. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature vrs tuple. /// @param _preimage The sha256 preimage of the digest. function provideECDSAFraudProof( DepositUtils.Deposit storage _d, uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public { // not external to allow bytes memory parameters require( !_d.inFunding(), "Use provideFundingECDSAFraudProof instead" ); require( !_d.inSignerLiquidation(), "Signer liquidation already in progress" ); require(!_d.inEndState(), "Contract has halted"); submitSignatureFraud(_d, _v, _r, _s, _signedDigest, _preimage); startLiquidation(_d, true); } /// @notice Closes an auction and purchases the signer bonds. Payout to buyer, funder, then signers if not fraud. /// @dev For interface, reading auctionValue will give a past value. the current is better. /// @param _d Deposit storage pointer. function purchaseSignerBondsAtAuction(DepositUtils.Deposit storage _d) external { bool _wasFraud = _d.inFraudLiquidationInProgress(); require(_d.inSignerLiquidation(), "No active auction"); _d.setLiquidated(); _d.logLiquidated(); // Send the TBTC to the redeemer if they exist, otherwise to the TDT // holder. If the TDT holder is the Vending Machine, burn it to maintain // the peg. This is because, if there is a redeemer set here, the TDT // holder has already been made whole at redemption request time. address tbtcRecipient = _d.redeemerAddress; if (tbtcRecipient == address(0)) { tbtcRecipient = _d.depositOwner(); } uint256 lotSizeTbtc = _d.lotSizeTbtc(); require(_d.tbtcToken.balanceOf(msg.sender) >= lotSizeTbtc, "Not enough TBTC to cover outstanding debt"); if(tbtcRecipient == _d.vendingMachineAddress){ _d.tbtcToken.burnFrom(msg.sender, lotSizeTbtc); // burn minimal amount to cover size } else{ _d.tbtcToken.transferFrom(msg.sender, tbtcRecipient, lotSizeTbtc); } // Distribute funds to auction buyer uint256 valueToDistribute = _d.auctionValue(); _d.enableWithdrawal(msg.sender, valueToDistribute); // Send any TBTC left to the Fee Rebate Token holder _d.distributeFeeRebate(); // For fraud, pay remainder to the liquidation initiator. // For non-fraud, split 50-50 between initiator and signers. if the transfer amount is 1, // division will yield a 0 value which causes a revert; instead, // we simply ignore such a tiny amount and leave some wei dust in escrow uint256 contractEthBalance = address(this).balance; address payable initiator = _d.liquidationInitiator; if (initiator == address(0)){ initiator = address(0xdead); } if (contractEthBalance > valueToDistribute + 1) { uint256 remainingUnallocated = contractEthBalance.sub(valueToDistribute); if (_wasFraud) { _d.enableWithdrawal(initiator, remainingUnallocated); } else { // There will always be a liquidation initiator. uint256 split = remainingUnallocated.div(2); _d.pushFundsToKeepGroup(split); _d.enableWithdrawal(initiator, remainingUnallocated.sub(split)); } } } /// @notice Notify the contract that the signers are undercollateralized. /// @dev Calls out to the system for oracle info. /// @param _d Deposit storage pointer. function notifyCourtesyCall(DepositUtils.Deposit storage _d) external { require(_d.inActive(), "Can only courtesy call from active state"); require(collateralizationPercentage(_d) < _d.undercollateralizedThresholdPercent, "Signers have sufficient collateral"); _d.courtesyCallInitiated = block.timestamp; _d.setCourtesyCall(); _d.logCourtesyCalled(); } /// @notice Goes from courtesy call to active. /// @dev Only callable if collateral is sufficient and the deposit is not expiring. /// @param _d Deposit storage pointer. function exitCourtesyCall(DepositUtils.Deposit storage _d) external { require(_d.inCourtesyCall(), "Not currently in courtesy call"); require(collateralizationPercentage(_d) >= _d.undercollateralizedThresholdPercent, "Deposit is still undercollateralized"); _d.setActive(); _d.logExitedCourtesyCall(); } /// @notice Notify the contract that the signers are undercollateralized. /// @dev Calls out to the system for oracle info. /// @param _d Deposit storage pointer. function notifyUndercollateralizedLiquidation(DepositUtils.Deposit storage _d) external { require(_d.inRedeemableState(), "Deposit not in active or courtesy call"); require(collateralizationPercentage(_d) < _d.severelyUndercollateralizedThresholdPercent, "Deposit has sufficient collateral"); startLiquidation(_d, false); } /// @notice Notifies the contract that the courtesy period has elapsed. /// @dev This is treated as an abort, rather than fraud. /// @param _d Deposit storage pointer. function notifyCourtesyCallExpired(DepositUtils.Deposit storage _d) external { require(_d.inCourtesyCall(), "Not in a courtesy call period"); require(block.timestamp >= _d.courtesyCallInitiated.add(TBTCConstants.getCourtesyCallTimeout()), "Courtesy period has not elapsed"); startLiquidation(_d, false); } } pragma solidity ^0.5.10; /** @title BitcoinSPV */ /** @author Summa (https://summa.one) */ import {BytesLib} from "./BytesLib.sol"; import {SafeMath} from "./SafeMath.sol"; library BTCUtils { using BytesLib for bytes; using SafeMath for uint256; // The target at minimum Difficulty. Also the target of the genesis block uint256 public constant DIFF1_TARGET = 0xffff0000000000000000000000000000000000000000000000000000; uint256 public constant RETARGET_PERIOD = 2 * 7 * 24 * 60 * 60; // 2 weeks in seconds uint256 public constant RETARGET_PERIOD_BLOCKS = 2016; // 2 weeks in blocks uint256 public constant ERR_BAD_ARG = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; /* ***** */ /* UTILS */ /* ***** */ /// @notice Determines the length of a VarInt in bytes /// @dev A VarInt of >1 byte is prefixed with a flag indicating its length /// @param _flag The first byte of a VarInt /// @return The number of non-flag bytes in the VarInt function determineVarIntDataLength(bytes memory _flag) internal pure returns (uint8) { if (uint8(_flag[0]) == 0xff) { return 8; // one-byte flag, 8 bytes data } if (uint8(_flag[0]) == 0xfe) { return 4; // one-byte flag, 4 bytes data } if (uint8(_flag[0]) == 0xfd) { return 2; // one-byte flag, 2 bytes data } return 0; // flag is data } /// @notice Parse a VarInt into its data length and the number it represents /// @dev Useful for Parsing Vins and Vouts. Returns ERR_BAD_ARG if insufficient bytes. /// Caller SHOULD explicitly handle this case (or bubble it up) /// @param _b A byte-string starting with a VarInt /// @return number of bytes in the encoding (not counting the tag), the encoded int function parseVarInt(bytes memory _b) internal pure returns (uint256, uint256) { uint8 _dataLen = determineVarIntDataLength(_b); if (_dataLen == 0) { return (0, uint8(_b[0])); } if (_b.length < 1 + _dataLen) { return (ERR_BAD_ARG, 0); } uint256 _number = bytesToUint(reverseEndianness(_b.slice(1, _dataLen))); return (_dataLen, _number); } /// @notice Changes the endianness of a byte array /// @dev Returns a new, backwards, bytes /// @param _b The bytes to reverse /// @return The reversed bytes function reverseEndianness(bytes memory _b) internal pure returns (bytes memory) { bytes memory _newValue = new bytes(_b.length); for (uint i = 0; i < _b.length; i++) { _newValue[_b.length - i - 1] = _b[i]; } return _newValue; } /// @notice Changes the endianness of a uint256 /// @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel /// @param _b The unsigned integer to reverse /// @return The reversed value function reverseUint256(uint256 _b) internal pure returns (uint256 v) { v = _b; // swap bytes v = ((v >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) | ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8); // swap 2-byte long pairs v = ((v >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) | ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16); // swap 4-byte long pairs v = ((v >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) | ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32); // swap 8-byte long pairs v = ((v >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) | ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64); // swap 16-byte long pairs v = (v >> 128) | (v << 128); } /// @notice Converts big-endian bytes to a uint /// @dev Traverses the byte array and sums the bytes /// @param _b The big-endian bytes-encoded integer /// @return The integer representation function bytesToUint(bytes memory _b) internal pure returns (uint256) { uint256 _number; for (uint i = 0; i < _b.length; i++) { _number = _number + uint8(_b[i]) * (2 ** (8 * (_b.length - (i + 1)))); } return _number; } /// @notice Get the last _num bytes from a byte array /// @param _b The byte array to slice /// @param _num The number of bytes to extract from the end /// @return The last _num bytes of _b function lastBytes(bytes memory _b, uint256 _num) internal pure returns (bytes memory) { uint256 _start = _b.length.sub(_num); return _b.slice(_start, _num); } /// @notice Implements bitcoin's hash160 (rmd160(sha2())) /// @dev abi.encodePacked changes the return to bytes instead of bytes32 /// @param _b The pre-image /// @return The digest function hash160(bytes memory _b) internal pure returns (bytes memory) { return abi.encodePacked(ripemd160(abi.encodePacked(sha256(_b)))); } /// @notice Implements bitcoin's hash256 (double sha2) /// @dev abi.encodePacked changes the return to bytes instead of bytes32 /// @param _b The pre-image /// @return The digest function hash256(bytes memory _b) internal pure returns (bytes32) { return sha256(abi.encodePacked(sha256(_b))); } /// @notice Implements bitcoin's hash256 (double sha2) /// @dev sha2 is precompiled smart contract located at address(2) /// @param _b The pre-image /// @return The digest function hash256View(bytes memory _b) internal view returns (bytes32 res) { // solium-disable-next-line security/no-inline-assembly assembly { let ptr := mload(0x40) pop(staticcall(gas, 2, add(_b, 32), mload(_b), ptr, 32)) pop(staticcall(gas, 2, ptr, 32, ptr, 32)) res := mload(ptr) } } /* ************ */ /* Legacy Input */ /* ************ */ /// @notice Extracts the nth input from the vin (0-indexed) /// @dev Iterates over the vin. If you need to extract several, write a custom function /// @param _vin The vin as a tightly-packed byte array /// @param _index The 0-indexed location of the input to extract /// @return The input as a byte array function extractInputAtIndex(bytes memory _vin, uint256 _index) internal pure returns (bytes memory) { uint256 _varIntDataLen; uint256 _nIns; (_varIntDataLen, _nIns) = parseVarInt(_vin); require(_varIntDataLen != ERR_BAD_ARG, "Read overrun during VarInt parsing"); require(_index < _nIns, "Vin read overrun"); bytes memory _remaining; uint256 _len = 0; uint256 _offset = 1 + _varIntDataLen; for (uint256 _i = 0; _i < _index; _i ++) { _remaining = _vin.slice(_offset, _vin.length - _offset); _len = determineInputLength(_remaining); require(_len != ERR_BAD_ARG, "Bad VarInt in scriptSig"); _offset = _offset + _len; } _remaining = _vin.slice(_offset, _vin.length - _offset); _len = determineInputLength(_remaining); require(_len != ERR_BAD_ARG, "Bad VarInt in scriptSig"); return _vin.slice(_offset, _len); } /// @notice Determines whether an input is legacy /// @dev False if no scriptSig, otherwise True /// @param _input The input /// @return True for legacy, False for witness function isLegacyInput(bytes memory _input) internal pure returns (bool) { return _input.keccak256Slice(36, 1) != keccak256(hex"00"); } /// @notice Determines the length of a scriptSig in an input /// @dev Will return 0 if passed a witness input. /// @param _input The LEGACY input /// @return The length of the script sig function extractScriptSigLen(bytes memory _input) internal pure returns (uint256, uint256) { if (_input.length < 37) { return (ERR_BAD_ARG, 0); } bytes memory _afterOutpoint = _input.slice(36, _input.length - 36); uint256 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = parseVarInt(_afterOutpoint); return (_varIntDataLen, _scriptSigLen); } /// @notice Determines the length of an input from its scriptSig /// @dev 36 for outpoint, 1 for scriptSig length, 4 for sequence /// @param _input The input /// @return The length of the input in bytes function determineInputLength(bytes memory _input) internal pure returns (uint256) { uint256 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input); if (_varIntDataLen == ERR_BAD_ARG) { return ERR_BAD_ARG; } return 36 + 1 + _varIntDataLen + _scriptSigLen + 4; } /// @notice Extracts the LE sequence bytes from an input /// @dev Sequence is used for relative time locks /// @param _input The LEGACY input /// @return The sequence bytes (LE uint) function extractSequenceLELegacy(bytes memory _input) internal pure returns (bytes memory) { uint256 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input); require(_varIntDataLen != ERR_BAD_ARG, "Bad VarInt in scriptSig"); return _input.slice(36 + 1 + _varIntDataLen + _scriptSigLen, 4); } /// @notice Extracts the sequence from the input /// @dev Sequence is a 4-byte little-endian number /// @param _input The LEGACY input /// @return The sequence number (big-endian uint) function extractSequenceLegacy(bytes memory _input) internal pure returns (uint32) { bytes memory _leSeqence = extractSequenceLELegacy(_input); bytes memory _beSequence = reverseEndianness(_leSeqence); return uint32(bytesToUint(_beSequence)); } /// @notice Extracts the VarInt-prepended scriptSig from the input in a tx /// @dev Will return hex"00" if passed a witness input /// @param _input The LEGACY input /// @return The length-prepended scriptSig function extractScriptSig(bytes memory _input) internal pure returns (bytes memory) { uint256 _varIntDataLen; uint256 _scriptSigLen; (_varIntDataLen, _scriptSigLen) = extractScriptSigLen(_input); require(_varIntDataLen != ERR_BAD_ARG, "Bad VarInt in scriptSig"); return _input.slice(36, 1 + _varIntDataLen + _scriptSigLen); } /* ************* */ /* Witness Input */ /* ************* */ /// @notice Extracts the LE sequence bytes from an input /// @dev Sequence is used for relative time locks /// @param _input The WITNESS input /// @return The sequence bytes (LE uint) function extractSequenceLEWitness(bytes memory _input) internal pure returns (bytes memory) { return _input.slice(37, 4); } /// @notice Extracts the sequence from the input in a tx /// @dev Sequence is a 4-byte little-endian number /// @param _input The WITNESS input /// @return The sequence number (big-endian uint) function extractSequenceWitness(bytes memory _input) internal pure returns (uint32) { bytes memory _leSeqence = extractSequenceLEWitness(_input); bytes memory _inputeSequence = reverseEndianness(_leSeqence); return uint32(bytesToUint(_inputeSequence)); } /// @notice Extracts the outpoint from the input in a tx /// @dev 32-byte tx id with 4-byte index /// @param _input The input /// @return The outpoint (LE bytes of prev tx hash + LE bytes of prev tx index) function extractOutpoint(bytes memory _input) internal pure returns (bytes memory) { return _input.slice(0, 36); } /// @notice Extracts the outpoint tx id from an input /// @dev 32-byte tx id /// @param _input The input /// @return The tx id (little-endian bytes) function extractInputTxIdLE(bytes memory _input) internal pure returns (bytes32) { return _input.slice(0, 32).toBytes32(); } /// @notice Extracts the LE tx input index from the input in a tx /// @dev 4-byte tx index /// @param _input The input /// @return The tx index (little-endian bytes) function extractTxIndexLE(bytes memory _input) internal pure returns (bytes memory) { return _input.slice(32, 4); } /* ****** */ /* Output */ /* ****** */ /// @notice Determines the length of an output /// @dev Works with any properly formatted output /// @param _output The output /// @return The length indicated by the prefix, error if invalid length function determineOutputLength(bytes memory _output) internal pure returns (uint256) { if (_output.length < 9) { return ERR_BAD_ARG; } bytes memory _afterValue = _output.slice(8, _output.length - 8); uint256 _varIntDataLen; uint256 _scriptPubkeyLength; (_varIntDataLen, _scriptPubkeyLength) = parseVarInt(_afterValue); if (_varIntDataLen == ERR_BAD_ARG) { return ERR_BAD_ARG; } // 8-byte value, 1-byte for tag itself return 8 + 1 + _varIntDataLen + _scriptPubkeyLength; } /// @notice Extracts the output at a given index in the TxOuts vector /// @dev Iterates over the vout. If you need to extract multiple, write a custom function /// @param _vout The _vout to extract from /// @param _index The 0-indexed location of the output to extract /// @return The specified output function extractOutputAtIndex(bytes memory _vout, uint256 _index) internal pure returns (bytes memory) { uint256 _varIntDataLen; uint256 _nOuts; (_varIntDataLen, _nOuts) = parseVarInt(_vout); require(_varIntDataLen != ERR_BAD_ARG, "Read overrun during VarInt parsing"); require(_index < _nOuts, "Vout read overrun"); bytes memory _remaining; uint256 _len = 0; uint256 _offset = 1 + _varIntDataLen; for (uint256 _i = 0; _i < _index; _i ++) { _remaining = _vout.slice(_offset, _vout.length - _offset); _len = determineOutputLength(_remaining); require(_len != ERR_BAD_ARG, "Bad VarInt in scriptPubkey"); _offset += _len; } _remaining = _vout.slice(_offset, _vout.length - _offset); _len = determineOutputLength(_remaining); require(_len != ERR_BAD_ARG, "Bad VarInt in scriptPubkey"); return _vout.slice(_offset, _len); } /// @notice Extracts the value bytes from the output in a tx /// @dev Value is an 8-byte little-endian number /// @param _output The output /// @return The output value as LE bytes function extractValueLE(bytes memory _output) internal pure returns (bytes memory) { return _output.slice(0, 8); } /// @notice Extracts the value from the output in a tx /// @dev Value is an 8-byte little-endian number /// @param _output The output /// @return The output value function extractValue(bytes memory _output) internal pure returns (uint64) { bytes memory _leValue = extractValueLE(_output); bytes memory _beValue = reverseEndianness(_leValue); return uint64(bytesToUint(_beValue)); } /// @notice Extracts the data from an op return output /// @dev Returns hex"" if no data or not an op return /// @param _output The output /// @return Any data contained in the opreturn output, null if not an op return function extractOpReturnData(bytes memory _output) internal pure returns (bytes memory) { if (_output.keccak256Slice(9, 1) != keccak256(hex"6a")) { return hex""; } bytes memory _dataLen = _output.slice(10, 1); return _output.slice(11, bytesToUint(_dataLen)); } /// @notice Extracts the hash from the output script /// @dev Determines type by the length prefix and validates format /// @param _output The output /// @return The hash committed to by the pk_script, or null for errors function extractHash(bytes memory _output) internal pure returns (bytes memory) { uint8 _scriptLen = uint8(_output[8]); // don't have to worry about overflow here. // if _scriptLen + 9 overflows, then output.length would have to be < 9 // for this check to pass. if it's < 9, then we errored when assigning // _scriptLen if (_scriptLen + 9 != _output.length) { return hex""; } if (uint8(_output[9]) == 0) { if (_scriptLen < 2) { return hex""; } uint256 _payloadLen = uint8(_output[10]); // Check for maliciously formatted witness outputs. // No need to worry about underflow as long b/c of the `< 2` check if (_payloadLen != _scriptLen - 2 || (_payloadLen != 0x20 && _payloadLen != 0x14)) { return hex""; } return _output.slice(11, _payloadLen); } else { bytes32 _tag = _output.keccak256Slice(8, 3); // p2pkh if (_tag == keccak256(hex"1976a9")) { // Check for maliciously formatted p2pkh // No need to worry about underflow, b/c of _scriptLen check if (uint8(_output[11]) != 0x14 || _output.keccak256Slice(_output.length - 2, 2) != keccak256(hex"88ac")) { return hex""; } return _output.slice(12, 20); //p2sh } else if (_tag == keccak256(hex"17a914")) { // Check for maliciously formatted p2sh // No need to worry about underflow, b/c of _scriptLen check if (uint8(_output[_output.length - 1]) != 0x87) { return hex""; } return _output.slice(11, 20); } } return hex""; /* NB: will trigger on OPRETURN and any non-standard that doesn't overrun */ } /* ********** */ /* Witness TX */ /* ********** */ /// @notice Checks that the vin passed up is properly formatted /// @dev Consider a vin with a valid vout in its scriptsig /// @param _vin Raw bytes length-prefixed input vector /// @return True if it represents a validly formatted vin function validateVin(bytes memory _vin) internal pure returns (bool) { uint256 _varIntDataLen; uint256 _nIns; (_varIntDataLen, _nIns) = parseVarInt(_vin); // Not valid if it says there are too many or no inputs if (_nIns == 0 || _varIntDataLen == ERR_BAD_ARG) { return false; } uint256 _offset = 1 + _varIntDataLen; for (uint256 i = 0; i < _nIns; i++) { // If we're at the end, but still expect more if (_offset >= _vin.length) { return false; } // Grab the next input and determine its length. bytes memory _next = _vin.slice(_offset, _vin.length - _offset); uint256 _nextLen = determineInputLength(_next); if (_nextLen == ERR_BAD_ARG) { return false; } // Increase the offset by that much _offset += _nextLen; } // Returns false if we're not exactly at the end return _offset == _vin.length; } /// @notice Checks that the vout passed up is properly formatted /// @dev Consider a vout with a valid scriptpubkey /// @param _vout Raw bytes length-prefixed output vector /// @return True if it represents a validly formatted vout function validateVout(bytes memory _vout) internal pure returns (bool) { uint256 _varIntDataLen; uint256 _nOuts; (_varIntDataLen, _nOuts) = parseVarInt(_vout); // Not valid if it says there are too many or no outputs if (_nOuts == 0 || _varIntDataLen == ERR_BAD_ARG) { return false; } uint256 _offset = 1 + _varIntDataLen; for (uint256 i = 0; i < _nOuts; i++) { // If we're at the end, but still expect more if (_offset >= _vout.length) { return false; } // Grab the next output and determine its length. // Increase the offset by that much bytes memory _next = _vout.slice(_offset, _vout.length - _offset); uint256 _nextLen = determineOutputLength(_next); if (_nextLen == ERR_BAD_ARG) { return false; } _offset += _nextLen; } // Returns false if we're not exactly at the end return _offset == _vout.length; } /* ************ */ /* Block Header */ /* ************ */ /// @notice Extracts the transaction merkle root from a block header /// @dev Use verifyHash256Merkle to verify proofs with this root /// @param _header The header /// @return The merkle root (little-endian) function extractMerkleRootLE(bytes memory _header) internal pure returns (bytes memory) { return _header.slice(36, 32); } /// @notice Extracts the target from a block header /// @dev Target is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent /// @param _header The header /// @return The target threshold function extractTarget(bytes memory _header) internal pure returns (uint256) { bytes memory _m = _header.slice(72, 3); uint8 _e = uint8(_header[75]); uint256 _mantissa = bytesToUint(reverseEndianness(_m)); uint _exponent = _e - 3; return _mantissa * (256 ** _exponent); } /// @notice Calculate difficulty from the difficulty 1 target and current target /// @dev Difficulty 1 is 0x1d00ffff on mainnet and testnet /// @dev Difficulty 1 is a 256-bit number encoded as a 3-byte mantissa and 1-byte exponent /// @param _target The current target /// @return The block difficulty (bdiff) function calculateDifficulty(uint256 _target) internal pure returns (uint256) { // Difficulty 1 calculated from 0x1d00ffff return DIFF1_TARGET.div(_target); } /// @notice Extracts the previous block's hash from a block header /// @dev Block headers do NOT include block number :( /// @param _header The header /// @return The previous block's hash (little-endian) function extractPrevBlockLE(bytes memory _header) internal pure returns (bytes memory) { return _header.slice(4, 32); } /// @notice Extracts the timestamp from a block header /// @dev Time is not 100% reliable /// @param _header The header /// @return The timestamp (little-endian bytes) function extractTimestampLE(bytes memory _header) internal pure returns (bytes memory) { return _header.slice(68, 4); } /// @notice Extracts the timestamp from a block header /// @dev Time is not 100% reliable /// @param _header The header /// @return The timestamp (uint) function extractTimestamp(bytes memory _header) internal pure returns (uint32) { return uint32(bytesToUint(reverseEndianness(extractTimestampLE(_header)))); } /// @notice Extracts the expected difficulty from a block header /// @dev Does NOT verify the work /// @param _header The header /// @return The difficulty as an integer function extractDifficulty(bytes memory _header) internal pure returns (uint256) { return calculateDifficulty(extractTarget(_header)); } /// @notice Concatenates and hashes two inputs for merkle proving /// @param _a The first hash /// @param _b The second hash /// @return The double-sha256 of the concatenated hashes function _hash256MerkleStep(bytes memory _a, bytes memory _b) internal pure returns (bytes32) { return hash256(abi.encodePacked(_a, _b)); } /// @notice Verifies a Bitcoin-style merkle tree /// @dev Leaves are 0-indexed. /// @param _proof The proof. Tightly packed LE sha256 hashes. The last hash is the root /// @param _index The index of the leaf /// @return true if the proof is valid, else false function verifyHash256Merkle(bytes memory _proof, uint _index) internal pure returns (bool) { // Not an even number of hashes if (_proof.length % 32 != 0) { return false; } // Special case for coinbase-only blocks if (_proof.length == 32) { return true; } // Should never occur if (_proof.length == 64) { return false; } uint _idx = _index; bytes32 _root = _proof.slice(_proof.length - 32, 32).toBytes32(); bytes32 _current = _proof.slice(0, 32).toBytes32(); for (uint i = 1; i < (_proof.length.div(32)) - 1; i++) { if (_idx % 2 == 1) { _current = _hash256MerkleStep(_proof.slice(i * 32, 32), abi.encodePacked(_current)); } else { _current = _hash256MerkleStep(abi.encodePacked(_current), _proof.slice(i * 32, 32)); } _idx = _idx >> 1; } return _current == _root; } /* NB: https://github.com/bitcoin/bitcoin/blob/78dae8caccd82cfbfd76557f1fb7d7557c7b5edb/src/pow.cpp#L49-L72 NB: We get a full-bitlength target from this. For comparison with header-encoded targets we need to mask it with the header target e.g. (full & truncated) == truncated */ /// @notice performs the bitcoin difficulty retarget /// @dev implements the Bitcoin algorithm precisely /// @param _previousTarget the target of the previous period /// @param _firstTimestamp the timestamp of the first block in the difficulty period /// @param _secondTimestamp the timestamp of the last block in the difficulty period /// @return the new period's target threshold function retargetAlgorithm( uint256 _previousTarget, uint256 _firstTimestamp, uint256 _secondTimestamp ) internal pure returns (uint256) { uint256 _elapsedTime = _secondTimestamp.sub(_firstTimestamp); // Normalize ratio to factor of 4 if very long or very short if (_elapsedTime < RETARGET_PERIOD.div(4)) { _elapsedTime = RETARGET_PERIOD.div(4); } if (_elapsedTime > RETARGET_PERIOD.mul(4)) { _elapsedTime = RETARGET_PERIOD.mul(4); } /* NB: high targets e.g. ffff0020 can cause overflows here so we divide it by 256**2, then multiply by 256**2 later we know the target is evenly divisible by 256**2, so this isn't an issue */ uint256 _adjusted = _previousTarget.div(65536).mul(_elapsedTime); return _adjusted.div(RETARGET_PERIOD).mul(65536); } } pragma solidity ^0.5.10; /* https://github.com/GNSPS/solidity-bytes-utils/ This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <https://unlicense.org> */ /** @title BytesLib **/ /** @author https://github.com/GNSPS **/ library BytesLib { function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } return tempBytes; } function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal { assembly { // Read the first 32 bytes of _preBytes storage, which is the length // of the array. (We don't need to use the offset into the slot // because arrays use the entire slot.) let fslot := sload(_preBytes_slot) // Arrays of 31 bytes or less have an even value in their slot, // while longer arrays have an odd value. The actual length is // the slot divided by two for odd values, and the lowest order // byte divided by two for even values. // If the slot is even, bitwise and the slot with 255 and divide by // two to get the length. If the slot is odd, bitwise and the slot // with -1 and divide by two. let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage switch add(lt(slength, 32), lt(newlength, 32)) case 2 { // Since the new array still fits in the slot, we just need to // update the contents of the slot. // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length sstore( _preBytes_slot, // all the modifications to the slot are inside this // next block add( // we can just add to the slot contents because the // bytes we want to change are the LSBs fslot, add( mul( div( // load the bytes from memory mload(add(_postBytes, 0x20)), // zero all bytes to the right exp(0x100, sub(32, mlength)) ), // and now shift left the number of bytes to // leave space for the length in the slot exp(0x100, sub(32, newlength)) ), // increase length by the double of the memory // bytes length mul(mlength, 2) ) ) ) } case 1 { // The stored value fits in the slot, but the combined value // will exceed it. // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // The contents of the _postBytes array start 32 bytes into // the structure. Our first read should obtain the `submod` // bytes that can fit into the unused space in the last word // of the stored array. To get this, we read 32 bytes starting // from `submod`, so the data we read overlaps with the array // contents by `submod` bytes. Masking the lowest-order // `submod` bytes allows us to add that value directly to the // stored value. let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore( sc, add( and( fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 ), and(mload(mc), mask) ) ) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) // Start copying to the last used word of the stored array. let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // Copy over the first `submod` bytes of the new data as in // case 1 above. let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } function slice(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory res) { if (_length == 0) { return hex""; } uint _end = _start + _length; require(_end > _start && _bytes.length >= _end, "Slice out of bounds"); assembly { // Alloc bytes array with additional 32 bytes afterspace and assign it's size res := mload(0x40) mstore(0x40, add(add(res, 64), _length)) mstore(res, _length) // Compute distance between source and destination pointers let diff := sub(res, add(_bytes, _start)) for { let src := add(add(_bytes, 32), _start) let end := add(src, _length) } lt(src, end) { src := add(src, 32) } { mstore(add(src, diff), mload(src)) } } } function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) { uint _totalLen = _start + 20; require(_totalLen > _start && _bytes.length >= _totalLen, "Address conversion out of bounds."); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) { uint _totalLen = _start + 32; require(_totalLen > _start && _bytes.length >= _totalLen, "Uint conversion out of bounds."); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { bool success = true; assembly { let length := mload(_preBytes) // if lengths don't match the arrays are not equal switch eq(length, mload(_postBytes)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } } default { // unsuccess: success := 0 } } return success; } function equalStorage(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) { bool success = true; assembly { // we know _preBytes_offset is 0 let fslot := sload(_preBytes_slot) // Decode the length of the stored array like in concatStorage(). let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) // if lengths don't match the arrays are not equal switch eq(slength, mlength) case 1 { // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { // blank the last byte which is the length fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { // unsuccess: success := 0 } } default { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) for {} eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { // unsuccess: success := 0 cb := 0 } } } } } default { // unsuccess: success := 0 } } return success; } function toBytes32(bytes memory _source) pure internal returns (bytes32 result) { if (_source.length == 0) { return 0x0; } assembly { result := mload(add(_source, 32)) } } function keccak256Slice(bytes memory _bytes, uint _start, uint _length) pure internal returns (bytes32 result) { uint _end = _start + _length; require(_end > _start && _bytes.length >= _end, "Slice out of bounds"); assembly { result := keccak256(add(add(_bytes, 32), _start), _length) } } } pragma solidity ^0.5.10; /* The MIT License (MIT) Copyright (c) 2016 Smart Contract Solutions, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; require(c / _a == _b, "Overflow during multiplication."); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a, "Underflow during subtraction."); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; require(c >= _a, "Overflow during addition."); return c; } } pragma solidity 0.5.17; import {DepositUtils} from "./DepositUtils.sol"; library DepositStates { enum States { // DOES NOT EXIST YET START, // FUNDING FLOW AWAITING_SIGNER_SETUP, AWAITING_BTC_FUNDING_PROOF, // FAILED SETUP FAILED_SETUP, // ACTIVE ACTIVE, // includes courtesy call // REDEMPTION FLOW AWAITING_WITHDRAWAL_SIGNATURE, AWAITING_WITHDRAWAL_PROOF, REDEEMED, // SIGNER LIQUIDATION FLOW COURTESY_CALL, FRAUD_LIQUIDATION_IN_PROGRESS, LIQUIDATION_IN_PROGRESS, LIQUIDATED } /// @notice Check if the contract is currently in the funding flow. /// @dev This checks on the funding flow happy path, not the fraud path. /// @param _d Deposit storage pointer. /// @return True if contract is currently in the funding flow else False. function inFunding(DepositUtils.Deposit storage _d) public view returns (bool) { return ( _d.currentState == uint8(States.AWAITING_SIGNER_SETUP) || _d.currentState == uint8(States.AWAITING_BTC_FUNDING_PROOF) ); } /// @notice Check if the contract is currently in the signer liquidation flow. /// @dev This could be caused by fraud, or by an unfilled margin call. /// @param _d Deposit storage pointer. /// @return True if contract is currently in the liquidaton flow else False. function inSignerLiquidation(DepositUtils.Deposit storage _d) public view returns (bool) { return ( _d.currentState == uint8(States.LIQUIDATION_IN_PROGRESS) || _d.currentState == uint8(States.FRAUD_LIQUIDATION_IN_PROGRESS) ); } /// @notice Check if the contract is currently in the redepmtion flow. /// @dev This checks on the redemption flow, not the REDEEMED termination state. /// @param _d Deposit storage pointer. /// @return True if contract is currently in the redemption flow else False. function inRedemption(DepositUtils.Deposit storage _d) public view returns (bool) { return ( _d.currentState == uint8(States.AWAITING_WITHDRAWAL_SIGNATURE) || _d.currentState == uint8(States.AWAITING_WITHDRAWAL_PROOF) ); } /// @notice Check if the contract has halted. /// @dev This checks on any halt state, regardless of triggering circumstances. /// @param _d Deposit storage pointer. /// @return True if contract has halted permanently. function inEndState(DepositUtils.Deposit storage _d) public view returns (bool) { return ( _d.currentState == uint8(States.LIQUIDATED) || _d.currentState == uint8(States.REDEEMED) || _d.currentState == uint8(States.FAILED_SETUP) ); } /// @notice Check if the contract is available for a redemption request. /// @dev Redemption is available from active and courtesy call. /// @param _d Deposit storage pointer. /// @return True if available, False otherwise. function inRedeemableState(DepositUtils.Deposit storage _d) public view returns (bool) { return ( _d.currentState == uint8(States.ACTIVE) || _d.currentState == uint8(States.COURTESY_CALL) ); } /// @notice Check if the contract is currently in the start state (awaiting setup). /// @dev This checks on the funding flow happy path, not the fraud path. /// @param _d Deposit storage pointer. /// @return True if contract is currently in the start state else False. function inStart(DepositUtils.Deposit storage _d) public view returns (bool) { return (_d.currentState == uint8(States.START)); } function inAwaitingSignerSetup(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.AWAITING_SIGNER_SETUP); } function inAwaitingBTCFundingProof(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.AWAITING_BTC_FUNDING_PROOF); } function inFailedSetup(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.FAILED_SETUP); } function inActive(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.ACTIVE); } function inAwaitingWithdrawalSignature(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.AWAITING_WITHDRAWAL_SIGNATURE); } function inAwaitingWithdrawalProof(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.AWAITING_WITHDRAWAL_PROOF); } function inRedeemed(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.REDEEMED); } function inCourtesyCall(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.COURTESY_CALL); } function inFraudLiquidationInProgress(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.FRAUD_LIQUIDATION_IN_PROGRESS); } function inLiquidationInProgress(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.LIQUIDATION_IN_PROGRESS); } function inLiquidated(DepositUtils.Deposit storage _d) external view returns (bool) { return _d.currentState == uint8(States.LIQUIDATED); } function setAwaitingSignerSetup(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.AWAITING_SIGNER_SETUP); } function setAwaitingBTCFundingProof(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.AWAITING_BTC_FUNDING_PROOF); } function setFailedSetup(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.FAILED_SETUP); } function setActive(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.ACTIVE); } function setAwaitingWithdrawalSignature(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.AWAITING_WITHDRAWAL_SIGNATURE); } function setAwaitingWithdrawalProof(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.AWAITING_WITHDRAWAL_PROOF); } function setRedeemed(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.REDEEMED); } function setCourtesyCall(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.COURTESY_CALL); } function setFraudLiquidationInProgress(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.FRAUD_LIQUIDATION_IN_PROGRESS); } function setLiquidationInProgress(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.LIQUIDATION_IN_PROGRESS); } function setLiquidated(DepositUtils.Deposit storage _d) external { _d.currentState = uint8(States.LIQUIDATED); } } pragma solidity 0.5.17; import {ValidateSPV} from "@summa-tx/bitcoin-spv-sol/contracts/ValidateSPV.sol"; import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol"; import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol"; import {IBondedECDSAKeep} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeep.sol"; import {IERC721} from "openzeppelin-solidity/contracts/token/ERC721/IERC721.sol"; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {DepositStates} from "./DepositStates.sol"; import {TBTCConstants} from "../system/TBTCConstants.sol"; import {ITBTCSystem} from "../interfaces/ITBTCSystem.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {FeeRebateToken} from "../system/FeeRebateToken.sol"; library DepositUtils { using SafeMath for uint256; using SafeMath for uint64; using BytesLib for bytes; using BTCUtils for bytes; using BTCUtils for uint256; using ValidateSPV for bytes; using ValidateSPV for bytes32; using DepositStates for DepositUtils.Deposit; struct Deposit { // SET DURING CONSTRUCTION ITBTCSystem tbtcSystem; TBTCToken tbtcToken; IERC721 tbtcDepositToken; FeeRebateToken feeRebateToken; address vendingMachineAddress; uint64 lotSizeSatoshis; uint8 currentState; uint16 signerFeeDivisor; uint16 initialCollateralizedPercent; uint16 undercollateralizedThresholdPercent; uint16 severelyUndercollateralizedThresholdPercent; uint256 keepSetupFee; // SET ON FRAUD uint256 liquidationInitiated; // Timestamp of when liquidation starts uint256 courtesyCallInitiated; // When the courtesy call is issued address payable liquidationInitiator; // written when we request a keep address keepAddress; // The address of our keep contract uint256 signingGroupRequestedAt; // timestamp of signing group request // written when we get a keep result uint256 fundingProofTimerStart; // start of the funding proof period. reused for funding fraud proof period bytes32 signingGroupPubkeyX; // The X coordinate of the signing group's pubkey bytes32 signingGroupPubkeyY; // The Y coordinate of the signing group's pubkey // INITIALLY WRITTEN BY REDEMPTION FLOW address payable redeemerAddress; // The redeemer's address, used as fallback for fraud in redemption bytes redeemerOutputScript; // The redeemer output script uint256 initialRedemptionFee; // the initial fee as requested uint256 latestRedemptionFee; // the fee currently required by a redemption transaction uint256 withdrawalRequestTime; // the most recent withdrawal request timestamp bytes32 lastRequestedDigest; // the digest most recently requested for signing // written when we get funded bytes8 utxoValueBytes; // LE uint. the size of the deposit UTXO in satoshis uint256 fundedAt; // timestamp when funding proof was received bytes utxoOutpoint; // the 36-byte outpoint of the custodied UTXO /// @dev Map of ETH balances an address can withdraw after contract reaches ends-state. mapping(address => uint256) withdrawableAmounts; /// @dev Map of timestamps representing when transaction digests were approved for signing mapping (bytes32 => uint256) approvedDigests; } /// @notice Closes keep associated with the deposit. /// @dev Should be called when the keep is no longer needed and the signing /// group can disband. function closeKeep(DepositUtils.Deposit storage _d) internal { IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); _keep.closeKeep(); } /// @notice Gets the current block difficulty. /// @dev Calls the light relay and gets the current block difficulty. /// @return The difficulty. function currentBlockDifficulty(Deposit storage _d) public view returns (uint256) { return _d.tbtcSystem.fetchRelayCurrentDifficulty(); } /// @notice Gets the previous block difficulty. /// @dev Calls the light relay and gets the previous block difficulty. /// @return The difficulty. function previousBlockDifficulty(Deposit storage _d) public view returns (uint256) { return _d.tbtcSystem.fetchRelayPreviousDifficulty(); } /// @notice Evaluates the header difficulties in a proof. /// @dev Uses the light oracle to source recent difficulty. /// @param _bitcoinHeaders The header chain to evaluate. /// @return True if acceptable, otherwise revert. function evaluateProofDifficulty(Deposit storage _d, bytes memory _bitcoinHeaders) public view { uint256 _reqDiff; uint256 _current = currentBlockDifficulty(_d); uint256 _previous = previousBlockDifficulty(_d); uint256 _firstHeaderDiff = _bitcoinHeaders.extractTarget().calculateDifficulty(); if (_firstHeaderDiff == _current) { _reqDiff = _current; } else if (_firstHeaderDiff == _previous) { _reqDiff = _previous; } else { revert("not at current or previous difficulty"); } uint256 _observedDiff = _bitcoinHeaders.validateHeaderChain(); require(_observedDiff != ValidateSPV.getErrBadLength(), "Invalid length of the headers chain"); require(_observedDiff != ValidateSPV.getErrInvalidChain(), "Invalid headers chain"); require(_observedDiff != ValidateSPV.getErrLowWork(), "Insufficient work in a header"); require( _observedDiff >= _reqDiff.mul(TBTCConstants.getTxProofDifficultyFactor()), "Insufficient accumulated difficulty in header chain" ); } /// @notice Syntactically check an SPV proof for a bitcoin transaction with its hash (ID). /// @dev Stateless SPV Proof verification documented elsewhere (see https://github.com/summa-tx/bitcoin-spv). /// @param _d Deposit storage pointer. /// @param _txId The bitcoin txid of the tx that is purportedly included in the header chain. /// @param _merkleProof The merkle proof of inclusion of the tx in the bitcoin block. /// @param _txIndexInBlock The index of the tx in the Bitcoin block (0-indexed). /// @param _bitcoinHeaders An array of tightly-packed bitcoin headers. function checkProofFromTxId( Deposit storage _d, bytes32 _txId, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public view{ require( _txId.prove( _bitcoinHeaders.extractMerkleRootLE().toBytes32(), _merkleProof, _txIndexInBlock ), "Tx merkle proof is not valid for provided header and txId"); evaluateProofDifficulty(_d, _bitcoinHeaders); } /// @notice Find and validate funding output in transaction output vector using the index. /// @dev Gets `_fundingOutputIndex` output from the output vector and validates if it is /// a p2wpkh output with public key hash matching this deposit's public key hash. /// @param _d Deposit storage pointer. /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC outputs. /// @param _fundingOutputIndex Index of funding output in _txOutputVector. /// @return Funding value. function findAndParseFundingOutput( DepositUtils.Deposit storage _d, bytes memory _txOutputVector, uint8 _fundingOutputIndex ) public view returns (bytes8) { bytes8 _valueBytes; bytes memory _output; // Find the output paying the signer PKH _output = _txOutputVector.extractOutputAtIndex(_fundingOutputIndex); require( keccak256(_output.extractHash()) == keccak256(abi.encodePacked(signerPKH(_d))), "Could not identify output funding the required public key hash" ); require( _output.length == 31 && _output.keccak256Slice(8, 23) == keccak256(abi.encodePacked(hex"160014", signerPKH(_d))), "Funding transaction output type unsupported: only p2wpkh outputs are supported" ); _valueBytes = bytes8(_output.slice(0, 8).toBytes32()); return _valueBytes; } /// @notice Validates the funding tx and parses information from it. /// @dev Takes a pre-parsed transaction and calculates values needed to verify funding. /// @param _d Deposit storage pointer. /// @param _txVersion Transaction version number (4-byte LE). /// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @param _txLocktime Final 4 bytes of the transaction. /// @param _fundingOutputIndex Index of funding output in _txOutputVector (0-indexed). /// @param _merkleProof The merkle proof of transaction inclusion in a block. /// @param _txIndexInBlock Transaction index in the block (0-indexed). /// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, lowest height first. /// @return The 8-byte LE UTXO size in satoshi, the 36byte outpoint. function validateAndParseFundingSPVProof( DepositUtils.Deposit storage _d, bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, uint8 _fundingOutputIndex, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public view returns (bytes8 _valueBytes, bytes memory _utxoOutpoint){ // not external to allow bytes memory parameters require(_txInputVector.validateVin(), "invalid input vector provided"); require(_txOutputVector.validateVout(), "invalid output vector provided"); bytes32 txID = abi.encodePacked(_txVersion, _txInputVector, _txOutputVector, _txLocktime).hash256(); _valueBytes = findAndParseFundingOutput(_d, _txOutputVector, _fundingOutputIndex); require(bytes8LEToUint(_valueBytes) >= _d.lotSizeSatoshis, "Deposit too small"); checkProofFromTxId(_d, txID, _merkleProof, _txIndexInBlock, _bitcoinHeaders); // The utxoOutpoint is the LE txID plus the index of the output as a 4-byte LE int // _fundingOutputIndex is a uint8, so we know it is only 1 byte // Therefore, pad with 3 more bytes _utxoOutpoint = abi.encodePacked(txID, _fundingOutputIndex, hex"000000"); } /// @notice Retreive the remaining term of the deposit /// @dev The return value is not guaranteed since block.timestmap can be lightly manipulated by miners. /// @return The remaining term of the deposit in seconds. 0 if already at term function remainingTerm(DepositUtils.Deposit storage _d) public view returns(uint256){ uint256 endOfTerm = _d.fundedAt.add(TBTCConstants.getDepositTerm()); if(block.timestamp < endOfTerm ) { return endOfTerm.sub(block.timestamp); } return 0; } /// @notice Calculates the amount of value at auction right now. /// @dev We calculate the % of the auction that has elapsed, then scale the value up. /// @param _d Deposit storage pointer. /// @return The value in wei to distribute in the auction at the current time. function auctionValue(Deposit storage _d) external view returns (uint256) { uint256 _elapsed = block.timestamp.sub(_d.liquidationInitiated); uint256 _available = address(this).balance; if (_elapsed > TBTCConstants.getAuctionDuration()) { return _available; } // This should make a smooth flow from base% to 100% uint256 _basePercentage = getAuctionBasePercentage(_d); uint256 _elapsedPercentage = uint256(100).sub(_basePercentage).mul(_elapsed).div(TBTCConstants.getAuctionDuration()); uint256 _percentage = _basePercentage.add(_elapsedPercentage); return _available.mul(_percentage).div(100); } /// @notice Gets the lot size in erc20 decimal places (max 18) /// @return uint256 lot size in 10**18 decimals. function lotSizeTbtc(Deposit storage _d) public view returns (uint256){ return _d.lotSizeSatoshis.mul(TBTCConstants.getSatoshiMultiplier()); } /// @notice Determines the fees due to the signers for work performed. /// @dev Signers are paid based on the TBTC issued. /// @return Accumulated fees in 10**18 decimals. function signerFeeTbtc(Deposit storage _d) public view returns (uint256) { return lotSizeTbtc(_d).div(_d.signerFeeDivisor); } /// @notice Determines the prefix to the compressed public key. /// @dev The prefix encodes the parity of the Y coordinate. /// @param _pubkeyY The Y coordinate of the public key. /// @return The 1-byte prefix for the compressed key. function determineCompressionPrefix(bytes32 _pubkeyY) public pure returns (bytes memory) { if(uint256(_pubkeyY) & 1 == 1) { return hex"03"; // Odd Y } else { return hex"02"; // Even Y } } /// @notice Compresses a public key. /// @dev Converts the 64-byte key to a 33-byte key, bitcoin-style. /// @param _pubkeyX The X coordinate of the public key. /// @param _pubkeyY The Y coordinate of the public key. /// @return The 33-byte compressed pubkey. function compressPubkey(bytes32 _pubkeyX, bytes32 _pubkeyY) public pure returns (bytes memory) { return abi.encodePacked(determineCompressionPrefix(_pubkeyY), _pubkeyX); } /// @notice Returns the packed public key (64 bytes) for the signing group. /// @dev We store it as 2 bytes32, (2 slots) then repack it on demand. /// @return 64 byte public key. function signerPubkey(Deposit storage _d) external view returns (bytes memory) { return abi.encodePacked(_d.signingGroupPubkeyX, _d.signingGroupPubkeyY); } /// @notice Returns the Bitcoin pubkeyhash (hash160) for the signing group. /// @dev This is used in bitcoin output scripts for the signers. /// @return 20-bytes public key hash. function signerPKH(Deposit storage _d) public view returns (bytes20) { bytes memory _pubkey = compressPubkey(_d.signingGroupPubkeyX, _d.signingGroupPubkeyY); bytes memory _digest = _pubkey.hash160(); return bytes20(_digest.toAddress(0)); // dirty solidity hack } /// @notice Returns the size of the deposit UTXO in satoshi. /// @dev We store the deposit as bytes8 to make signature checking easier. /// @return UTXO value in satoshi. function utxoValue(Deposit storage _d) external view returns (uint256) { return bytes8LEToUint(_d.utxoValueBytes); } /// @notice Gets the current price of Bitcoin in Ether. /// @dev Polls the price feed via the system contract. /// @return The current price of 1 sat in wei. function fetchBitcoinPrice(Deposit storage _d) external view returns (uint256) { return _d.tbtcSystem.fetchBitcoinPrice(); } /// @notice Fetches the Keep's bond amount in wei. /// @dev Calls the keep contract to do so. /// @return The amount of bonded ETH in wei. function fetchBondAmount(Deposit storage _d) external view returns (uint256) { IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); return _keep.checkBondAmount(); } /// @notice Convert a LE bytes8 to a uint256. /// @dev Do this by converting to bytes, then reversing endianness, then converting to int. /// @return The uint256 represented in LE by the bytes8. function bytes8LEToUint(bytes8 _b) public pure returns (uint256) { return abi.encodePacked(_b).reverseEndianness().bytesToUint(); } /// @notice Gets timestamp of digest approval for signing. /// @dev Identifies entry in the recorded approvals by keep ID and digest pair. /// @param _digest Digest to check approval for. /// @return Timestamp from the moment of recording the digest for signing. /// Returns 0 if the digest was not approved for signing. function wasDigestApprovedForSigning(Deposit storage _d, bytes32 _digest) external view returns (uint256) { return _d.approvedDigests[_digest]; } /// @notice Looks up the Fee Rebate Token holder. /// @return The current token holder if the Token exists. /// address(0) if the token does not exist. function feeRebateTokenHolder(Deposit storage _d) public view returns (address payable) { address tokenHolder = address(0); if(_d.feeRebateToken.exists(uint256(address(this)))){ tokenHolder = address(uint160(_d.feeRebateToken.ownerOf(uint256(address(this))))); } return address(uint160(tokenHolder)); } /// @notice Looks up the deposit beneficiary by calling the tBTC system. /// @dev We cast the address to a uint256 to match the 721 standard. /// @return The current deposit beneficiary. function depositOwner(Deposit storage _d) public view returns (address payable) { return address(uint160(_d.tbtcDepositToken.ownerOf(uint256(address(this))))); } /// @notice Deletes state after termination of redemption process. /// @dev We keep around the redeemer address so we can pay them out. function redemptionTeardown(Deposit storage _d) public { _d.redeemerOutputScript = ""; _d.initialRedemptionFee = 0; _d.withdrawalRequestTime = 0; _d.lastRequestedDigest = bytes32(0); } /// @notice Get the starting percentage of the bond at auction. /// @dev This will return the same value regardless of collateral price. /// @return The percentage of the InitialCollateralizationPercent that will result /// in a 100% bond value base auction given perfect collateralization. function getAuctionBasePercentage(Deposit storage _d) internal view returns (uint256) { return uint256(10000).div(_d.initialCollateralizedPercent); } /// @notice Seize the signer bond from the keep contract. /// @dev we check our balance before and after. /// @return The amount seized in wei. function seizeSignerBonds(Deposit storage _d) internal returns (uint256) { uint256 _preCallBalance = address(this).balance; IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); _keep.seizeSignerBonds(); uint256 _postCallBalance = address(this).balance; require(_postCallBalance > _preCallBalance, "No funds received, unexpected"); return _postCallBalance.sub(_preCallBalance); } /// @notice Adds a given amount to the withdraw allowance for the address. /// @dev Withdrawals can only happen when a contract is in an end-state. function enableWithdrawal(DepositUtils.Deposit storage _d, address _withdrawer, uint256 _amount) internal { _d.withdrawableAmounts[_withdrawer] = _d.withdrawableAmounts[_withdrawer].add(_amount); } /// @notice Withdraw caller's allowance. /// @dev Withdrawals can only happen when a contract is in an end-state. function withdrawFunds(DepositUtils.Deposit storage _d) internal { uint256 available = _d.withdrawableAmounts[msg.sender]; require(_d.inEndState(), "Contract not yet terminated"); require(available > 0, "Nothing to withdraw"); require(address(this).balance >= available, "Insufficient contract balance"); // zero-out to prevent reentrancy _d.withdrawableAmounts[msg.sender] = 0; /* solium-disable-next-line security/no-call-value */ (bool ok,) = msg.sender.call.value(available)(""); require( ok, "Failed to send withdrawable amount to sender" ); } /// @notice Get the caller's withdraw allowance. /// @return The caller's withdraw allowance in wei. function getWithdrawableAmount(DepositUtils.Deposit storage _d) internal view returns (uint256) { return _d.withdrawableAmounts[msg.sender]; } /// @notice Distributes the fee rebate to the Fee Rebate Token owner. /// @dev Whenever this is called we are shutting down. function distributeFeeRebate(Deposit storage _d) internal { address rebateTokenHolder = feeRebateTokenHolder(_d); // exit the function if there is nobody to send the rebate to if(rebateTokenHolder == address(0)){ return; } // pay out the rebate if it is available if(_d.tbtcToken.balanceOf(address(this)) >= signerFeeTbtc(_d)) { _d.tbtcToken.transfer(rebateTokenHolder, signerFeeTbtc(_d)); } } /// @notice Pushes ether held by the deposit to the signer group. /// @dev Ether is returned to signing group members bonds. /// @param _ethValue The amount of ether to send. function pushFundsToKeepGroup(Deposit storage _d, uint256 _ethValue) internal { require(address(this).balance >= _ethValue, "Not enough funds to send"); if(_ethValue > 0){ IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); _keep.returnPartialSignerBonds.value(_ethValue)(); } } /// @notice Calculate TBTC amount required for redemption by a specified /// _redeemer. If _assumeRedeemerHoldTdt is true, return the /// requirement as if the redeemer holds this deposit's TDT. /// @dev Will revert if redemption is not possible by the current owner and /// _assumeRedeemerHoldsTdt was not set. Setting /// _assumeRedeemerHoldsTdt only when appropriate is the responsibility /// of the caller; as such, this function should NEVER be publicly /// exposed. /// @param _redeemer The account that should be treated as redeeming this /// deposit for the purposes of this calculation. /// @param _assumeRedeemerHoldsTdt If true, the calculation assumes that the /// specified redeemer holds the TDT. If false, the calculation /// checks the deposit owner against the specified _redeemer. Note /// that this parameter should be false for all mutating calls to /// preserve system correctness. /// @return A tuple of the amount the redeemer owes to the deposit to /// initiate redemption, the amount that is owed to the TDT holder /// when redemption is initiated, and the amount that is owed to the /// FRT holder when redemption is initiated. function calculateRedemptionTbtcAmounts( DepositUtils.Deposit storage _d, address _redeemer, bool _assumeRedeemerHoldsTdt ) internal view returns ( uint256 owedToDeposit, uint256 owedToTdtHolder, uint256 owedToFrtHolder ) { bool redeemerHoldsTdt = _assumeRedeemerHoldsTdt || depositOwner(_d) == _redeemer; bool preTerm = remainingTerm(_d) > 0 && !_d.inCourtesyCall(); require( redeemerHoldsTdt || !preTerm, "Only TDT holder can redeem unless deposit is at-term or in COURTESY_CALL" ); bool frtExists = feeRebateTokenHolder(_d) != address(0); bool redeemerHoldsFrt = feeRebateTokenHolder(_d) == _redeemer; uint256 signerFee = signerFeeTbtc(_d); uint256 feeEscrow = calculateRedemptionFeeEscrow( signerFee, preTerm, frtExists, redeemerHoldsTdt, redeemerHoldsFrt ); // Base redemption + fee = total we need to have escrowed to start // redemption. owedToDeposit = calculateBaseRedemptionCharge( lotSizeTbtc(_d), redeemerHoldsTdt ).add(feeEscrow); // Adjust the amount owed to the deposit based on any balance the // deposit already has. uint256 balance = _d.tbtcToken.balanceOf(address(this)); if (owedToDeposit > balance) { owedToDeposit = owedToDeposit.sub(balance); } else { owedToDeposit = 0; } // Pre-term, the FRT rebate is payed out, but if the redeemer holds the // FRT, the amount has already been subtracted from what is owed to the // deposit at this point (by calculateRedemptionFeeEscrow). This allows // the redeemer to simply *not pay* the fee rebate, rather than having // them pay it only to have it immediately returned. if (preTerm && frtExists && !redeemerHoldsFrt) { owedToFrtHolder = signerFee; } // The TDT holder gets any leftover balance. owedToTdtHolder = balance.add(owedToDeposit).sub(signerFee).sub(owedToFrtHolder); return (owedToDeposit, owedToTdtHolder, owedToFrtHolder); } /// @notice Get the base TBTC amount needed to redeem. /// @param _lotSize The lot size to use for the base redemption charge. /// @param _redeemerHoldsTdt True if the redeemer is the TDT holder. /// @return The amount in TBTC. function calculateBaseRedemptionCharge( uint256 _lotSize, bool _redeemerHoldsTdt ) internal pure returns (uint256){ if (_redeemerHoldsTdt) { return 0; } return _lotSize; } /// @notice Get fees owed for redemption /// @param signerFee The value of the signer fee for fee calculations. /// @param _preTerm True if the Deposit is at-term or in courtesy_call. /// @param _frtExists True if the FRT exists. /// @param _redeemerHoldsTdt True if the the redeemer holds the TDT. /// @param _redeemerHoldsFrt True if the redeemer holds the FRT. /// @return The fees owed in TBTC. function calculateRedemptionFeeEscrow( uint256 signerFee, bool _preTerm, bool _frtExists, bool _redeemerHoldsTdt, bool _redeemerHoldsFrt ) internal pure returns (uint256) { // Escrow the fee rebate so the FRT holder can be repaids, unless the // redeemer holds the FRT, in which case we simply don't require the // rebate from them. bool escrowRequiresFeeRebate = _preTerm && _frtExists && ! _redeemerHoldsFrt; bool escrowRequiresFee = _preTerm || // If the FRT exists at term/courtesy call, the fee is // "required", but should already be escrowed before redemption. _frtExists || // The TDT holder always owes fees if there is no FRT. _redeemerHoldsTdt; uint256 feeEscrow = 0; if (escrowRequiresFee) { feeEscrow += signerFee; } if (escrowRequiresFeeRebate) { feeEscrow += signerFee; } return feeEscrow; } } pragma solidity 0.5.17; import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol"; import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol"; import {IBondedECDSAKeep} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeep.sol"; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {DepositUtils} from "./DepositUtils.sol"; import {DepositLiquidation} from "./DepositLiquidation.sol"; import {DepositStates} from "./DepositStates.sol"; import {OutsourceDepositLogging} from "./OutsourceDepositLogging.sol"; import {TBTCConstants} from "../system/TBTCConstants.sol"; library DepositFunding { using SafeMath for uint256; using SafeMath for uint64; using BTCUtils for bytes; using BytesLib for bytes; using DepositUtils for DepositUtils.Deposit; using DepositStates for DepositUtils.Deposit; using DepositLiquidation for DepositUtils.Deposit; using OutsourceDepositLogging for DepositUtils.Deposit; /// @notice Deletes state after funding. /// @dev This is called when we go to ACTIVE or setup fails without fraud. function fundingTeardown(DepositUtils.Deposit storage _d) internal { _d.signingGroupRequestedAt = 0; _d.fundingProofTimerStart = 0; } /// @notice Deletes state after the funding ECDSA fraud process. /// @dev This is only called as we transition to setup failed. function fundingFraudTeardown(DepositUtils.Deposit storage _d) internal { _d.keepAddress = address(0); _d.signingGroupRequestedAt = 0; _d.fundingProofTimerStart = 0; _d.signingGroupPubkeyX = bytes32(0); _d.signingGroupPubkeyY = bytes32(0); } /// @notice Internally called function to set up a newly created Deposit /// instance. This should not be called by developers, use /// `DepositFactory.createDeposit` to create a new deposit. /// @dev If called directly, the transaction will revert since the call will /// be executed on an already set-up instance. /// @param _d Deposit storage pointer. /// @param _lotSizeSatoshis Lot size in satoshis. function initialize( DepositUtils.Deposit storage _d, uint64 _lotSizeSatoshis ) public { require(_d.tbtcSystem.getAllowNewDeposits(), "New deposits aren't allowed."); require(_d.inStart(), "Deposit setup already requested"); _d.lotSizeSatoshis = _lotSizeSatoshis; _d.keepSetupFee = _d.tbtcSystem.getNewDepositFeeEstimate(); // Note: this is a library, and library functions cannot be marked as // payable. Thus, we disable Solium's check that msg.value can only be // used in a payable function---this restriction actually applies to the // caller of this `initialize` function, Deposit.initializeDeposit. /* solium-disable-next-line value-in-payable */ _d.keepAddress = _d.tbtcSystem.requestNewKeep.value(msg.value)( _lotSizeSatoshis, TBTCConstants.getDepositTerm() ); require(_d.fetchBondAmount() >= _d.keepSetupFee, "Insufficient signer bonds to cover setup fee"); _d.signerFeeDivisor = _d.tbtcSystem.getSignerFeeDivisor(); _d.undercollateralizedThresholdPercent = _d.tbtcSystem.getUndercollateralizedThresholdPercent(); _d.severelyUndercollateralizedThresholdPercent = _d.tbtcSystem.getSeverelyUndercollateralizedThresholdPercent(); _d.initialCollateralizedPercent = _d.tbtcSystem.getInitialCollateralizedPercent(); _d.signingGroupRequestedAt = block.timestamp; _d.setAwaitingSignerSetup(); _d.logCreated(_d.keepAddress); } /// @notice Anyone may notify the contract that signing group setup has timed out. /// @param _d Deposit storage pointer. function notifySignerSetupFailed(DepositUtils.Deposit storage _d) external { require(_d.inAwaitingSignerSetup(), "Not awaiting setup"); require( block.timestamp > _d.signingGroupRequestedAt.add(TBTCConstants.getSigningGroupFormationTimeout()), "Signing group formation timeout not yet elapsed" ); // refund the deposit owner the cost to create a new Deposit at the time the Deposit was opened. uint256 _seized = _d.seizeSignerBonds(); if(_seized >= _d.keepSetupFee){ /* solium-disable-next-line security/no-send */ _d.enableWithdrawal(_d.depositOwner(), _d.keepSetupFee); _d.pushFundsToKeepGroup(_seized.sub(_d.keepSetupFee)); } _d.setFailedSetup(); _d.logSetupFailed(); fundingTeardown(_d); } /// @notice we poll the Keep contract to retrieve our pubkey. /// @dev We store the pubkey as 2 bytestrings, X and Y. /// @param _d Deposit storage pointer. /// @return True if successful, otherwise revert. function retrieveSignerPubkey(DepositUtils.Deposit storage _d) public { require(_d.inAwaitingSignerSetup(), "Not currently awaiting signer setup"); bytes memory _publicKey = IBondedECDSAKeep(_d.keepAddress).getPublicKey(); require(_publicKey.length == 64, "public key not set or not 64-bytes long"); _d.signingGroupPubkeyX = _publicKey.slice(0, 32).toBytes32(); _d.signingGroupPubkeyY = _publicKey.slice(32, 32).toBytes32(); require(_d.signingGroupPubkeyY != bytes32(0) && _d.signingGroupPubkeyX != bytes32(0), "Keep returned bad pubkey"); _d.fundingProofTimerStart = block.timestamp; _d.setAwaitingBTCFundingProof(); _d.logRegisteredPubkey( _d.signingGroupPubkeyX, _d.signingGroupPubkeyY); } /// @notice Anyone may notify the contract that the funder has failed to /// prove that they have sent BTC in time. /// @dev This is considered a funder fault, and the funder's payment for /// opening the deposit is not refunded. Reverts if the funding timeout /// has not yet elapsed, or if the deposit is not currently awaiting /// funding proof. /// @param _d Deposit storage pointer. function notifyFundingTimedOut(DepositUtils.Deposit storage _d) external { require(_d.inAwaitingBTCFundingProof(), "Funding timeout has not started"); require( block.timestamp > _d.fundingProofTimerStart.add(TBTCConstants.getFundingTimeout()), "Funding timeout has not elapsed." ); _d.setFailedSetup(); _d.logSetupFailed(); _d.closeKeep(); fundingTeardown(_d); } /// @notice Requests a funder abort for a failed-funding deposit; that is, /// requests return of a sent UTXO to `_abortOutputScript`. This can /// be used for example when a UTXO is sent that is the wrong size /// for the lot. Must be called after setup fails for any reason, /// and imposes no requirement or incentive on the signing group to /// return the UTXO. /// @dev This is a self-admitted funder fault, and should only be callable /// by the TDT holder. /// @param _d Deposit storage pointer. /// @param _abortOutputScript The output script the funder wishes to request /// a return of their UTXO to. function requestFunderAbort( DepositUtils.Deposit storage _d, bytes memory _abortOutputScript ) public { // not external to allow bytes memory parameters require( _d.inFailedSetup(), "The deposit has not failed funding" ); _d.logFunderRequestedAbort(_abortOutputScript); } /// @notice Anyone can provide a signature that was not requested to prove fraud during funding. /// @dev Calls out to the keep to verify if there was fraud. /// @param _d Deposit storage pointer. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. /// @param _signedDigest The digest signed by the signature vrs tuple. /// @param _preimage The sha256 preimage of the digest. /// @return True if successful, otherwise revert. function provideFundingECDSAFraudProof( DepositUtils.Deposit storage _d, uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes memory _preimage ) public { // not external to allow bytes memory parameters require( _d.inAwaitingBTCFundingProof(), "Signer fraud during funding flow only available while awaiting funding" ); _d.submitSignatureFraud(_v, _r, _s, _signedDigest, _preimage); _d.logFraudDuringSetup(); // Allow deposit owner to withdraw seized bonds after contract termination. uint256 _seized = _d.seizeSignerBonds(); _d.enableWithdrawal(_d.depositOwner(), _seized); fundingFraudTeardown(_d); _d.setFailedSetup(); _d.logSetupFailed(); } /// @notice Anyone may notify the deposit of a funding proof to activate the deposit. /// This is the happy-path of the funding flow. It means that we have succeeded. /// @dev Takes a pre-parsed transaction and calculates values needed to verify funding. /// @param _d Deposit storage pointer. /// @param _txVersion Transaction version number (4-byte LE). /// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @param _txLocktime Final 4 bytes of the transaction. /// @param _fundingOutputIndex Index of funding output in _txOutputVector (0-indexed). /// @param _merkleProof The merkle proof of transaction inclusion in a block. /// @param _txIndexInBlock Transaction index in the block (0-indexed). /// @param _bitcoinHeaders Single bytestring of 80-byte bitcoin headers, lowest height first. function provideBTCFundingProof( DepositUtils.Deposit storage _d, bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, uint8 _fundingOutputIndex, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public { // not external to allow bytes memory parameters require(_d.inAwaitingBTCFundingProof(), "Not awaiting funding"); bytes8 _valueBytes; bytes memory _utxoOutpoint; (_valueBytes, _utxoOutpoint) = _d.validateAndParseFundingSPVProof( _txVersion, _txInputVector, _txOutputVector, _txLocktime, _fundingOutputIndex, _merkleProof, _txIndexInBlock, _bitcoinHeaders ); // Write down the UTXO info and set to active. Congratulations :) _d.utxoValueBytes = _valueBytes; _d.utxoOutpoint = _utxoOutpoint; _d.fundedAt = block.timestamp; bytes32 _txid = abi.encodePacked(_txVersion, _txInputVector, _txOutputVector, _txLocktime).hash256(); fundingTeardown(_d); _d.setActive(); _d.logFunded(_txid); } } pragma solidity 0.5.17; import {BTCUtils} from "@summa-tx/bitcoin-spv-sol/contracts/BTCUtils.sol"; import {BytesLib} from "@summa-tx/bitcoin-spv-sol/contracts/BytesLib.sol"; import {ValidateSPV} from "@summa-tx/bitcoin-spv-sol/contracts/ValidateSPV.sol"; import {CheckBitcoinSigs} from "@summa-tx/bitcoin-spv-sol/contracts/CheckBitcoinSigs.sol"; import {IERC721} from "openzeppelin-solidity/contracts/token/ERC721/IERC721.sol"; import {SafeMath} from "openzeppelin-solidity/contracts/math/SafeMath.sol"; import {IBondedECDSAKeep} from "@keep-network/keep-ecdsa/contracts/api/IBondedECDSAKeep.sol"; import {DepositUtils} from "./DepositUtils.sol"; import {DepositStates} from "./DepositStates.sol"; import {OutsourceDepositLogging} from "./OutsourceDepositLogging.sol"; import {TBTCConstants} from "../system/TBTCConstants.sol"; import {TBTCToken} from "../system/TBTCToken.sol"; import {DepositLiquidation} from "./DepositLiquidation.sol"; library DepositRedemption { using SafeMath for uint256; using CheckBitcoinSigs for bytes; using BytesLib for bytes; using BTCUtils for bytes; using ValidateSPV for bytes; using ValidateSPV for bytes32; using DepositUtils for DepositUtils.Deposit; using DepositStates for DepositUtils.Deposit; using DepositLiquidation for DepositUtils.Deposit; using OutsourceDepositLogging for DepositUtils.Deposit; /// @notice Pushes signer fee to the Keep group by transferring it to the Keep address. /// @dev Approves the keep contract, then expects it to call transferFrom. function distributeSignerFee(DepositUtils.Deposit storage _d) internal { IBondedECDSAKeep _keep = IBondedECDSAKeep(_d.keepAddress); _d.tbtcToken.approve(_d.keepAddress, _d.signerFeeTbtc()); _keep.distributeERC20Reward(address(_d.tbtcToken), _d.signerFeeTbtc()); } /// @notice Approves digest for signing by a keep. /// @dev Calls given keep to sign the digest. Records a current timestamp /// for given digest. /// @param _digest Digest to approve. function approveDigest(DepositUtils.Deposit storage _d, bytes32 _digest) internal { IBondedECDSAKeep(_d.keepAddress).sign(_digest); _d.approvedDigests[_digest] = block.timestamp; } /// @notice Handles TBTC requirements for redemption. /// @dev Burns or transfers depending on term and supply-peg impact. /// Once these transfers complete, the deposit balance should be /// sufficient to pay out signer fees once the redemption transaction /// is proven on the Bitcoin side. function performRedemptionTbtcTransfers(DepositUtils.Deposit storage _d) internal { address tdtHolder = _d.depositOwner(); address frtHolder = _d.feeRebateTokenHolder(); address vendingMachineAddress = _d.vendingMachineAddress; ( uint256 tbtcOwedToDeposit, uint256 tbtcOwedToTdtHolder, uint256 tbtcOwedToFrtHolder ) = _d.calculateRedemptionTbtcAmounts(_d.redeemerAddress, false); if(tbtcOwedToDeposit > 0){ _d.tbtcToken.transferFrom(msg.sender, address(this), tbtcOwedToDeposit); } if(tbtcOwedToTdtHolder > 0){ if(tdtHolder == vendingMachineAddress){ _d.tbtcToken.burn(tbtcOwedToTdtHolder); } else { _d.tbtcToken.transfer(tdtHolder, tbtcOwedToTdtHolder); } } if(tbtcOwedToFrtHolder > 0){ _d.tbtcToken.transfer(frtHolder, tbtcOwedToFrtHolder); } } function _requestRedemption( DepositUtils.Deposit storage _d, bytes8 _outputValueBytes, bytes memory _redeemerOutputScript, address payable _redeemer ) internal { require(_d.inRedeemableState(), "Redemption only available from Active or Courtesy state"); bytes memory _output = abi.encodePacked(_outputValueBytes, _redeemerOutputScript); require(_output.extractHash().length > 0, "Output script must be a standard type"); // set redeemerAddress early to enable direct access by other functions _d.redeemerAddress = _redeemer; performRedemptionTbtcTransfers(_d); // Convert the 8-byte LE ints to uint256 uint256 _outputValue = abi.encodePacked(_outputValueBytes).reverseEndianness().bytesToUint(); uint256 _requestedFee = _d.utxoValue().sub(_outputValue); require(_requestedFee >= TBTCConstants.getMinimumRedemptionFee(), "Fee is too low"); require( _requestedFee < _d.utxoValue() / 2, "Initial fee cannot exceed half of the deposit's value" ); // Calculate the sighash bytes32 _sighash = CheckBitcoinSigs.wpkhSpendSighash( _d.utxoOutpoint, _d.signerPKH(), _d.utxoValueBytes, _outputValueBytes, _redeemerOutputScript); // write all request details _d.redeemerOutputScript = _redeemerOutputScript; _d.initialRedemptionFee = _requestedFee; _d.latestRedemptionFee = _requestedFee; _d.withdrawalRequestTime = block.timestamp; _d.lastRequestedDigest = _sighash; approveDigest(_d, _sighash); _d.setAwaitingWithdrawalSignature(); _d.logRedemptionRequested( _redeemer, _sighash, _d.utxoValue(), _redeemerOutputScript, _requestedFee, _d.utxoOutpoint); } /// @notice Anyone can request redemption as long as they can. /// approve the TDT transfer to the final recipient. /// @dev The redeemer specifies details about the Bitcoin redemption tx and pays for the redemption /// on behalf of _finalRecipient. /// @param _d Deposit storage pointer. /// @param _outputValueBytes The 8-byte LE output size. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. /// @param _finalRecipient The address to receive the TDT and later be recorded as deposit redeemer. function transferAndRequestRedemption( DepositUtils.Deposit storage _d, bytes8 _outputValueBytes, bytes memory _redeemerOutputScript, address payable _finalRecipient ) public { // not external to allow bytes memory parameters _d.tbtcDepositToken.transferFrom(msg.sender, _finalRecipient, uint256(address(this))); _requestRedemption(_d, _outputValueBytes, _redeemerOutputScript, _finalRecipient); } /// @notice Only TDT holder can request redemption, /// unless Deposit is expired or in COURTESY_CALL. /// @dev The redeemer specifies details about the Bitcoin redemption transaction. /// @param _d Deposit storage pointer. /// @param _outputValueBytes The 8-byte LE output size. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. function requestRedemption( DepositUtils.Deposit storage _d, bytes8 _outputValueBytes, bytes memory _redeemerOutputScript ) public { // not external to allow bytes memory parameters _requestRedemption(_d, _outputValueBytes, _redeemerOutputScript, msg.sender); } /// @notice Anyone may provide a withdrawal signature if it was requested. /// @dev The signers will be penalized if this (or provideRedemptionProof) is not called. /// @param _d Deposit storage pointer. /// @param _v Signature recovery value. /// @param _r Signature R value. /// @param _s Signature S value. Should be in the low half of secp256k1 curve's order. function provideRedemptionSignature( DepositUtils.Deposit storage _d, uint8 _v, bytes32 _r, bytes32 _s ) external { require(_d.inAwaitingWithdrawalSignature(), "Not currently awaiting a signature"); // If we're outside of the signature window, we COULD punish signers here // Instead, we consider this a no-harm-no-foul situation. // The signers have not stolen funds. Most likely they've just inconvenienced someone // Validate `s` value for a malleability concern described in EIP-2. // Only signatures with `s` value in the lower half of the secp256k1 // curve's order are considered valid. require( uint256(_s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "Malleable signature - s should be in the low half of secp256k1 curve's order" ); // The signature must be valid on the pubkey require( _d.signerPubkey().checkSig( _d.lastRequestedDigest, _v, _r, _s ), "Invalid signature" ); // A signature has been provided, now we wait for fee bump or redemption _d.setAwaitingWithdrawalProof(); _d.logGotRedemptionSignature( _d.lastRequestedDigest, _r, _s); } /// @notice Anyone may notify the contract that a fee bump is needed. /// @dev This sends us back to AWAITING_WITHDRAWAL_SIGNATURE. /// @param _d Deposit storage pointer. /// @param _previousOutputValueBytes The previous output's value. /// @param _newOutputValueBytes The new output's value. function increaseRedemptionFee( DepositUtils.Deposit storage _d, bytes8 _previousOutputValueBytes, bytes8 _newOutputValueBytes ) public { require(_d.inAwaitingWithdrawalProof(), "Fee increase only available after signature provided"); require(block.timestamp >= _d.withdrawalRequestTime.add(TBTCConstants.getIncreaseFeeTimer()), "Fee increase not yet permitted"); uint256 _newOutputValue = checkRelationshipToPrevious(_d, _previousOutputValueBytes, _newOutputValueBytes); // If the fee bump shrinks the UTXO value below the minimum allowed // value, clamp it to that minimum. Further fee bumps will be disallowed // by checkRelationshipToPrevious. if (_newOutputValue < TBTCConstants.getMinimumUtxoValue()) { _newOutputValue = TBTCConstants.getMinimumUtxoValue(); } _d.latestRedemptionFee = _d.utxoValue().sub(_newOutputValue); // Calculate the next sighash bytes32 _sighash = CheckBitcoinSigs.wpkhSpendSighash( _d.utxoOutpoint, _d.signerPKH(), _d.utxoValueBytes, _newOutputValueBytes, _d.redeemerOutputScript); // Ratchet the signature and redemption proof timeouts _d.withdrawalRequestTime = block.timestamp; _d.lastRequestedDigest = _sighash; approveDigest(_d, _sighash); // Go back to waiting for a signature _d.setAwaitingWithdrawalSignature(); _d.logRedemptionRequested( msg.sender, _sighash, _d.utxoValue(), _d.redeemerOutputScript, _d.latestRedemptionFee, _d.utxoOutpoint); } function checkRelationshipToPrevious( DepositUtils.Deposit storage _d, bytes8 _previousOutputValueBytes, bytes8 _newOutputValueBytes ) public view returns (uint256 _newOutputValue){ // Check that we're incrementing the fee by exactly the redeemer's initial fee uint256 _previousOutputValue = DepositUtils.bytes8LEToUint(_previousOutputValueBytes); _newOutputValue = DepositUtils.bytes8LEToUint(_newOutputValueBytes); require(_previousOutputValue.sub(_newOutputValue) == _d.initialRedemptionFee, "Not an allowed fee step"); // Calculate the previous one so we can check that it really is the previous one bytes32 _previousSighash = CheckBitcoinSigs.wpkhSpendSighash( _d.utxoOutpoint, _d.signerPKH(), _d.utxoValueBytes, _previousOutputValueBytes, _d.redeemerOutputScript); require( _d.wasDigestApprovedForSigning(_previousSighash) == _d.withdrawalRequestTime, "Provided previous value does not yield previous sighash" ); } /// @notice Anyone may provide a withdrawal proof to prove redemption. /// @dev The signers will be penalized if this is not called. /// @param _d Deposit storage pointer. /// @param _txVersion Transaction version number (4-byte LE). /// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @param _txLocktime Final 4 bytes of the transaction. /// @param _merkleProof The merkle proof of inclusion of the tx in the bitcoin block. /// @param _txIndexInBlock The index of the tx in the Bitcoin block (0-indexed). /// @param _bitcoinHeaders An array of tightly-packed bitcoin headers. function provideRedemptionProof( DepositUtils.Deposit storage _d, bytes4 _txVersion, bytes memory _txInputVector, bytes memory _txOutputVector, bytes4 _txLocktime, bytes memory _merkleProof, uint256 _txIndexInBlock, bytes memory _bitcoinHeaders ) public { // not external to allow bytes memory parameters bytes32 _txid; uint256 _fundingOutputValue; require(_d.inRedemption(), "Redemption proof only allowed from redemption flow"); _fundingOutputValue = redemptionTransactionChecks(_d, _txInputVector, _txOutputVector); _txid = abi.encodePacked(_txVersion, _txInputVector, _txOutputVector, _txLocktime).hash256(); _d.checkProofFromTxId(_txid, _merkleProof, _txIndexInBlock, _bitcoinHeaders); require((_d.utxoValue().sub(_fundingOutputValue)) <= _d.latestRedemptionFee, "Incorrect fee amount"); // Transfer TBTC to signers and close the keep. distributeSignerFee(_d); _d.closeKeep(); _d.distributeFeeRebate(); // We're done yey! _d.setRedeemed(); _d.redemptionTeardown(); _d.logRedeemed(_txid); } /// @notice Check the redemption transaction input and output vector to ensure the transaction spends /// the correct UTXO and sends value to the appropriate public key hash. /// @dev We only look at the first input and first output. Revert if we find the wrong UTXO or value recipient. /// It's safe to look at only the first input/output as anything that breaks this can be considered fraud /// and can be caught by ECDSAFraudProof. /// @param _d Deposit storage pointer. /// @param _txInputVector All transaction inputs prepended by the number of inputs encoded as a VarInt, max 0xFC(252) inputs. /// @param _txOutputVector All transaction outputs prepended by the number of outputs encoded as a VarInt, max 0xFC(252) outputs. /// @return The value sent to the redeemer's public key hash. function redemptionTransactionChecks( DepositUtils.Deposit storage _d, bytes memory _txInputVector, bytes memory _txOutputVector ) public view returns (uint256) { require(_txInputVector.validateVin(), "invalid input vector provided"); require(_txOutputVector.validateVout(), "invalid output vector provided"); bytes memory _input = _txInputVector.slice(1, _txInputVector.length-1); require( keccak256(_input.extractOutpoint()) == keccak256(_d.utxoOutpoint), "Tx spends the wrong UTXO" ); bytes memory _output = _txOutputVector.slice(1, _txOutputVector.length-1); bytes memory _expectedOutputScript = _d.redeemerOutputScript; require(_output.length - 8 >= _d.redeemerOutputScript.length, "Output script is too short to extract the expected script"); require( keccak256(_output.slice(8, _expectedOutputScript.length)) == keccak256(_expectedOutputScript), "Tx sends value to wrong output script" ); return (uint256(_output.extractValue())); } /// @notice Anyone may notify the contract that the signers have failed to produce a signature. /// @dev This is considered fraud, and is punished. /// @param _d Deposit storage pointer. function notifyRedemptionSignatureTimedOut(DepositUtils.Deposit storage _d) external { require(_d.inAwaitingWithdrawalSignature(), "Not currently awaiting a signature"); require(block.timestamp > _d.withdrawalRequestTime.add(TBTCConstants.getSignatureTimeout()), "Signature timer has not elapsed"); _d.startLiquidation(false); // not fraud, just failure } /// @notice Anyone may notify the contract that the signers have failed to produce a redemption proof. /// @dev This is considered fraud, and is punished. /// @param _d Deposit storage pointer. function notifyRedemptionProofTimedOut(DepositUtils.Deposit storage _d) external { require(_d.inAwaitingWithdrawalProof(), "Not currently awaiting a redemption proof"); require(block.timestamp > _d.withdrawalRequestTime.add(TBTCConstants.getRedemptionProofTimeout()), "Proof timer has not elapsed"); _d.startLiquidation(false); // not fraud, just failure } } pragma solidity 0.5.17; library TBTCConstants { // This is intended to make it easy to update system params // During testing swap this out with another constats contract // System Parameters uint256 public constant BENEFICIARY_FEE_DIVISOR = 1000; // 1/1000 = 10 bps = 0.1% = 0.001 uint256 public constant SATOSHI_MULTIPLIER = 10 ** 10; // multiplier to convert satoshi to TBTC token units uint256 public constant DEPOSIT_TERM_LENGTH = 180 * 24 * 60 * 60; // 180 days in seconds uint256 public constant TX_PROOF_DIFFICULTY_FACTOR = 6; // confirmations on the Bitcoin chain // Redemption Flow uint256 public constant REDEMPTION_SIGNATURE_TIMEOUT = 2 * 60 * 60; // seconds uint256 public constant INCREASE_FEE_TIMER = 4 * 60 * 60; // seconds uint256 public constant REDEMPTION_PROOF_TIMEOUT = 6 * 60 * 60; // seconds uint256 public constant MINIMUM_REDEMPTION_FEE = 2000; // satoshi uint256 public constant MINIMUM_UTXO_VALUE = 2000; // satoshi // Funding Flow uint256 public constant FUNDING_PROOF_TIMEOUT = 3 * 60 * 60; // seconds uint256 public constant FORMATION_TIMEOUT = 3 * 60 * 60; // seconds // Liquidation Flow uint256 public constant COURTESY_CALL_DURATION = 6 * 60 * 60; // seconds uint256 public constant AUCTION_DURATION = 24 * 60 * 60; // seconds // Getters for easy access function getBeneficiaryRewardDivisor() external pure returns (uint256) { return BENEFICIARY_FEE_DIVISOR; } function getSatoshiMultiplier() external pure returns (uint256) { return SATOSHI_MULTIPLIER; } function getDepositTerm() external pure returns (uint256) { return DEPOSIT_TERM_LENGTH; } function getTxProofDifficultyFactor() external pure returns (uint256) { return TX_PROOF_DIFFICULTY_FACTOR; } function getSignatureTimeout() external pure returns (uint256) { return REDEMPTION_SIGNATURE_TIMEOUT; } function getIncreaseFeeTimer() external pure returns (uint256) { return INCREASE_FEE_TIMER; } function getRedemptionProofTimeout() external pure returns (uint256) { return REDEMPTION_PROOF_TIMEOUT; } function getMinimumRedemptionFee() external pure returns (uint256) { return MINIMUM_REDEMPTION_FEE; } function getMinimumUtxoValue() external pure returns (uint256) { return MINIMUM_UTXO_VALUE; } function getFundingTimeout() external pure returns (uint256) { return FUNDING_PROOF_TIMEOUT; } function getSigningGroupFormationTimeout() external pure returns (uint256) { return FORMATION_TIMEOUT; } function getCourtesyCallTimeout() external pure returns (uint256) { return COURTESY_CALL_DURATION; } function getAuctionDuration() external pure returns (uint256) { return AUCTION_DURATION; } } pragma solidity 0.5.17; import {DepositLog} from "../DepositLog.sol"; import {DepositUtils} from "./DepositUtils.sol"; library OutsourceDepositLogging { /// @notice Fires a Created event. /// @dev `DepositLog.logCreated` fires a Created event with /// _keepAddress, msg.sender and block.timestamp. /// msg.sender will be the calling Deposit's address. /// @param _keepAddress The address of the associated keep. function logCreated(DepositUtils.Deposit storage _d, address _keepAddress) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logCreated(_keepAddress); } /// @notice Fires a RedemptionRequested event. /// @dev This is the only event without an explicit timestamp. /// @param _redeemer The ethereum address of the redeemer. /// @param _digest The calculated sighash digest. /// @param _utxoValue The size of the utxo in sat. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. /// @param _requestedFee The redeemer or bump-system specified fee. /// @param _outpoint The 36 byte outpoint. /// @return True if successful, else revert. function logRedemptionRequested( DepositUtils.Deposit storage _d, address _redeemer, bytes32 _digest, uint256 _utxoValue, bytes memory _redeemerOutputScript, uint256 _requestedFee, bytes memory _outpoint ) public { // not external to allow bytes memory parameters DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logRedemptionRequested( _redeemer, _digest, _utxoValue, _redeemerOutputScript, _requestedFee, _outpoint ); } /// @notice Fires a GotRedemptionSignature event. /// @dev We append the sender, which is the deposit contract that called. /// @param _digest Signed digest. /// @param _r Signature r value. /// @param _s Signature s value. /// @return True if successful, else revert. function logGotRedemptionSignature( DepositUtils.Deposit storage _d, bytes32 _digest, bytes32 _r, bytes32 _s ) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logGotRedemptionSignature( _digest, _r, _s ); } /// @notice Fires a RegisteredPubkey event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logRegisteredPubkey( DepositUtils.Deposit storage _d, bytes32 _signingGroupPubkeyX, bytes32 _signingGroupPubkeyY ) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logRegisteredPubkey( _signingGroupPubkeyX, _signingGroupPubkeyY); } /// @notice Fires a SetupFailed event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logSetupFailed(DepositUtils.Deposit storage _d) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logSetupFailed(); } /// @notice Fires a FunderAbortRequested event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logFunderRequestedAbort( DepositUtils.Deposit storage _d, bytes memory _abortOutputScript ) public { // not external to allow bytes memory parameters DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logFunderRequestedAbort(_abortOutputScript); } /// @notice Fires a FraudDuringSetup event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logFraudDuringSetup(DepositUtils.Deposit storage _d) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logFraudDuringSetup(); } /// @notice Fires a Funded event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logFunded(DepositUtils.Deposit storage _d, bytes32 _txid) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logFunded(_txid); } /// @notice Fires a CourtesyCalled event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logCourtesyCalled(DepositUtils.Deposit storage _d) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logCourtesyCalled(); } /// @notice Fires a StartedLiquidation event. /// @dev We append the sender, which is the deposit contract that called. /// @param _wasFraud True if liquidating for fraud. function logStartedLiquidation(DepositUtils.Deposit storage _d, bool _wasFraud) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logStartedLiquidation(_wasFraud); } /// @notice Fires a Redeemed event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logRedeemed(DepositUtils.Deposit storage _d, bytes32 _txid) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logRedeemed(_txid); } /// @notice Fires a Liquidated event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logLiquidated(DepositUtils.Deposit storage _d) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logLiquidated(); } /// @notice Fires a ExitedCourtesyCall event. /// @dev The logger is on a system contract, so all logs from all deposits are from the same address. function logExitedCourtesyCall(DepositUtils.Deposit storage _d) external { DepositLog _logger = DepositLog(address(_d.tbtcSystem)); _logger.logExitedCourtesyCall(); } } pragma solidity 0.5.17; import {TBTCDepositToken} from "./system/TBTCDepositToken.sol"; // solium-disable function-order // Below, a few functions must be public to allow bytes memory parameters, but // their being so triggers errors because public functions should be grouped // below external functions. Since these would be external if it were possible, // we ignore the issue. contract DepositLog { /* Logging philosophy: Every state transition should fire a log That log should have ALL necessary info for off-chain actors Everyone should be able to ENTIRELY rely on log messages */ // `TBTCDepositToken` mints a token for every new Deposit. // If a token exists for a given ID, we know it is a valid Deposit address. TBTCDepositToken tbtcDepositToken; // This event is fired when we init the deposit event Created( address indexed _depositContractAddress, address indexed _keepAddress, uint256 _timestamp ); // This log event contains all info needed to rebuild the redemption tx // We index on request and signers and digest event RedemptionRequested( address indexed _depositContractAddress, address indexed _requester, bytes32 indexed _digest, uint256 _utxoValue, bytes _redeemerOutputScript, uint256 _requestedFee, bytes _outpoint ); // This log event contains all info needed to build a witnes // We index the digest so that we can search events for the other log event GotRedemptionSignature( address indexed _depositContractAddress, bytes32 indexed _digest, bytes32 _r, bytes32 _s, uint256 _timestamp ); // This log is fired when the signing group returns a public key event RegisteredPubkey( address indexed _depositContractAddress, bytes32 _signingGroupPubkeyX, bytes32 _signingGroupPubkeyY, uint256 _timestamp ); // This event is fired when we enter the FAILED_SETUP state for any reason event SetupFailed( address indexed _depositContractAddress, uint256 _timestamp ); // This event is fired when a funder requests funder abort after // FAILED_SETUP has been reached. Funder abort is a voluntary signer action // to return UTXO(s) that were sent to a signer-controlled wallet despite // the funding proofs having failed. event FunderAbortRequested( address indexed _depositContractAddress, bytes _abortOutputScript ); // This event is fired when we detect an ECDSA fraud before seeing a funding proof event FraudDuringSetup( address indexed _depositContractAddress, uint256 _timestamp ); // This event is fired when we enter the ACTIVE state event Funded( address indexed _depositContractAddress, bytes32 indexed _txid, uint256 _timestamp ); // This event is called when we enter the COURTESY_CALL state event CourtesyCalled( address indexed _depositContractAddress, uint256 _timestamp ); // This event is fired when we go from COURTESY_CALL to ACTIVE event ExitedCourtesyCall( address indexed _depositContractAddress, uint256 _timestamp ); // This log event is fired when liquidation event StartedLiquidation( address indexed _depositContractAddress, bool _wasFraud, uint256 _timestamp ); // This event is fired when the Redemption SPV proof is validated event Redeemed( address indexed _depositContractAddress, bytes32 indexed _txid, uint256 _timestamp ); // This event is fired when Liquidation is completed event Liquidated( address indexed _depositContractAddress, uint256 _timestamp ); // // Logging // /// @notice Fires a Created event. /// @dev We append the sender, which is the deposit contract that called. /// @param _keepAddress The address of the associated keep. /// @return True if successful, else revert. function logCreated(address _keepAddress) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit Created(msg.sender, _keepAddress, block.timestamp); } /// @notice Fires a RedemptionRequested event. /// @dev This is the only event without an explicit timestamp. /// @param _requester The ethereum address of the requester. /// @param _digest The calculated sighash digest. /// @param _utxoValue The size of the utxo in sat. /// @param _redeemerOutputScript The redeemer's length-prefixed output script. /// @param _requestedFee The requester or bump-system specified fee. /// @param _outpoint The 36 byte outpoint. /// @return True if successful, else revert. function logRedemptionRequested( address _requester, bytes32 _digest, uint256 _utxoValue, bytes memory _redeemerOutputScript, uint256 _requestedFee, bytes memory _outpoint ) public { // not external to allow bytes memory parameters require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit RedemptionRequested( msg.sender, _requester, _digest, _utxoValue, _redeemerOutputScript, _requestedFee, _outpoint ); } /// @notice Fires a GotRedemptionSignature event. /// @dev We append the sender, which is the deposit contract that called. /// @param _digest signed digest. /// @param _r signature r value. /// @param _s signature s value. function logGotRedemptionSignature(bytes32 _digest, bytes32 _r, bytes32 _s) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit GotRedemptionSignature( msg.sender, _digest, _r, _s, block.timestamp ); } /// @notice Fires a RegisteredPubkey event. /// @dev We append the sender, which is the deposit contract that called. function logRegisteredPubkey( bytes32 _signingGroupPubkeyX, bytes32 _signingGroupPubkeyY ) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit RegisteredPubkey( msg.sender, _signingGroupPubkeyX, _signingGroupPubkeyY, block.timestamp ); } /// @notice Fires a SetupFailed event. /// @dev We append the sender, which is the deposit contract that called. function logSetupFailed() external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit SetupFailed(msg.sender, block.timestamp); } /// @notice Fires a FunderAbortRequested event. /// @dev We append the sender, which is the deposit contract that called. function logFunderRequestedAbort(bytes memory _abortOutputScript) public { // not external to allow bytes memory parameters require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit FunderAbortRequested(msg.sender, _abortOutputScript); } /// @notice Fires a FraudDuringSetup event. /// @dev We append the sender, which is the deposit contract that called. function logFraudDuringSetup() external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit FraudDuringSetup(msg.sender, block.timestamp); } /// @notice Fires a Funded event. /// @dev We append the sender, which is the deposit contract that called. function logFunded(bytes32 _txid) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit Funded(msg.sender, _txid, block.timestamp); } /// @notice Fires a CourtesyCalled event. /// @dev We append the sender, which is the deposit contract that called. function logCourtesyCalled() external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit CourtesyCalled(msg.sender, block.timestamp); } /// @notice Fires a StartedLiquidation event. /// @dev We append the sender, which is the deposit contract that called. /// @param _wasFraud True if liquidating for fraud. function logStartedLiquidation(bool _wasFraud) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit StartedLiquidation(msg.sender, _wasFraud, block.timestamp); } /// @notice Fires a Redeemed event /// @dev We append the sender, which is the deposit contract that called. function logRedeemed(bytes32 _txid) external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit Redeemed(msg.sender, _txid, block.timestamp); } /// @notice Fires a Liquidated event /// @dev We append the sender, which is the deposit contract that called. function logLiquidated() external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit Liquidated(msg.sender, block.timestamp); } /// @notice Fires a ExitedCourtesyCall event /// @dev We append the sender, which is the deposit contract that called. function logExitedCourtesyCall() external { require( approvedToLog(msg.sender), "Caller is not approved to log events" ); emit ExitedCourtesyCall(msg.sender, block.timestamp); } /// @notice Sets the tbtcDepositToken contract. /// @dev The contract is used by `approvedToLog` to check if the /// caller is a Deposit contract. This should only be called once. /// @param _tbtcDepositTokenAddress The address of the tbtcDepositToken. function setTbtcDepositToken(TBTCDepositToken _tbtcDepositTokenAddress) internal { require( address(tbtcDepositToken) == address(0), "tbtcDepositToken is already set" ); tbtcDepositToken = _tbtcDepositTokenAddress; } // // AUTH // /// @notice Checks if an address is an allowed logger. /// @dev checks tbtcDepositToken to see if the caller represents /// an existing deposit. /// We don't require this, so deposits are not bricked if the system borks. /// @param _caller The address of the calling contract. /// @return True if approved, otherwise false. function approvedToLog(address _caller) public view returns (bool) { return tbtcDepositToken.exists(uint256(_caller)); } } pragma solidity 0.5.17; import {ERC721Metadata} from "openzeppelin-solidity/contracts/token/ERC721/ERC721Metadata.sol"; import {DepositFactoryAuthority} from "./DepositFactoryAuthority.sol"; import {ITokenRecipient} from "../interfaces/ITokenRecipient.sol"; /// @title tBTC Deposit Token for tracking deposit ownership /// @notice The tBTC Deposit Token, commonly referenced as the TDT, is an /// ERC721 non-fungible token whose ownership reflects the ownership /// of its corresponding deposit. Each deposit has one TDT, and vice /// versa. Owning a TDT is equivalent to owning its corresponding /// deposit. TDTs can be transferred freely. tBTC's VendingMachine /// contract takes ownership of TDTs and in exchange returns fungible /// TBTC tokens whose value is backed 1-to-1 by the corresponding /// deposit's BTC. /// @dev Currently, TDTs are minted using the uint256 casting of the /// corresponding deposit contract's address. That is, the TDT's id is /// convertible to the deposit's address and vice versa. TDTs are minted /// automatically by the factory during each deposit's initialization. See /// DepositFactory.createNewDeposit() for more info on how the TDT is minted. contract TBTCDepositToken is ERC721Metadata, DepositFactoryAuthority { constructor(address _depositFactoryAddress) ERC721Metadata("tBTC Deposit Token", "TDT") public { initialize(_depositFactoryAddress); } /// @dev Mints a new token. /// Reverts if the given token ID already exists. /// @param _to The address that will own the minted token /// @param _tokenId uint256 ID of the token to be minted function mint(address _to, uint256 _tokenId) external onlyFactory { _mint(_to, _tokenId); } /// @dev Returns whether the specified token exists. /// @param _tokenId uint256 ID of the token to query the existence of. /// @return bool whether the token exists. function exists(uint256 _tokenId) external view returns (bool) { return _exists(_tokenId); } /// @notice Allow another address to spend on the caller's behalf. /// Set allowance for other address and notify. /// Allows `_spender` to transfer the specified TDT /// on your behalf and then ping the contract about it. /// @dev The `_spender` should implement the `ITokenRecipient` /// interface below to receive approval notifications. /// @param _spender `ITokenRecipient`-conforming contract authorized to /// operate on the approved token. /// @param _tdtId The TDT they can spend. /// @param _extraData Extra information to send to the approved contract. function approveAndCall( ITokenRecipient _spender, uint256 _tdtId, bytes memory _extraData ) public returns (bool) { // not external to allow bytes memory parameters approve(address(_spender), _tdtId); _spender.receiveApproval(msg.sender, _tdtId, address(this), _extraData); return true; } } /* Authored by Satoshi Nakamoto 🤪 */ pragma solidity 0.5.17; import {ERC20} from "openzeppelin-solidity/contracts/token/ERC20/ERC20.sol"; import {ERC20Detailed} from "openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol"; import {VendingMachineAuthority} from "./VendingMachineAuthority.sol"; import {ITokenRecipient} from "../interfaces/ITokenRecipient.sol"; /// @title TBTC Token. /// @notice This is the TBTC ERC20 contract. /// @dev Tokens can only be minted by the `VendingMachine` contract. contract TBTCToken is ERC20Detailed, ERC20, VendingMachineAuthority { /// @dev Constructor, calls ERC20Detailed constructor to set Token info /// ERC20Detailed(TokenName, TokenSymbol, NumberOfDecimals) constructor(address _VendingMachine) ERC20Detailed("tBTC", "TBTC", 18) VendingMachineAuthority(_VendingMachine) public { // solium-disable-previous-line no-empty-blocks } /// @dev Mints an amount of the token and assigns it to an account. /// Uses the internal _mint function. /// @param _account The account that will receive the created tokens. /// @param _amount The amount of tokens that will be created. function mint(address _account, uint256 _amount) public onlyVendingMachine returns (bool) { // NOTE: this is a public function with unchecked minting. _mint(_account, _amount); return true; } /// @dev Burns an amount of the token from the given account's balance. /// deducting from the sender's allowance for said account. /// Uses the internal _burn function. /// @param _account The account whose tokens will be burnt. /// @param _amount The amount of tokens that will be burnt. function burnFrom(address _account, uint256 _amount) public { _burnFrom(_account, _amount); } /// @dev Destroys `amount` tokens from `msg.sender`, reducing the /// total supply. /// @param _amount The amount of tokens that will be burnt. function burn(uint256 _amount) public { _burn(msg.sender, _amount); } /// @notice Set allowance for other address and notify. /// Allows `_spender` to spend no more than `_value` /// tokens on your behalf and then ping the contract about /// it. /// @dev The `_spender` should implement the `ITokenRecipient` /// interface to receive approval notifications. /// @param _spender Address of contract authorized to spend. /// @param _value The max amount they can spend. /// @param _extraData Extra information to send to the approved contract. /// @return true if the `_spender` was successfully approved and acted on /// the approval, false (or revert) otherwise. function approveAndCall(ITokenRecipient _spender, uint256 _value, bytes memory _extraData) public returns (bool) { if (approve(address(_spender), _value)) { _spender.receiveApproval(msg.sender, _value, address(this), _extraData); return true; } return false; } } pragma solidity 0.5.17; /// @title Deposit Factory Authority /// @notice Contract to secure function calls to the Deposit Factory. /// @dev Secured by setting the depositFactory address and using the onlyFactory /// modifier on functions requiring restriction. contract DepositFactoryAuthority { bool internal _initialized = false; address internal _depositFactory; /// @notice Set the address of the System contract on contract /// initialization. /// @dev Since this function is not access-controlled, it should be called /// transactionally with contract instantiation. In cases where a /// regular contract directly inherits from DepositFactoryAuthority, /// that should happen in the constructor. In cases where the inheritor /// is binstead used via a clone factory, the same function that /// creates a new clone should also trigger initialization. function initialize(address _factory) public { require(_factory != address(0), "Factory cannot be the zero address."); require(! _initialized, "Factory can only be initialized once."); _depositFactory = _factory; _initialized = true; } /// @notice Function modifier ensures modified function is only called by set deposit factory. modifier onlyFactory(){ require(_initialized, "Factory initialization must have been called."); require(msg.sender == _depositFactory, "Caller must be depositFactory contract"); _; } } pragma solidity 0.5.17; /// @title TBTC System Authority. /// @notice Contract to secure function calls to the TBTC System contract. /// @dev The `TBTCSystem` contract address is passed as a constructor parameter. contract TBTCSystemAuthority { address internal tbtcSystemAddress; /// @notice Set the address of the System contract on contract initialization. constructor(address _tbtcSystemAddress) public { tbtcSystemAddress = _tbtcSystemAddress; } /// @notice Function modifier ensures modified function is only called by TBTCSystem. modifier onlyTbtcSystem(){ require(msg.sender == tbtcSystemAddress, "Caller must be tbtcSystem contract"); _; } } pragma solidity 0.5.17; /// @title Vending Machine Authority. /// @notice Contract to secure function calls to the Vending Machine. /// @dev Secured by setting the VendingMachine address and using the /// onlyVendingMachine modifier on functions requiring restriction. contract VendingMachineAuthority { address internal VendingMachine; constructor(address _vendingMachine) public { VendingMachine = _vendingMachine; } /// @notice Function modifier ensures modified function caller address is the vending machine. modifier onlyVendingMachine() { require(msg.sender == VendingMachine, "caller must be the vending machine"); _; } } pragma solidity 0.5.17; /// @title Interface of recipient contract for `approveAndCall` pattern. /// Implementors will be able to be used in an `approveAndCall` /// interaction with a supporting contract, such that a token approval /// can call the contract acting on that approval in a single /// transaction. /// /// See the `FundingScript` and `RedemptionScript` contracts as examples. interface ITokenRecipient { /// Typically called from a token contract's `approveAndCall` method, this /// method will receive the original owner of the token (`_from`), the /// transferred `_value` (in the case of an ERC721, the token id), the token /// address (`_token`), and a blob of `_extraData` that is informally /// specified by the implementor of this method as a way to communicate /// additional parameters. /// /// Token calls to `receiveApproval` should revert if `receiveApproval` /// reverts, and reverts should remove the approval. /// /// @param _from The original owner of the token approved for transfer. /// @param _value For an ERC20, the amount approved for transfer; for an /// ERC721, the id of the token approved for transfer. /// @param _token The address of the contract for the token whose transfer /// was approved. /// @param _extraData An additional data blob forwarded unmodified through /// `approveAndCall`, used to allow the token owner to pass /// additional parameters and data to this method. The structure of /// the extra data is informally specified by the implementor of /// this interface. function receiveApproval( address _from, uint256 _value, address _token, bytes calldata _extraData ) external; } pragma solidity 0.5.17; import "openzeppelin-solidity/contracts/token/ERC721/ERC721Metadata.sol"; import "./VendingMachineAuthority.sol"; /// @title Fee Rebate Token /// @notice The Fee Rebate Token (FRT) is a non fungible token (ERC721) /// the ID of which corresponds to a given deposit address. /// If the corresponding deposit is still active, ownership of this token /// could result in reimbursement of the signer fee paid to open the deposit. /// @dev This token is minted automatically when a TDT (`TBTCDepositToken`) /// is exchanged for TBTC (`TBTCToken`) via the Vending Machine (`VendingMachine`). /// When the Deposit is redeemed, the TDT holder will be reimbursed /// the signer fee if the redeemer is not the TDT holder and Deposit is not /// at-term or in COURTESY_CALL. contract FeeRebateToken is ERC721Metadata, VendingMachineAuthority { constructor(address _vendingMachine) ERC721Metadata("tBTC Fee Rebate Token", "FRT") VendingMachineAuthority(_vendingMachine) public { // solium-disable-previous-line no-empty-blocks } /// @dev Mints a new token. /// Reverts if the given token ID already exists. /// @param _to The address that will own the minted token. /// @param _tokenId uint256 ID of the token to be minted. function mint(address _to, uint256 _tokenId) external onlyVendingMachine { _mint(_to, _tokenId); } /// @dev Returns whether the specified token exists. /// @param _tokenId uint256 ID of the token to query the existence of. /// @return bool whether the token exists. function exists(uint256 _tokenId) external view returns (bool) { return _exists(_tokenId); } } /** ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ Trust math, not hardware. */ pragma solidity 0.5.17; /// @title ECDSA Keep /// @notice Contract reflecting an ECDSA keep. contract IBondedECDSAKeep { /// @notice Returns public key of this keep. /// @return Keeps's public key. function getPublicKey() external view returns (bytes memory); /// @notice Returns the amount of the keep's ETH bond in wei. /// @return The amount of the keep's ETH bond in wei. function checkBondAmount() external view returns (uint256); /// @notice Calculates a signature over provided digest by the keep. Note that /// signatures from the keep not explicitly requested by calling `sign` /// will be provable as fraud via `submitSignatureFraud`. /// @param _digest Digest to be signed. function sign(bytes32 _digest) external; /// @notice Distributes ETH reward evenly across keep signer beneficiaries. /// @dev Only the value passed to this function is distributed. function distributeETHReward() external payable; /// @notice Distributes ERC20 reward evenly across keep signer beneficiaries. /// @dev This works with any ERC20 token that implements a transferFrom /// function. /// This function only has authority over pre-approved /// token amount. We don't explicitly check for allowance, SafeMath /// subtraction overflow is enough protection. /// @param _tokenAddress Address of the ERC20 token to distribute. /// @param _value Amount of ERC20 token to distribute. function distributeERC20Reward(address _tokenAddress, uint256 _value) external; /// @notice Seizes the signers' ETH bonds. After seizing bonds keep is /// terminated so it will no longer respond to signing requests. Bonds can /// be seized only when there is no signing in progress or requested signing /// process has timed out. This function seizes all of signers' bonds. /// The application may decide to return part of bonds later after they are /// processed using returnPartialSignerBonds function. function seizeSignerBonds() external; /// @notice Returns partial signer's ETH bonds to the pool as an unbounded /// value. This function is called after bonds have been seized and processed /// by the privileged application after calling seizeSignerBonds function. /// It is entirely up to the application if a part of signers' bonds is /// returned. The application may decide for that but may also decide to /// seize bonds and do not return anything. function returnPartialSignerBonds() external payable; /// @notice Submits a fraud proof for a valid signature from this keep that was /// not first approved via a call to sign. /// @dev The function expects the signed digest to be calculated as a sha256 /// hash of the preimage: `sha256(_preimage)`. /// @param _v Signature's header byte: `27 + recoveryID`. /// @param _r R part of ECDSA signature. /// @param _s S part of ECDSA signature. /// @param _signedDigest Digest for the provided signature. Result of hashing /// the preimage. /// @param _preimage Preimage of the hashed message. /// @return True if fraud, error otherwise. function submitSignatureFraud( uint8 _v, bytes32 _r, bytes32 _s, bytes32 _signedDigest, bytes calldata _preimage ) external returns (bool _isFraud); /// @notice Closes keep when no longer needed. Releases bonds to the keep /// members. Keep can be closed only when there is no signing in progress or /// requested signing process has timed out. /// @dev The function can be called only by the owner of the keep and only /// if the keep has not been already closed. function closeKeep() external; } pragma solidity ^0.5.10; /** @title ValidateSPV*/ /** @author Summa (https://summa.one) */ import {BytesLib} from "./BytesLib.sol"; import {SafeMath} from "./SafeMath.sol"; import {BTCUtils} from "./BTCUtils.sol"; library ValidateSPV { using BTCUtils for bytes; using BTCUtils for uint256; using BytesLib for bytes; using SafeMath for uint256; enum InputTypes { NONE, LEGACY, COMPATIBILITY, WITNESS } enum OutputTypes { NONE, WPKH, WSH, OP_RETURN, PKH, SH, NONSTANDARD } uint256 constant ERR_BAD_LENGTH = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; uint256 constant ERR_INVALID_CHAIN = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe; uint256 constant ERR_LOW_WORK = 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd; function getErrBadLength() internal pure returns (uint256) { return ERR_BAD_LENGTH; } function getErrInvalidChain() internal pure returns (uint256) { return ERR_INVALID_CHAIN; } function getErrLowWork() internal pure returns (uint256) { return ERR_LOW_WORK; } /// @notice Validates a tx inclusion in the block /// @dev `index` is not a reliable indicator of location within a block /// @param _txid The txid (LE) /// @param _merkleRoot The merkle root (as in the block header) /// @param _intermediateNodes The proof's intermediate nodes (digests between leaf and root) /// @param _index The leaf's index in the tree (0-indexed) /// @return true if fully valid, false otherwise function prove( bytes32 _txid, bytes32 _merkleRoot, bytes memory _intermediateNodes, uint _index ) internal pure returns (bool) { // Shortcut the empty-block case if (_txid == _merkleRoot && _index == 0 && _intermediateNodes.length == 0) { return true; } bytes memory _proof = abi.encodePacked(_txid, _intermediateNodes, _merkleRoot); // If the Merkle proof failed, bubble up error return _proof.verifyHash256Merkle(_index); } /// @notice Hashes transaction to get txid /// @dev Supports Legacy and Witness /// @param _version 4-bytes version /// @param _vin Raw bytes length-prefixed input vector /// @param _vout Raw bytes length-prefixed output vector /// @param _locktime 4-byte tx locktime /// @return 32-byte transaction id, little endian function calculateTxId( bytes memory _version, bytes memory _vin, bytes memory _vout, bytes memory _locktime ) internal pure returns (bytes32) { // Get transaction hash double-Sha256(version + nIns + inputs + nOuts + outputs + locktime) return abi.encodePacked(_version, _vin, _vout, _locktime).hash256(); } /// @notice Checks validity of header chain /// @notice Compares the hash of each header to the prevHash in the next header /// @param _headers Raw byte array of header chain /// @return The total accumulated difficulty of the header chain, or an error code function validateHeaderChain(bytes memory _headers) internal view returns (uint256 _totalDifficulty) { // Check header chain length if (_headers.length % 80 != 0) {return ERR_BAD_LENGTH;} // Initialize header start index bytes32 _digest; _totalDifficulty = 0; for (uint256 _start = 0; _start < _headers.length; _start += 80) { // ith header start index and ith header bytes memory _header = _headers.slice(_start, 80); // After the first header, check that headers are in a chain if (_start != 0) { if (!validateHeaderPrevHash(_header, _digest)) {return ERR_INVALID_CHAIN;} } // ith header target uint256 _target = _header.extractTarget(); // Require that the header has sufficient work _digest = _header.hash256View(); if(uint256(_digest).reverseUint256() > _target) { return ERR_LOW_WORK; } // Add ith header difficulty to difficulty sum _totalDifficulty = _totalDifficulty.add(_target.calculateDifficulty()); } } /// @notice Checks validity of header work /// @param _digest Header digest /// @param _target The target threshold /// @return true if header work is valid, false otherwise function validateHeaderWork(bytes32 _digest, uint256 _target) internal pure returns (bool) { if (_digest == bytes32(0)) {return false;} return (abi.encodePacked(_digest).reverseEndianness().bytesToUint() < _target); } /// @notice Checks validity of header chain /// @dev Compares current header prevHash to previous header's digest /// @param _header The raw bytes header /// @param _prevHeaderDigest The previous header's digest /// @return true if the connect is valid, false otherwise function validateHeaderPrevHash(bytes memory _header, bytes32 _prevHeaderDigest) internal pure returns (bool) { // Extract prevHash of current header bytes32 _prevHash = _header.extractPrevBlockLE().toBytes32(); // Compare prevHash of current header to previous header's digest if (_prevHash != _prevHeaderDigest) {return false;} return true; } } pragma solidity ^0.5.10; /** @title CheckBitcoinSigs */ /** @author Summa (https://summa.one) */ import {BytesLib} from "./BytesLib.sol"; import {BTCUtils} from "./BTCUtils.sol"; library CheckBitcoinSigs { using BytesLib for bytes; using BTCUtils for bytes; /// @notice Derives an Ethereum Account address from a pubkey /// @dev The address is the last 20 bytes of the keccak256 of the address /// @param _pubkey The public key X & Y. Unprefixed, as a 64-byte array /// @return The account address function accountFromPubkey(bytes memory _pubkey) internal pure returns (address) { require(_pubkey.length == 64, "Pubkey must be 64-byte raw, uncompressed key."); // keccak hash of uncompressed unprefixed pubkey bytes32 _digest = keccak256(_pubkey); return address(uint256(_digest)); } /// @notice Calculates the p2wpkh output script of a pubkey /// @dev Compresses keys to 33 bytes as required by Bitcoin /// @param _pubkey The public key, compressed or uncompressed /// @return The p2wkph output script function p2wpkhFromPubkey(bytes memory _pubkey) internal pure returns (bytes memory) { bytes memory _compressedPubkey; uint8 _prefix; if (_pubkey.length == 64) { _prefix = uint8(_pubkey[_pubkey.length - 1]) % 2 == 1 ? 3 : 2; _compressedPubkey = abi.encodePacked(_prefix, _pubkey.slice(0, 32)); } else if (_pubkey.length == 65) { _prefix = uint8(_pubkey[_pubkey.length - 1]) % 2 == 1 ? 3 : 2; _compressedPubkey = abi.encodePacked(_prefix, _pubkey.slice(1, 32)); } else { _compressedPubkey = _pubkey; } require(_compressedPubkey.length == 33, "Witness PKH requires compressed keys"); bytes memory _pubkeyHash = _compressedPubkey.hash160(); return abi.encodePacked(hex"0014", _pubkeyHash); } /// @notice checks a signed message's validity under a pubkey /// @dev does this using ecrecover because Ethereum has no soul /// @param _pubkey the public key to check (64 bytes) /// @param _digest the message digest signed /// @param _v the signature recovery value /// @param _r the signature r value /// @param _s the signature s value /// @return true if signature is valid, else false function checkSig( bytes memory _pubkey, bytes32 _digest, uint8 _v, bytes32 _r, bytes32 _s ) internal pure returns (bool) { require(_pubkey.length == 64, "Requires uncompressed unprefixed pubkey"); address _expected = accountFromPubkey(_pubkey); address _actual = ecrecover(_digest, _v, _r, _s); return _actual == _expected; } /// @notice checks a signed message against a bitcoin p2wpkh output script /// @dev does this my verifying the p2wpkh matches an ethereum account /// @param _p2wpkhOutputScript the bitcoin output script /// @param _pubkey the uncompressed, unprefixed public key to check /// @param _digest the message digest signed /// @param _v the signature recovery value /// @param _r the signature r value /// @param _s the signature s value /// @return true if signature is valid, else false function checkBitcoinSig( bytes memory _p2wpkhOutputScript, bytes memory _pubkey, bytes32 _digest, uint8 _v, bytes32 _r, bytes32 _s ) internal pure returns (bool) { require(_pubkey.length == 64, "Requires uncompressed unprefixed pubkey"); bool _isExpectedSigner = keccak256(p2wpkhFromPubkey(_pubkey)) == keccak256(_p2wpkhOutputScript); // is it the expected signer? if (!_isExpectedSigner) {return false;} bool _sigResult = checkSig(_pubkey, _digest, _v, _r, _s); return _sigResult; } /// @notice checks if a message is the sha256 preimage of a digest /// @dev this is NOT the hash256! this step is necessary for ECDSA security! /// @param _digest the digest /// @param _candidate the purported preimage /// @return true if the preimage matches the digest, else false function isSha256Preimage( bytes memory _candidate, bytes32 _digest ) internal pure returns (bool) { return sha256(_candidate) == _digest; } /// @notice checks if a message is the keccak256 preimage of a digest /// @dev this step is necessary for ECDSA security! /// @param _digest the digest /// @param _candidate the purported preimage /// @return true if the preimage matches the digest, else false function isKeccak256Preimage( bytes memory _candidate, bytes32 _digest ) internal pure returns (bool) { return keccak256(_candidate) == _digest; } /// @notice calculates the signature hash of a Bitcoin transaction with the provided details /// @dev documented in bip143. many values are hardcoded here /// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index) /// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey)) /// @param _inputValue the value of the input in satoshi /// @param _outputValue the value of the output in satoshi /// @param _outputScript the length-prefixed output script /// @return the double-sha256 (hash256) signature hash as defined by bip143 function wpkhSpendSighash( bytes memory _outpoint, // 36-byte UTXO id bytes20 _inputPKH, // 20-byte hash160 bytes8 _inputValue, // 8-byte LE bytes8 _outputValue, // 8-byte LE bytes memory _outputScript // lenght-prefixed output script ) internal pure returns (bytes32) { // Fixes elements to easily make a 1-in 1-out sighash digest // Does not support timelocks bytes memory _scriptCode = abi.encodePacked( hex"1976a914", // length, dup, hash160, pkh_length _inputPKH, hex"88ac"); // equal, checksig bytes32 _hashOutputs = abi.encodePacked( _outputValue, // 8-byte LE _outputScript).hash256(); bytes memory _sighashPreimage = abi.encodePacked( hex"01000000", // version _outpoint.hash256(), // hashPrevouts hex"8cb9012517c817fead650287d61bdd9c68803b6bf9c64133dcab3e65b5a50cb9", // hashSequence(00000000) _outpoint, // outpoint _scriptCode, // p2wpkh script code _inputValue, // value of the input in 8-byte LE hex"00000000", // input nSequence _hashOutputs, // hash of the single output hex"00000000", // nLockTime hex"01000000" // SIGHASH_ALL ); return _sighashPreimage.hash256(); } /// @notice calculates the signature hash of a Bitcoin transaction with the provided details /// @dev documented in bip143. many values are hardcoded here /// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index) /// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey)) /// @param _inputValue the value of the input in satoshi /// @param _outputValue the value of the output in satoshi /// @param _outputPKH the output pubkeyhash (hash160(recipient_pubkey)) /// @return the double-sha256 (hash256) signature hash as defined by bip143 function wpkhToWpkhSighash( bytes memory _outpoint, // 36-byte UTXO id bytes20 _inputPKH, // 20-byte hash160 bytes8 _inputValue, // 8-byte LE bytes8 _outputValue, // 8-byte LE bytes20 _outputPKH // 20-byte hash160 ) internal pure returns (bytes32) { return wpkhSpendSighash( _outpoint, _inputPKH, _inputValue, _outputValue, abi.encodePacked( hex"160014", // wpkh tag _outputPKH) ); } /// @notice Preserved for API compatibility with older version /// @dev documented in bip143. many values are hardcoded here /// @param _outpoint the bitcoin UTXO id (32-byte txid + 4-byte output index) /// @param _inputPKH the input pubkeyhash (hash160(sender_pubkey)) /// @param _inputValue the value of the input in satoshi /// @param _outputValue the value of the output in satoshi /// @param _outputPKH the output pubkeyhash (hash160(recipient_pubkey)) /// @return the double-sha256 (hash256) signature hash as defined by bip143 function oneInputOneOutputSighash( bytes memory _outpoint, // 36-byte UTXO id bytes20 _inputPKH, // 20-byte hash160 bytes8 _inputValue, // 8-byte LE bytes8 _outputValue, // 8-byte LE bytes20 _outputPKH // 20-byte hash160 ) internal pure returns (bytes32) { return wpkhToWpkhSighash(_outpoint, _inputPKH, _inputValue, _outputValue, _outputPKH); } } pragma solidity ^0.5.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the `IERC20` interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using `_mint`. * For a generic mechanism see `ERC20Mintable`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an `Approval` event is emitted on calls to `transferFrom`. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard `decreaseAllowance` and `increaseAllowance` * functions have been added to mitigate the well-known issues around setting * allowances. See `IERC20.approve`. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See `IERC20.transfer`. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount)); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in `IERC20.approve`. * * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to `transfer`, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a `Transfer` event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a `Transfer` event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destoys `amount` tokens from `account`, reducing the * total supply. * * Emits a `Transfer` event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an `Approval` event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity ^0.5.0; import "./IERC20.sol"; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that this information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * `IERC20.balanceOf` and `IERC20.transfer`. */ function decimals() public view returns (uint8) { return _decimals; } } pragma solidity ^0.5.0; import "../../introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either `approve` or `setApproveForAll`. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either `approve` or `setApproveForAll`. */ function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } pragma solidity ^0.5.0; import "./ERC721.sol"; import "./IERC721Metadata.sol"; import "../../introspection/ERC165.sol"; contract ERC721Metadata is ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721_METADATA); } /** * @dev Gets the token name. * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param tokenId uint256 ID of the token to query */ function tokenURI(uint256 tokenId) external view returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); return _tokenURIs[tokenId]; } /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setTokenURI(uint256 tokenId, string memory uri) internal { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = uri; } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 tokenId) internal { super._burn(owner, tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } pragma solidity ^0.5.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../drafts/Counters.sol"; import "../../introspection/ERC165.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != msg.sender, "ERC721: approve to caller"); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use `safeTransferFrom` whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `onERC721Received` on a target address. * The call is not executed if the target address is not a contract. * * This function is deprecated. * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } pragma solidity ^0.5.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } pragma solidity ^0.5.0; /** * @dev Collection of functions related to the address type, */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * > It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } pragma solidity ^0.5.0; import "../math/SafeMath.sol"; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the SafeMath * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } pragma solidity ^0.5.0; /** * @dev Interface of the ERC165 standard, as defined in the * [EIP](https://eips.ethereum.org/EIPS/eip-165). * * Implementers can declare support of contract interfaces, which can then be * queried by others (`ERC165Checker`). * * For an implementation, see `ERC165`. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified) * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } pragma solidity ^0.5.0; import "./IERC165.sol"; /** * @dev Implementation of the `IERC165` interface. * * Contracts may inherit from this and call `_registerInterface` to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See `IERC165.supportsInterface`. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See `IERC165.supportsInterface`. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } pragma solidity ^0.5.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); }
@notice Check if the contract is currently in the signer liquidation flow. @dev This could be caused by fraud, or by an unfilled margin call. @param _d Deposit storage pointer. @return True if contract is currently in the liquidaton flow else False.
function inSignerLiquidation(DepositUtils.Deposit storage _d) public view returns (bool) { return ( _d.currentState == uint8(States.LIQUIDATION_IN_PROGRESS) || _d.currentState == uint8(States.FRAUD_LIQUIDATION_IN_PROGRESS) ); }
7,283,350
[ 1, 1564, 309, 326, 6835, 353, 4551, 316, 326, 10363, 4501, 26595, 367, 4693, 18, 540, 1220, 3377, 506, 15848, 635, 284, 354, 1100, 16, 578, 635, 392, 640, 13968, 7333, 745, 18, 225, 389, 72, 282, 4019, 538, 305, 2502, 4407, 18, 327, 377, 1053, 309, 6835, 353, 4551, 316, 326, 4501, 26595, 16799, 4693, 469, 1083, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 316, 15647, 48, 18988, 350, 367, 12, 758, 1724, 1989, 18, 758, 1724, 2502, 389, 72, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 261, 203, 5411, 389, 72, 18, 2972, 1119, 422, 2254, 28, 12, 7629, 18, 2053, 53, 3060, 2689, 67, 706, 67, 24022, 13, 203, 540, 747, 389, 72, 18, 2972, 1119, 422, 2254, 28, 12, 7629, 18, 42, 2849, 12587, 67, 2053, 53, 3060, 2689, 67, 706, 67, 24022, 13, 203, 3639, 11272, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xCa598CA7E3B6C5d78DD41848DF50228195BdD282/sources/contracts/PaymentSplitterManagerClones.sol
* @dev Getter for the addresses of the PaymentSplitters registered where `_target` has shares./
function registeredSplittersOf(address _target) external view returns (address[] memory) { return _registeredSplitters[_target]; }
774,308
[ 1, 8461, 364, 326, 6138, 434, 326, 12022, 5521, 5432, 4104, 1625, 1375, 67, 3299, 68, 711, 24123, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4104, 5521, 5432, 951, 12, 2867, 389, 3299, 13, 3903, 1476, 1135, 261, 2867, 8526, 3778, 13, 288, 203, 3639, 327, 389, 14327, 5521, 5432, 63, 67, 3299, 15533, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: UNLICENSED pragma solidity ^0.6.12; contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor() internal {} function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), 'Ownable: caller is not the owner'); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), 'Ownable: new owner is the zero address'); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } library SafeMath{ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, 'SafeMath: subtraction overflow'); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, 'SafeMath: division by zero'); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, 'SafeMath: modulo by zero'); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } interface IBEP20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the bep token owner. */ function getOwner() external view returns (address); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address _owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } interface IWBNB { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); function withdraw(uint256) external; } // contract JoiStaking { // using SafeMath for uint256; // using EnumerableSet for EnumerableSet.AddressSet; // event RewardsTransferred(address holder, uint256 amount); // IBEP20 public rewardToken; // address public treasury; // address public admin; // //WBNB // address public immutable WBNB; // uint256 public constant MAX_PERFORMANCE_FEE = 500; // 5% // uint256 public constant MAX_CALL_FEE = 100; // 1% // uint256 public constant MAX_WITHDRAW_FEE = 100; // 1% // // reward rate 120.00% per year // uint256 public constant rewardRate = 12000; // uint256 public constant rewardInterval = 365 days; // uint256 public performanceFee = 500; // 5% // uint256 public callFee = 25; // 0.25% // uint256 public withdrawFee = 10; // 0.1% // mapping(address => uint256) public depositedTokens; // constructor(IBEP20 _rewardToken,address _wbnb) public { // rewardToken = _rewardToken; // WBNB = _wbnb; // } // modifier onlyAdmin(){ // require(msg.sender == admin,"admin: wut?"); // _; // } // receive() external payable { // assert(msg.sender == WBNB); // only accept BNB via fallback from the WBNB contract // } // function deposit() public payable{ // require(msg.value > 0,"stake amount is not zero."); // IWBNB(WBNB).deposit{value:msg.value}(); // assert(IWBNB(WBNB).transfer(address(this),msg.value)); // depositedTokens[msg.sender] = depositedTokens[msg.sender].add(msg.value); // } // } contract JoiStaking is Ownable{ using SafeMath for uint256; //Info of each user. struct UserInfo { uint256 amount; uint256 rewardDebt; } //Info of each pool struct PoolInfo { IBEP20 token; uint256 allocPoint; uint256 lastRewardBlock; uint256 accJoiPerShare; } // Reward token IBEP20 public rewardToken; //adminAddress address public adminAddress; address public immutable WBNB; // JOI tokens created per block uint256 public rewardPerBlock; //Info of each Pool PoolInfo[] public poolInfo; //Info of each user that stakes tokens mapping(address => UserInfo) public userInfo; // limit 10 BNB here uint256 public limitAmount =10000000000000000000; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when JOI mining starts. uint256 public startBlock; // The block number when JOI mining ends. uint256 public bonusEndBlock; event Deposit(address indexed user,uint256 amount); event Withdraw(address indexed user,uint256 amount); event EmergencyWithdraw(address indexed user,uint256 amount); constructor( IBEP20 _token, IBEP20 _rewardToken, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _bonusBlock, address _adminAddress, address _wbnb ) public { rewardToken = _rewardToken; rewardPerBlock = _rewardPerBlock; WBNB = _wbnb; startBlock = _startBlock; bonusEndBlock = _bonusBlock; adminAddress = _adminAddress; // staking pool poolInfo.push(PoolInfo({ token:_token, allocPoint:1000, lastRewardBlock:startBlock, accJoiPerShare:0 })); totalAllocPoint = 1000; } modifier onlyAdmin() { require(msg.sender == adminAddress,"admin:wut?"); _; } receive() external payable { assert(msg.sender == WBNB); } function setAdmin(address _adminAddress) public onlyOwner { adminAddress = _adminAddress; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from ,uint256 _to) public view returns(uint256){ if(_to <= bonusEndBlock){ return _to.sub(_from); } else if(_from >= bonusEndBlock){ return 0; } else { return bonusEndBlock.sub(_from); } } // View function to see pending Reward on frontend function pendingReward(address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[_user]; uint256 accJoiPerShare = pool.accJoiPerShare; uint256 balance = pool.token.balanceOf(address(this)); if(block.number > pool.lastRewardBlock && balance != 0){ uint256 multiplier = getMultiplier(pool.lastRewardBlock,block.number); uint256 joiReward = multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accJoiPerShare = accJoiPerShare.add(joiReward.mul(1e12).div(balance)); } return user.amount.mul(accJoiPerShare).div(1e12).sub(user.rewardDebt); } function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if(block.number <= pool.lastRewardBlock){ return; } uint256 balance = pool.token.balanceOf(address(this)); if(balance == 0){ pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock,block.number); uint256 joiReward = multiplier.mul(rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); pool.accJoiPerShare = pool.accJoiPerShare.add(joiReward.mul(1e12).div(balance)); pool.lastRewardBlock = block.number; } // Stake tokens function deposit() public payable{ PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[msg.sender]; require(user.amount.add(msg.value) <= limitAmount,'exceed the top'); updatePool(0); if(user.amount > 0){ uint256 pending = user.amount.mul(pool.accJoiPerShare).div(1e12).sub(user.rewardDebt); if(pending > 0){ rewardToken.transfer(address(msg.sender),pending); } } if(msg.value > 0){ IWBNB(WBNB).deposit{value:msg.value}(); assert(IWBNB(WBNB).transfer(address(this),msg.value)); user.amount = user.amount.add(msg.value); } user.rewardDebt = user.amount.mul(pool.accJoiPerShare).div(1e12); emit Deposit(msg.sender,msg.value); } function safeTransferBNB(address to, uint256 value) internal { (bool success, ) = to.call{gas: 23000, value: value}(""); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } //Withdraw token from staking function withdraw(uint256 _amount) public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[msg.sender]; require(user.amount >= _amount,'withdraw: not good'); updatePool(0); uint256 pending = user.amount.mul(pool.accJoiPerShare).div(1e12).sub(user.rewardDebt); if(pending >0){ rewardToken.transfer(address(msg.sender),pending); } if(_amount > 0){ user.amount = user.amount.sub(_amount); IWBNB(WBNB).withdraw(_amount); safeTransferBNB(address(msg.sender),_amount); } user.rewardDebt = user.amount.mul(pool.accJoiPerShare).div(1e12); emit Withdraw(msg.sender,_amount); } function emergencyWithdraw() public { PoolInfo storage pool = poolInfo[0]; UserInfo storage user = userInfo[msg.sender]; pool.token.transfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, user.amount); user.amount = 0; user.rewardDebt = 0; } }
Empty internal constructor, to prevent people from mistakenly deploying an instance of this contract, which should be used via inheritance.
contract Context { pragma solidity ^0.6.12; constructor() internal {} function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { return msg.data; } }
2,545,107
[ 1, 1921, 2713, 3885, 16, 358, 5309, 16951, 628, 27228, 7940, 715, 7286, 310, 392, 791, 434, 333, 6835, 16, 1492, 1410, 506, 1399, 3970, 16334, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1772, 288, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 26, 18, 2138, 31, 203, 565, 3885, 1435, 2713, 2618, 203, 565, 445, 389, 3576, 12021, 1435, 2713, 1476, 1135, 261, 2867, 8843, 429, 13, 288, 203, 3639, 327, 1234, 18, 15330, 31, 203, 565, 289, 203, 203, 565, 445, 389, 3576, 751, 1435, 2713, 1476, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 327, 1234, 18, 892, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** * The Dioti token contract bases on the ERC20 standard token contracts from * open-zeppelin and is extended by functions to issue tokens as needed by the * Dioti ICO. * authors: Yuda Chandra Wiguna * */ pragma solidity ^0.4.19; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) public balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { assert(token.transfer(to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { assert(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { assert(token.approve(spender, value)); } } /** * @title TokenTimelock * @dev TokenTimelock is a token holder contract that will allow a * beneficiary to extract the tokens after a given release time */ contract TokenTimelock { using SafeERC20 for ERC20Basic; // ERC20 basic token contract being held ERC20Basic public token; // beneficiary of tokens after they are released address public beneficiary; // timestamp when token release is enabled uint64 public releaseTime; function TokenTimelock (ERC20Basic _token, address _beneficiary, uint64 _releaseTime) public { require(_releaseTime > uint64(block.timestamp)); token = _token; beneficiary = _beneficiary; releaseTime = _releaseTime; } /** * @notice Transfers tokens held by timelock to beneficiary. */ function release() public { require(uint64(block.timestamp) >= releaseTime); uint256 amount = token.balanceOf(this); require(amount > 0); token.safeTransfer(beneficiary, amount); } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract Owned { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Owned() public { owner = msg.sender; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } modifier onlyOwner { require(msg.sender == owner); _; } } contract DiotiToken is StandardToken, Owned { string public constant name = "DiotiToken"; string public constant symbol = "DOT"; uint8 public constant decimals = 18; /// Maximum tokens to be allocated on the sale (51% of the hard cap) uint256 public constant TOKENS_SALE_HARD_CAP = 510000000000000000000000000; // 510000000 * 10**18 /// Base exchange rate is set to 1 ETH = 166 DOT. uint256 public constant BASE_RATE = 166667; /// seconds since 01.01.1970 to 04.02.2019 (17:00:00 o'clock UTC) /// HOT sale start time uint64 private constant dateHOTSale = 1549360800 + 72 hours; /// HOT sale end time; Sale A start time 07.02.2019 uint64 private constant dateSaleA = 1549558800 + 72 hours; /// Sale A end time; Sale B start time 14.02.2019 uint64 private constant dateSaleB = 1550768400 + 72 hours; /// Sale B end time; Sale C start time 21.02.2019 uint64 private constant dateSaleC = 1551373200 + 72 hours; /// Sale F end time; 01.03.2018 uint64 private constant date21Mar2018 = 1553162400 + 16 hours; /// token caps for each round uint256[4] private roundCaps = [ 70000000000000000000000, // HOT sale 70000000 * 10**15 140000000000000000000000, // Sale A 140000000 * 10**15 210000000000000000000000, // Sale B 210000000 * 10**15 285000000000000000000000 // Sale C 285000000 * 10**15 ]; uint8[4] private roundDiscountPercentages = [37, 25, 16, 10]; /// team tokens are locked until this date (01.01.2020) 00:00:00 uint64 private constant dateTeamTokensLockedTill = 1577836800; /// no tokens can be ever issued when this is set to "true" bool public tokenSaleClosed = false; /// contract to be called to release the Dioti team tokens address public timelockContractAddress; modifier inProgress { require(totalSupply < TOKENS_SALE_HARD_CAP && !tokenSaleClosed && now >= dateHOTSale); _; } /// Allow the closing to happen only once modifier beforeEnd { require(!tokenSaleClosed); _; } /// Require that the token sale has been closed modifier tradingOpen { require(tokenSaleClosed); _; } function DiotiToken() public { } /// @dev This default function allows token to be purchased by directly /// sending ether to this smart contract. function () public payable { purchaseTokens(msg.sender); } /// @dev Issue token based on Ether received. /// @param _beneficiary Address that newly issued token will be sent to. function purchaseTokens(address _beneficiary) public payable inProgress { // only accept a minimum amount of ETH? require(msg.value >= 0.01 ether); uint256 tokens = computeTokenAmount(msg.value); // roll back if hard cap reached require(totalSupply.add(tokens) <= TOKENS_SALE_HARD_CAP); doIssueTokens(_beneficiary, tokens); /// forward the raised funds to the contract creator owner.transfer(this.balance); } /// @dev Batch issue tokens on the presale /// @param _addresses addresses that the presale tokens will be sent to. /// @param _addresses the amounts of tokens, with decimals expanded (full). function issueTokensMulti(address[] _addresses, uint256[] _tokens) public onlyOwner beforeEnd { require(_addresses.length == _tokens.length); require(_addresses.length <= 100); for (uint256 i = 0; i < _tokens.length; i = i.add(1)) { doIssueTokens(_addresses[i], _tokens[i]); } } /// @dev Issue tokens for a single buyer on the presale /// @param _beneficiary addresses that the presale tokens will be sent to. /// @param _tokens the amount of tokens, with decimals expanded (full). function issueTokens(address _beneficiary, uint256 _tokens) public onlyOwner beforeEnd { doIssueTokens(_beneficiary, _tokens); } /// @dev issue tokens for a single buyer /// @param _beneficiary addresses that the tokens will be sent to. /// @param _tokens the amount of tokens, with decimals expanded (full). function doIssueTokens(address _beneficiary, uint256 _tokens) internal { require(_beneficiary != address(0)); // increase token total supply totalSupply = totalSupply.add(_tokens); // update the beneficiary balance to number of tokens sent balances[_beneficiary] = balances[_beneficiary].add(_tokens); // event is fired when tokens issued Transfer(address(0), _beneficiary, _tokens); } /// @dev Returns the current price. function price() public view returns (uint256 tokens) { return computeTokenAmount(1 ether); } /// @dev Compute the amount of DOR token that can be purchased. /// @param ethAmount Amount of Ether in WEI to purchase DOR. /// @return Amount of DOR token to purchase function computeTokenAmount(uint256 ethAmount) internal view returns (uint256 tokens) { uint256 tokenBase = (ethAmount.mul(BASE_RATE)/10000000000000)*10000000000000;//18 decimals to 18 decimals, set precision to 5 decimals uint8 roundNum = currentRoundIndex(); tokens = tokenBase.mul(100)/(100 - (roundDiscountPercentages[roundNum])); while(tokens.add(totalSupply) > roundCaps[roundNum] && roundNum < 4){ roundNum++; tokens = tokenBase.mul(100)/(100 - (roundDiscountPercentages[roundNum])); } } /// @dev Determine the current sale round /// @return integer representing the index of the current sale round function currentRoundIndex() internal view returns (uint8 roundNum) { roundNum = currentRoundIndexByDate(); /// round determined by conjunction of both time and total sold tokens while(roundNum < 4 && totalSupply > roundCaps[roundNum]) { roundNum++; } } /// @dev Determine the current sale tier. /// @return the index of the current sale tier by date. function currentRoundIndexByDate() internal view returns (uint8 roundNum) { require(now <= date21Mar2018); if(now > dateSaleC) return 3; if(now > dateSaleB) return 2; if(now > dateSaleA) return 1; else return 0; } /// @dev Closes the sale, issues the team tokens and burns the unsold function close() public onlyOwner beforeEnd { /// team tokens are equal to 15% of the sold tokens /// 8% foodout group tokens are added to the locked tokens uint256 lockedTokens = 230000000000000000000000; //partner tokens are available from the beginning uint256 partnerTokens = 260000000000000000000000; issueLockedTokens(lockedTokens); issuePartnerTokens(partnerTokens); /// increase token total supply totalSupply = totalSupply.add(lockedTokens+partnerTokens); /// burn the unallocated tokens - no more tokens can be issued after this line tokenSaleClosed = true; /// forward the raised funds to the contract creator owner.transfer(this.balance); } /** * issue the tokens for the team and the foodout group. * tokens are locked for 3 years. * @param lockedTokens the amount of tokens to the issued and locked * */ function issueLockedTokens( uint lockedTokens) internal{ /// team tokens are locked until this date (01.01.2021) TokenTimelock lockedTeamTokens = new TokenTimelock(this, owner, dateTeamTokensLockedTill); timelockContractAddress = address(lockedTeamTokens); balances[timelockContractAddress] = balances[timelockContractAddress].add(lockedTokens); /// fire event when tokens issued Transfer(address(0), timelockContractAddress, lockedTokens); } /** * issue the tokens for partners and advisors * @param partnerTokens the amount of tokens to be issued * */ function issuePartnerTokens(uint partnerTokens) internal{ balances[owner] = partnerTokens; Transfer(address(0), owner, partnerTokens); } /// Transfer limited by the tradingOpen modifier function transferFrom(address _from, address _to, uint256 _value) public tradingOpen returns (bool) { return super.transferFrom(_from, _to, _value); } /// Transfer limited by the tradingOpen modifier function transfer(address _to, uint256 _value) public tradingOpen returns (bool) { return super.transfer(_to, _value); } }
@dev Issue token based on Ether received. @param _beneficiary Address that newly issued token will be sent to. only accept a minimum amount of ETH? roll back if hard cap reached
function purchaseTokens(address _beneficiary) public payable inProgress { require(msg.value >= 0.01 ether); uint256 tokens = computeTokenAmount(msg.value); require(totalSupply.add(tokens) <= TOKENS_SALE_HARD_CAP); doIssueTokens(_beneficiary, tokens); owner.transfer(this.balance);
5,391,150
[ 1, 12956, 1147, 2511, 603, 512, 1136, 5079, 18, 225, 389, 70, 4009, 74, 14463, 814, 5267, 716, 10894, 16865, 1147, 903, 506, 3271, 358, 18, 1338, 2791, 279, 5224, 3844, 434, 512, 2455, 35, 5824, 1473, 309, 7877, 3523, 8675, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 23701, 5157, 12, 2867, 389, 70, 4009, 74, 14463, 814, 13, 1071, 8843, 429, 316, 5491, 288, 203, 3639, 2583, 12, 3576, 18, 1132, 1545, 374, 18, 1611, 225, 2437, 1769, 203, 203, 3639, 2254, 5034, 2430, 273, 3671, 1345, 6275, 12, 3576, 18, 1132, 1769, 203, 203, 3639, 2583, 12, 4963, 3088, 1283, 18, 1289, 12, 7860, 13, 1648, 14275, 55, 67, 5233, 900, 67, 44, 8085, 67, 17296, 1769, 203, 203, 3639, 741, 12956, 5157, 24899, 70, 4009, 74, 14463, 814, 16, 2430, 1769, 203, 203, 3639, 3410, 18, 13866, 12, 2211, 18, 12296, 1769, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.8; // /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // /** * @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"); } } } // /** * @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. * * Credit: https://github.com/OpenZeppelin/openzeppelin-upgrades/blob/master/packages/core/contracts/Initializable.sol */ 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; } // /** * @notice An account contracted created for each user address. * @dev Anyone can directy deposit assets to the Account contract. * @dev Only operators can withdraw asstes or perform operation from the Account contract. */ contract Account is Initializable { using SafeMath for uint256; using SafeERC20 for IERC20; /** * @dev Asset is withdrawn from the Account. */ event Withdrawn(address indexed tokenAddress, address indexed targetAddress, uint256 amount); /** * @dev Spender is allowed to spend an asset. */ event Approved(address indexed tokenAddress, address indexed targetAddress, uint256 amount); /** * @dev A transaction is invoked on the Account. */ event Invoked(address indexed targetAddress, uint256 value, bytes data); address public owner; mapping(address => bool) public admins; mapping(address => bool) public operators; /** * @dev Initializes the owner, admin and operator roles. * @param _owner Address of the contract owner * @param _initialAdmins The list of addresses that are granted the admin role. */ function initialize(address _owner, address[] memory _initialAdmins) public initializer { owner = _owner; // Grant the admin role to the initial admins for (uint256 i = 0; i < _initialAdmins.length; i++) { admins[_initialAdmins[i]] = true; } } /** * @dev Throws if called by any account that does not have operator role. */ modifier onlyOperator() { require(isOperator(msg.sender), "not operator"); _; } /** * @dev Transfers the ownership of the account to another address. * The new owner can be an zero address which means renouncing the ownership. * @param _owner New owner address */ function transferOwnership(address _owner) public { require(msg.sender == owner, "not owner"); owner = _owner; } /** * @dev Grants admin role to a new address. * @param _account New admin address. */ function grantAdmin(address _account) public { require(msg.sender == owner, "not owner"); require(!admins[_account], "already admin"); admins[_account] = true; } /** * @dev Revokes the admin role from an address. Only owner can revoke admin. * @param _account The admin address to revoke. */ function revokeAdmin(address _account) public { require(msg.sender == owner, "not owner"); require(admins[_account], "not admin"); admins[_account] = false; } /** * @dev Grants operator role to a new address. Only owner or admin can grant operator roles. * @param _account The new operator address. */ function grantOperator(address _account) public { require(msg.sender == owner || admins[msg.sender], "not admin"); require(!operators[_account], "already operator"); operators[_account] = true; } /** * @dev Revoke operator role from an address. Only owner or admin can revoke operator roles. * @param _account The operator address to revoke. */ function revokeOperator(address _account) public { require(msg.sender == owner || admins[msg.sender], "not admin"); require(operators[_account], "not operator"); operators[_account] = false; } /** * @dev Allows Account contract to receive ETH. */ receive() payable external {} /** * @dev Checks whether a user is an operator of the contract. * Since admin role can grant operator role and owner can grant admin role, we treat both * admins and owner as operators! * @param userAddress Address to check whether it's an operator. */ function isOperator(address userAddress) public view returns (bool) { return userAddress == owner || admins[userAddress] || operators[userAddress]; } /** * @dev Withdraws ETH from the Account contract. Only operators can withdraw ETH. * @param targetAddress Address to send the ETH to. * @param amount Amount of ETH to withdraw. */ function withdraw(address payable targetAddress, uint256 amount) public onlyOperator { targetAddress.transfer(amount); // Use address(-1) to represent ETH. emit Withdrawn(address(-1), targetAddress, amount); } /** * @dev Withdraws ERC20 token from the Account contract. Only operators can withdraw ERC20 tokens. * @param tokenAddress Address of the ERC20 to withdraw. * @param targetAddress Address to send the ERC20 to. * @param amount Amount of ERC20 token to withdraw. */ function withdrawToken(address tokenAddress, address targetAddress, uint256 amount) public onlyOperator { IERC20(tokenAddress).safeTransfer(targetAddress, amount); emit Withdrawn(tokenAddress, targetAddress, amount); } /** * @dev Withdraws ERC20 token from the Account contract. If the Account contract does not have sufficient balance, * try to withdraw from the owner's address as well. This is useful if users wants to keep assets in their own wallet * by setting adequate allowance to the Account contract. * @param tokenAddress Address of the ERC20 to withdraw. * @param targetAddress Address to send the ERC20 to. * @param amount Amount of ERC20 token to withdraw. */ function withdrawTokenFallThrough(address tokenAddress, address targetAddress, uint256 amount) public onlyOperator { uint256 tokenBalance = IERC20(tokenAddress).balanceOf(address(this)); // If we have enough token balance, send the token directly. if (tokenBalance >= amount) { IERC20(tokenAddress).safeTransfer(targetAddress, amount); emit Withdrawn(tokenAddress, targetAddress, amount); } else { IERC20(tokenAddress).safeTransferFrom(owner, targetAddress, amount.sub(tokenBalance)); IERC20(tokenAddress).safeTransfer(targetAddress, tokenBalance); emit Withdrawn(tokenAddress, targetAddress, amount); } } /** * @dev Allows the spender address to spend up to the amount of token. * @param tokenAddress Address of the ERC20 that can spend. * @param targetAddress Address which can spend the ERC20. * @param amount Amount of ERC20 that can be spent by the target address. */ function approveToken(address tokenAddress, address targetAddress, uint256 amount) public onlyOperator { IERC20(tokenAddress).safeApprove(targetAddress, 0); if (amount > 0) { IERC20(tokenAddress).safeApprove(targetAddress, amount); } emit Approved(tokenAddress, targetAddress, amount); } /** * @notice Performs a generic transaction on the Account contract. * @param target The address for the target contract. * @param value The value of the transaction. * @param data The data of the transaction. */ function invoke(address target, uint256 value, bytes memory data) public onlyOperator returns (bytes memory result) { bool success; (success, result) = target.call{value: value}(data); if (!success) { // solhint-disable-next-line no-inline-assembly assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } emit Invoked(target, value, data); } } // /** * @title Proxy * @dev Implements delegation of calls to other contracts, with proper * forwarding of return values and bubbling of failures. * It defines a fallback function that delegates all calls to the address * returned by the abstract _implementation() internal function. * * Credit: https://github.com/OpenZeppelin/openzeppelin-sdk/blob/master/packages/lib/contracts/upgradeability/Proxy.sol */ abstract contract Proxy { /** * @dev Receive function. * Implemented entirely in `_fallback`. */ receive () payable external { _fallback(); } /** * @dev Fallback function. * Implemented entirely in `_fallback`. */ fallback () payable external { _fallback(); } /** * @return The Address of the implementation. */ function _implementation() internal virtual view returns (address); /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param implementation Address to delegate. */ function _delegate(address implementation) internal { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev Function that is run as the first thing in the fallback function. * Can be redefined in derived contracts to add functionality. * Redefinitions must call super._willFallback(). */ function _willFallback() internal virtual { } /** * @dev fallback implementation. * Extracted to enable manual triggering. */ function _fallback() internal { _willFallback(); _delegate(_implementation()); } } // /** * @title BaseUpgradeabilityProxy * @dev This contract implements a proxy that allows to change the * implementation address to which it will delegate. * Such a change is called an implementation upgrade. * * Credit: https://github.com/OpenZeppelin/openzeppelin-sdk/blob/master/packages/lib/contracts/upgradeability/BaseUpgradeabilityProxy.sol */ contract BaseUpgradeabilityProxy is Proxy { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation. * @return impl Address of the current implementation */ function _implementation() internal override view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function _setImplementation(address newImplementation) internal { require( Address.isContract(newImplementation), "Implementation not set" ); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } emit Upgraded(newImplementation); } } // /** * @title AdminUpgradeabilityProxy * @dev This contract combines an upgradeability proxy with an authorization * mechanism for administrative tasks. * All external functions in this contract must be guarded by the * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity * feature proposal that would enable this to be done automatically. * Credit: https://github.com/OpenZeppelin/openzeppelin-sdk/blob/master/packages/lib/contracts/upgradeability/BaseAdminUpgradeabilityProxy.sol */ contract AdminUpgradeabilityProxy is BaseUpgradeabilityProxy { /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * Contract constructor. * @param _logic address of the initial implementation. * @param _admin Address of the proxy administrator. * It should include the signature and the parameters of the function to be called, as described in * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding. * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped. */ constructor(address _logic, address _admin) public payable { assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1)); assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1)); _setImplementation(_logic); _setAdmin(_admin); } /** * @dev Modifier to check whether the `msg.sender` is the admin. * If it is, it will run the function. Otherwise, it will delegate the call * to the implementation. */ modifier ifAdmin() { if (msg.sender == _admin()) { _; } else { _fallback(); } } /** * @return The address of the proxy admin. */ function admin() external ifAdmin returns (address) { return _admin(); } /** * @return The address of the implementation. */ function implementation() external ifAdmin returns (address) { return _implementation(); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param newAdmin Address to transfer proxy administration to. */ function changeAdmin(address newAdmin) external ifAdmin { emit AdminChanged(_admin(), newAdmin); _setAdmin(newAdmin); } /** * @dev Upgrade the backing implementation of the proxy. * Only the admin can call this function. * @param newImplementation Address of the new implementation. */ function changeImplementation(address newImplementation) external ifAdmin { _setImplementation(newImplementation); } /** * @return adm The admin slot. */ function _admin() internal view returns (address adm) { bytes32 slot = ADMIN_SLOT; assembly { adm := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param newAdmin Address of the new proxy admin. */ function _setAdmin(address newAdmin) internal { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, newAdmin) } } } // /** * @notice Factory of Account contracts. */ contract AccountFactory { /** * @dev A new Account contract is created. */ event AccountCreated(address indexed userAddress, address indexed accountAddress); address public governance; address public accountBase; mapping(address => address) public accounts; /** * @dev Constructor for Account Factory. * @param _accountBase Base account implementation. */ constructor(address _accountBase) public { require(_accountBase != address(0x0), "account base not set"); governance = msg.sender; accountBase = _accountBase; } /** * @dev Updates the base account implementation. Base account must be set. */ function setAccountBase(address _accountBase) public { require(msg.sender == governance, "not governance"); require(_accountBase != address(0x0), "account base not set"); accountBase = _accountBase; } /** * @dev Updates the govenance address. Governance can be empty address which means * renouncing the governance. */ function setGovernance(address _governance) public { require(msg.sender == governance, "not governance"); governance = _governance; } /** * @dev Creates a new Account contract for the caller. * Users can create multiple accounts by invoking this method multiple times. However, * only the latest one is actively tracked and used by the platform. * @param _initialAdmins The list of addresses that are granted the admin role. */ function createAccount(address[] memory _initialAdmins) public returns (Account) { AdminUpgradeabilityProxy proxy = new AdminUpgradeabilityProxy(accountBase, msg.sender); Account account = Account(address(proxy)); account.initialize(msg.sender, _initialAdmins); accounts[msg.sender] = address(account); emit AccountCreated(msg.sender, address(account)); return account; } } // /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { // 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; } } // /** * @notice Interface for ERC20 token which supports minting new tokens. */ interface IERC20Mintable is IERC20 { function mint(address _user, uint256 _amount) external; } // /** * @notice Interface for ERC20 token which supports mint and burn. */ interface IERC20MintableBurnable is IERC20Mintable { function burn(uint256 _amount) external; function burnFrom(address _user, uint256 _amount) external; } // /** * @notice ACoconut swap. */ contract ACoconutSwap is Initializable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; /** * @dev Token swapped between two underlying tokens. */ event TokenSwapped(address indexed buyer, address indexed tokenSold, address indexed tokenBought, uint256 amountSold, uint256 amountBought); /** * @dev New pool token is minted. */ event Minted(address indexed provider, uint256 mintAmount, uint256[] amounts, uint256 feeAmount); /** * @dev Pool token is redeemed. */ event Redeemed(address indexed provider, uint256 redeemAmount, uint256[] amounts, uint256 feeAmount); /** * @dev Fee is collected. */ event FeeCollected(address indexed feeRecipient, uint256 feeAmount); uint256 public constant feeDenominator = 10 ** 10; address[] public tokens; uint256[] public precisions; // 10 ** (18 - token decimals) uint256[] public balances; // Converted to 10 ** 18 uint256 public mintFee; // Mint fee * 10**10 uint256 public swapFee; // Swap fee * 10**10 uint256 public redeemFee; // Redeem fee * 10**10 address public feeRecipient; address public poolToken; uint256 public totalSupply; // The total amount of pool token minted by the swap. // It might be different from the pool token supply as the pool token can have multiple minters. address public governance; mapping(address => bool) public admins; bool public paused; uint256 public initialA; /** * @dev Initialize the ACoconut Swap. */ function initialize(address[] memory _tokens, uint256[] memory _precisions, uint256[] memory _fees, address _poolToken, uint256 _A) public initializer { require(_tokens.length == _precisions.length, "input mismatch"); require(_fees.length == 3, "no fees"); for (uint256 i = 0; i < _tokens.length; i++) { require(_tokens[i] != address(0x0), "token not set"); require(_precisions[i] != 0, "precision not set"); balances.push(0); } require(_poolToken != address(0x0), "pool token not set"); governance = msg.sender; feeRecipient = msg.sender; tokens = _tokens; precisions = _precisions; mintFee = _fees[0]; swapFee = _fees[1]; redeemFee = _fees[2]; poolToken = _poolToken; initialA = _A; // The swap must start with paused state! paused = true; } /** * @dev Returns the current value of A. This method might be updated in the future. */ function getA() public view returns (uint256) { return initialA; } /** * @dev Computes D given token balances. * @param _balances Normalized balance of each token. * @param _A Amplification coefficient from getA() */ function _getD(uint256[] memory _balances, uint256 _A) internal pure returns (uint256) { uint256 sum = 0; uint256 i = 0; uint256 Ann = _A; for (i = 0; i < _balances.length; i++) { sum = sum.add(_balances[i]); Ann = Ann.mul(_balances.length); } if (sum == 0) return 0; uint256 prevD = 0; uint256 D = sum; for (i = 0; i < 255; i++) { uint256 pD = D; for (uint256 j = 0; j < _balances.length; j++) { // pD = pD * D / (_x * balance.length) pD = pD.mul(D).div(_balances[j].mul(_balances.length)); } prevD = D; // D = (Ann * sum + pD * balance.length) * D / ((Ann - 1) * D + (balance.length + 1) * pD) D = Ann.mul(sum).add(pD.mul(_balances.length)).mul(D).div(Ann.sub(1).mul(D).add(_balances.length.add(1).mul(pD))); if (D > prevD) { if (D - prevD <= 1) break; } else { if (prevD - D <= 1) break; } } return D; } /** * @dev Computes token balance given D. * @param _balances Converted balance of each token except token with index _j. * @param _j Index of the token to calculate balance. * @param _D The target D value. * @param _A Amplification coeffient. * @return Converted balance of the token with index _j. */ function _getY(uint256[] memory _balances, uint256 _j, uint256 _D, uint256 _A) internal pure returns (uint256) { uint256 c = _D; uint256 S_ = 0; uint256 Ann = _A; uint256 i = 0; for (i = 0; i < _balances.length; i++) { Ann = Ann.mul(_balances.length); if (i == _j) continue; S_ = S_.add(_balances[i]); // c = c * D / (_x * N) c = c.mul(_D).div(_balances[i].mul(_balances.length)); } // c = c * D / (Ann * N) c = c.mul(_D).div(Ann.mul(_balances.length)); // b = S_ + D / Ann uint256 b = S_.add(_D.div(Ann)); uint256 prevY = 0; uint256 y = _D; // 255 since the result is 256 digits for (i = 0; i < 255; i++) { prevY = y; // y = (y * y + c) / (2 * y + b - D) y = y.mul(y).add(c).div(y.mul(2).add(b).sub(_D)); if (y > prevY) { if (y - prevY <= 1) break; } else { if (prevY - y <= 1) break; } } return y; } /** * @dev Compute the amount of pool token that can be minted. * @param _amounts Unconverted token balances. * @return The amount of pool token minted. */ function getMintAmount(uint256[] calldata _amounts) external view returns (uint256, uint256) { uint256[] memory _balances = balances; require(_amounts.length == _balances.length, "invalid amount"); uint256 A = getA(); uint256 oldD = totalSupply; uint256 i = 0; for (i = 0; i < _balances.length; i++) { if (_amounts[i] == 0) continue; // balance = balance + amount * precision _balances[i] = _balances[i].add(_amounts[i].mul(precisions[i])); } uint256 newD = _getD(_balances, A); // newD should be bigger than or equal to oldD uint256 mintAmount = newD.sub(oldD); uint256 feeAmount = 0; if (mintFee > 0) { feeAmount = mintAmount.mul(mintFee).div(feeDenominator); mintAmount = mintAmount.sub(feeAmount); } return (mintAmount, feeAmount); } /** * @dev Mints new pool token. * @param _amounts Unconverted token balances used to mint pool token. * @param _minMintAmount Minimum amount of pool token to mint. */ function mint(uint256[] calldata _amounts, uint256 _minMintAmount) external nonReentrant { uint256[] memory _balances = balances; // If swap is paused, only admins can mint. require(!paused || admins[msg.sender], "paused"); require(_balances.length == _amounts.length, "invalid amounts"); uint256 A = getA(); uint256 oldD = totalSupply; uint256 i = 0; for (i = 0; i < _balances.length; i++) { if (_amounts[i] == 0) { // Initial deposit requires all tokens provided! require(oldD > 0, "zero amount"); continue; } _balances[i] = _balances[i].add(_amounts[i].mul(precisions[i])); } uint256 newD = _getD(_balances, A); // newD should be bigger than or equal to oldD uint256 mintAmount = newD.sub(oldD); uint256 fee = mintFee; uint256 feeAmount; if (fee > 0) { feeAmount = mintAmount.mul(fee).div(feeDenominator); mintAmount = mintAmount.sub(feeAmount); } require(mintAmount >= _minMintAmount, "fewer than expected"); // Transfer tokens into the swap for (i = 0; i < _amounts.length; i++) { if (_amounts[i] == 0) continue; // Update the balance in storage balances[i] = _balances[i]; IERC20(tokens[i]).safeTransferFrom(msg.sender, address(this), _amounts[i]); } totalSupply = newD; IERC20MintableBurnable(poolToken).mint(feeRecipient, feeAmount); IERC20MintableBurnable(poolToken).mint(msg.sender, mintAmount); emit Minted(msg.sender, mintAmount, _amounts, feeAmount); } /** * @dev Computes the output amount after the swap. * @param _i Token index to swap in. * @param _j Token index to swap out. * @param _dx Unconverted amount of token _i to swap in. * @return Unconverted amount of token _j to swap out. */ function getSwapAmount(uint256 _i, uint256 _j, uint256 _dx) external view returns (uint256) { uint256[] memory _balances = balances; require(_i != _j, "same token"); require(_i < _balances.length, "invalid in"); require(_j < _balances.length, "invalid out"); require(_dx > 0, "invalid amount"); uint256 A = getA(); uint256 D = totalSupply; // balance[i] = balance[i] + dx * precisions[i] _balances[_i] = _balances[_i].add(_dx.mul(precisions[_i])); uint256 y = _getY(_balances, _j, D, A); // dy = (balance[j] - y - 1) / precisions[j] in case there was rounding errors uint256 dy = _balances[_j].sub(y).sub(1).div(precisions[_j]); if (swapFee > 0) { dy = dy.sub(dy.mul(swapFee).div(feeDenominator)); } return dy; } /** * @dev Exchange between two underlying tokens. * @param _i Token index to swap in. * @param _j Token index to swap out. * @param _dx Unconverted amount of token _i to swap in. * @param _minDy Minimum token _j to swap out in converted balance. */ function swap(uint256 _i, uint256 _j, uint256 _dx, uint256 _minDy) external nonReentrant { uint256[] memory _balances = balances; // If swap is paused, only admins can swap. require(!paused || admins[msg.sender], "paused"); require(_i != _j, "same token"); require(_i < _balances.length, "invalid in"); require(_j < _balances.length, "invalid out"); require(_dx > 0, "invalid amount"); uint256 A = getA(); uint256 D = totalSupply; // balance[i] = balance[i] + dx * precisions[i] _balances[_i] = _balances[_i].add(_dx.mul(precisions[_i])); uint256 y = _getY(_balances, _j, D, A); // dy = (balance[j] - y - 1) / precisions[j] in case there was rounding errors uint256 dy = _balances[_j].sub(y).sub(1).div(precisions[_j]); // Update token balance in storage balances[_j] = y; balances[_i] = _balances[_i]; uint256 fee = swapFee; if (fee > 0) { dy = dy.sub(dy.mul(fee).div(feeDenominator)); } require(dy >= _minDy, "fewer than expected"); IERC20(tokens[_i]).safeTransferFrom(msg.sender, address(this), _dx); // Important: When swap fee > 0, the swap fee is charged on the output token. // Therefore, balances[j] < tokens[j].balanceOf(this) // Since balances[j] is used to compute D, D is unchanged. // collectFees() is used to convert the difference between balances[j] and tokens[j].balanceOf(this) // into pool token as fees! IERC20(tokens[_j]).safeTransfer(msg.sender, dy); emit TokenSwapped(msg.sender, tokens[_i], tokens[_j], _dx, dy); } /** * @dev Computes the amounts of underlying tokens when redeeming pool token. * @param _amount Amount of pool tokens to redeem. * @return Amounts of underlying tokens redeemed. */ function getRedeemProportionAmount(uint256 _amount) external view returns (uint256[] memory, uint256) { uint256[] memory _balances = balances; require(_amount > 0, "zero amount"); uint256 D = totalSupply; uint256[] memory amounts = new uint256[](_balances.length); uint256 feeAmount = 0; if (redeemFee > 0) { feeAmount = _amount.mul(redeemFee).div(feeDenominator); // Redemption fee is charged with pool token before redemption. _amount = _amount.sub(feeAmount); } for (uint256 i = 0; i < _balances.length; i++) { // We might choose to use poolToken.totalSupply to compute the amount, but decide to use // D in case we have multiple minters on the pool token. amounts[i] = _balances[i].mul(_amount).div(D).div(precisions[i]); } return (amounts, feeAmount); } /** * @dev Redeems pool token to underlying tokens proportionally. * @param _amount Amount of pool token to redeem. * @param _minRedeemAmounts Minimum amount of underlying tokens to get. */ function redeemProportion(uint256 _amount, uint256[] calldata _minRedeemAmounts) external nonReentrant { uint256[] memory _balances = balances; // If swap is paused, only admins can redeem. require(!paused || admins[msg.sender], "paused"); require(_amount > 0, "zero amount"); require(_balances.length == _minRedeemAmounts.length, "invalid mins"); uint256 D = totalSupply; uint256[] memory amounts = new uint256[](_balances.length); uint256 fee = redeemFee; uint256 feeAmount; if (fee > 0) { feeAmount = _amount.mul(fee).div(feeDenominator); // Redemption fee is paid with pool token // No conversion is needed as the pool token has 18 decimals IERC20(poolToken).safeTransferFrom(msg.sender, feeRecipient, feeAmount); _amount = _amount.sub(feeAmount); } for (uint256 i = 0; i < _balances.length; i++) { // We might choose to use poolToken.totalSupply to compute the amount, but decide to use // D in case we have multiple minters on the pool token. uint256 tokenAmount = _balances[i].mul(_amount).div(D); // Important: Underlying tokens must convert back to original decimals! amounts[i] = tokenAmount.div(precisions[i]); require(amounts[i] >= _minRedeemAmounts[i], "fewer than expected"); // Updates the balance in storage balances[i] = _balances[i].sub(tokenAmount); IERC20(tokens[i]).safeTransfer(msg.sender, amounts[i]); } totalSupply = D.sub(_amount); // After reducing the redeem fee, the remaining pool tokens are burned! IERC20MintableBurnable(poolToken).burnFrom(msg.sender, _amount); emit Redeemed(msg.sender, _amount.add(feeAmount), amounts, feeAmount); } /** * @dev Computes the amount when redeeming pool token to one specific underlying token. * @param _amount Amount of pool token to redeem. * @param _i Index of the underlying token to redeem to. * @return Amount of underlying token that can be redeem to. */ function getRedeemSingleAmount(uint256 _amount, uint256 _i) external view returns (uint256, uint256) { uint256[] memory _balances = balances; require(_amount > 0, "zero amount"); require(_i < _balances.length, "invalid token"); uint256 A = getA(); uint256 D = totalSupply; uint256 feeAmount = 0; if (redeemFee > 0) { feeAmount = _amount.mul(redeemFee).div(feeDenominator); // Redemption fee is charged with pool token before redemption. _amount = _amount.sub(feeAmount); } // The pool token amount becomes D - _amount uint256 y = _getY(_balances, _i, D.sub(_amount), A); // dy = (balance[i] - y - 1) / precisions[i] in case there was rounding errors uint256 dy = _balances[_i].sub(y).sub(1).div(precisions[_i]); return (dy, feeAmount); } /** * @dev Redeem pool token to one specific underlying token. * @param _amount Amount of pool token to redeem. * @param _i Index of the token to redeem to. * @param _minRedeemAmount Minimum amount of the underlying token to redeem to. */ function redeemSingle(uint256 _amount, uint256 _i, uint256 _minRedeemAmount) external nonReentrant { uint256[] memory _balances = balances; // If swap is paused, only admins can redeem. require(!paused || admins[msg.sender], "paused"); require(_amount > 0, "zero amount"); require(_i < _balances.length, "invalid token"); uint256 A = getA(); uint256 D = totalSupply; uint256 fee = redeemFee; uint256 feeAmount = 0; if (fee > 0) { // Redemption fee is charged with pool token before redemption. feeAmount = _amount.mul(fee).div(feeDenominator); // No conversion is needed as the pool token has 18 decimals IERC20(poolToken).safeTransferFrom(msg.sender, feeRecipient, feeAmount); _amount = _amount.sub(feeAmount); } // y is converted(18 decimals) uint256 y = _getY(_balances, _i, D.sub(_amount), A); // dy is not converted // dy = (balance[i] - y - 1) / precisions[i] in case there was rounding errors uint256 dy = _balances[_i].sub(y).sub(1).div(precisions[_i]); require(dy >= _minRedeemAmount, "fewer than expected"); // Updates token balance in storage balances[_i] = y; uint256[] memory amounts = new uint256[](_balances.length); amounts[_i] = dy; IERC20(tokens[_i]).safeTransfer(msg.sender, dy); totalSupply = D.sub(_amount); IERC20MintableBurnable(poolToken).burnFrom(msg.sender, _amount); emit Redeemed(msg.sender, _amount.add(feeAmount), amounts, feeAmount); } /** * @dev Compute the amount of pool token that needs to be redeemed. * @param _amounts Unconverted token balances. * @return The amount of pool token that needs to be redeemed. */ function getRedeemMultiAmount(uint256[] calldata _amounts) external view returns (uint256, uint256) { uint256[] memory _balances = balances; require(_amounts.length == balances.length, "length not match"); uint256 A = getA(); uint256 oldD = totalSupply; for (uint256 i = 0; i < _balances.length; i++) { if (_amounts[i] == 0) continue; // balance = balance + amount * precision _balances[i] = _balances[i].sub(_amounts[i].mul(precisions[i])); } uint256 newD = _getD(_balances, A); // newD should be smaller than or equal to oldD uint256 redeemAmount = oldD.sub(newD); uint256 feeAmount = 0; if (redeemFee > 0) { redeemAmount = redeemAmount.mul(feeDenominator).div(feeDenominator.sub(redeemFee)); feeAmount = redeemAmount.sub(oldD.sub(newD)); } return (redeemAmount, feeAmount); } /** * @dev Redeems underlying tokens. * @param _amounts Amounts of underlying tokens to redeem to. * @param _maxRedeemAmount Maximum of pool token to redeem. */ function redeemMulti(uint256[] calldata _amounts, uint256 _maxRedeemAmount) external nonReentrant { uint256[] memory _balances = balances; require(_amounts.length == balances.length, "length not match"); // If swap is paused, only admins can redeem. require(!paused || admins[msg.sender], "paused"); uint256 A = getA(); uint256 oldD = totalSupply; uint256 i = 0; for (i = 0; i < _balances.length; i++) { if (_amounts[i] == 0) continue; // balance = balance + amount * precision _balances[i] = _balances[i].sub(_amounts[i].mul(precisions[i])); } uint256 newD = _getD(_balances, A); // newD should be smaller than or equal to oldD uint256 redeemAmount = oldD.sub(newD); uint256 fee = redeemFee; uint256 feeAmount = 0; if (fee > 0) { redeemAmount = redeemAmount.mul(feeDenominator).div(feeDenominator.sub(fee)); feeAmount = redeemAmount.sub(oldD.sub(newD)); // No conversion is needed as the pool token has 18 decimals IERC20(poolToken).safeTransferFrom(msg.sender, feeRecipient, feeAmount); } require(redeemAmount <= _maxRedeemAmount, "more than expected"); // Updates token balances in storage. balances = _balances; uint256 burnAmount = redeemAmount.sub(feeAmount); totalSupply = oldD.sub(burnAmount); IERC20MintableBurnable(poolToken).burnFrom(msg.sender, burnAmount); for (i = 0; i < _balances.length; i++) { if (_amounts[i] == 0) continue; IERC20(tokens[i]).safeTransfer(msg.sender, _amounts[i]); } emit Redeemed(msg.sender, redeemAmount, _amounts, feeAmount); } /** * @dev Return the amount of fee that's not collected. */ function getPendingFeeAmount() external view returns (uint256) { uint256[] memory _balances = balances; uint256 A = getA(); uint256 oldD = totalSupply; for (uint256 i = 0; i < _balances.length; i++) { _balances[i] = IERC20(tokens[i]).balanceOf(address(this)).mul(precisions[i]); } uint256 newD = _getD(_balances, A); return newD.sub(oldD); } /** * @dev Collect fee based on the token balance difference. */ function collectFee() external returns (uint256) { require(admins[msg.sender], "not admin"); uint256[] memory _balances = balances; uint256 A = getA(); uint256 oldD = totalSupply; for (uint256 i = 0; i < _balances.length; i++) { _balances[i] = IERC20(tokens[i]).balanceOf(address(this)).mul(precisions[i]); } uint256 newD = _getD(_balances, A); uint256 feeAmount = newD.sub(oldD); if (feeAmount == 0) return 0; balances = _balances; totalSupply = newD; address _feeRecipient = feeRecipient; IERC20MintableBurnable(poolToken).mint(_feeRecipient, feeAmount); emit FeeCollected(_feeRecipient, feeAmount); return feeAmount; } /** * @dev Updates the govenance address. */ function setGovernance(address _governance) external { require(msg.sender == governance, "not governance"); governance = _governance; } /** * @dev Updates the mint fee. */ function setMintFee(uint256 _mintFee) external { require(msg.sender == governance, "not governance"); mintFee = _mintFee; } /** * @dev Updates the swap fee. */ function setSwapFee(uint256 _swapFee) external { require(msg.sender == governance, "not governance"); swapFee = _swapFee; } /** * @dev Updates the redeem fee. */ function setRedeemFee(uint256 _redeemFee) external { require(msg.sender == governance, "not governance"); redeemFee = _redeemFee; } /** * @dev Updates the recipient of mint/swap/redeem fees. */ function setFeeRecipient(address _feeRecipient) external { require(msg.sender == governance, "not governance"); require(_feeRecipient != address(0x0), "fee recipient not set"); feeRecipient = _feeRecipient; } /** * @dev Updates the pool token. */ function setPoolToken(address _poolToken) external { require(msg.sender == governance, "not governance"); require(_poolToken != address(0x0), "pool token not set"); poolToken = _poolToken; } /** * @dev Pause mint/swap/redeem actions. Can unpause later. */ function pause() external { require(msg.sender == governance, "not governance"); require(!paused, "paused"); paused = true; } /** * @dev Unpause mint/swap/redeem actions. */ function unpause() external { require(msg.sender == governance, "not governance"); require(paused, "not paused"); paused = false; } /** * @dev Updates the admin role for the address. * @param _account Address to update admin role. * @param _allowed Whether the address is granted the admin role. */ function setAdmin(address _account, bool _allowed) external { require(msg.sender == governance, "not governance"); require(_account != address(0x0), "account not set"); admins[_account] = _allowed; } } // /** * @dev Application to help interact with ACoconutSwap with account. */ contract SwapApplication is Initializable { using SafeMath for uint256; address public governance; ACoconutSwap public swap; /** * @dev Initializes swap application. */ function initialize(address _swap) external initializer { require(_swap != address(0x0), "swap not set"); governance = msg.sender; swap = ACoconutSwap(_swap); } /** * @dev Updates the govenance address. */ function setGovernance(address _governance) external { require(msg.sender == governance, "not governance"); governance = _governance; } /** * @dev Updates the swap address. */ function setSwap(address _swap) external { require(msg.sender == governance, "not governance"); require(_swap != address(0x0), "swap not set"); swap = ACoconutSwap(_swap); } modifier validAccount(address _account) { Account account = Account(payable(_account)); require(account.owner() == msg.sender, "not owner"); require(account.isOperator(address(this)), "not operator"); _; } /** * @dev Mints new pool token. * @param _account The account address used to mint. * @param _amounts Unconverted token balances used to mint pool token. * @param _minMintAmount Minimum amount of pool token to mint. */ function mintToken(address _account, uint256[] calldata _amounts, uint256 _minMintAmount) external validAccount(_account) { Account account = Account(payable(_account)); ACoconutSwap _swap = swap; // We don't perform input validations here as they are done in ACoconutSwap. for (uint256 i = 0; i < _amounts.length; i++) { if (_amounts[i] == 0) continue; account.approveToken(_swap.tokens(i), address(_swap), _amounts[i]); } bytes memory methodData = abi.encodeWithSignature("mint(uint256[],uint256)", _amounts, _minMintAmount); account.invoke(address(_swap), 0, methodData); } /** * @dev Exchange between two underlying tokens. * @param _account The account address used to swap. * @param _i Token index to swap in. * @param _j Token index to swap out. * @param _dx Unconverted amount of token _i to swap in. * @param _minDy Minimum token _j to swap out in converted balance. */ function swapToken(address _account, uint256 _i, uint256 _j, uint256 _dx, uint256 _minDy) external validAccount(_account) { Account account = Account(payable(_account)); ACoconutSwap _swap = swap; // We don't perform input validations here as they are done in ACoconutSwap. account.approveToken(_swap.tokens(_i), address(_swap), _dx); bytes memory methodData = abi.encodeWithSignature("swap(uint256,uint256,uint256,uint256)", _i, _j, _dx, _minDy); account.invoke(address(_swap), 0, methodData); } /** * @dev Redeems pool token to underlying tokens proportionally. * @param _account The account address used to redeem. * @param _amount Amount of pool token to redeem. * @param _minRedeemAmounts Minimum amount of underlying tokens to get. */ function redeemProportion(address _account, uint256 _amount, uint256[] calldata _minRedeemAmounts) external validAccount(_account) { Account account = Account(payable(_account)); ACoconutSwap _swap = swap; // We don't perform input validations here as they are done in ACoconutSwap. account.approveToken(_swap.poolToken(), address(_swap), _amount); bytes memory methodData = abi.encodeWithSignature("redeemProportion(uint256,uint256[])", _amount, _minRedeemAmounts); account.invoke(address(_swap), 0, methodData); } /** * @dev Redeem pool token to one specific underlying token. * @param _account The account address used to redeem. * @param _amount Amount of pool token to redeem. * @param _i Index of the token to redeem to. * @param _minRedeemAmount Minimum amount of the underlying token to redeem to. */ function redeemSingle(address _account, uint256 _amount, uint256 _i, uint256 _minRedeemAmount) external validAccount(_account) { Account account = Account(payable(_account)); ACoconutSwap _swap = swap; // We don't perform input validations here as they are done in ACoconutSwap. account.approveToken(_swap.poolToken(), address(_swap), _amount); bytes memory methodData = abi.encodeWithSignature("redeemSingle(uint256,uint256,uint256)", _amount, _i, _minRedeemAmount); account.invoke(address(_swap), 0, methodData); } /** * @dev Redeems underlying tokens. * @param _account The account address used to redeem. * @param _amounts Amounts of underlying tokens to redeem to. * @param _maxRedeemAmount Maximum of pool token to redeem. */ function redeemMulti(address _account, uint256[] calldata _amounts, uint256 _maxRedeemAmount) external validAccount(_account) { Account account = Account(payable(_account)); ACoconutSwap _swap = swap; // We don't perform input validations here as they are done in ACoconutSwap. // The amount of acBTC to burn is unknown yet. Simply set the allowance to the maximum redeem amount. account.approveToken(_swap.poolToken(), address(_swap), _maxRedeemAmount); bytes memory methodData = abi.encodeWithSignature("redeemMulti(uint256[],uint256)", _amounts, _maxRedeemAmount); account.invoke(address(_swap), 0, methodData); // Clears the allowance afterward account.approveToken(_swap.poolToken(), address(this), 0); } }
* @dev Mints new pool token. @param _account The account address used to mint. @param _amounts Unconverted token balances used to mint pool token. @param _minMintAmount Minimum amount of pool token to mint./ We don't perform input validations here as they are done in ACoconutSwap.
function mintToken(address _account, uint256[] calldata _amounts, uint256 _minMintAmount) external validAccount(_account) { Account account = Account(payable(_account)); ACoconutSwap _swap = swap; for (uint256 i = 0; i < _amounts.length; i++) { if (_amounts[i] == 0) continue; account.approveToken(_swap.tokens(i), address(_swap), _amounts[i]); } bytes memory methodData = abi.encodeWithSignature("mint(uint256[],uint256)", _amounts, _minMintAmount); account.invoke(address(_swap), 0, methodData); }
7,662,568
[ 1, 49, 28142, 394, 2845, 1147, 18, 225, 389, 4631, 1021, 2236, 1758, 1399, 358, 312, 474, 18, 225, 389, 8949, 87, 1351, 6283, 329, 1147, 324, 26488, 1399, 358, 312, 474, 2845, 1147, 18, 225, 389, 1154, 49, 474, 6275, 23456, 3844, 434, 2845, 1147, 358, 312, 474, 18, 19, 1660, 2727, 1404, 3073, 810, 20808, 2674, 487, 2898, 854, 2731, 316, 12048, 16550, 322, 12521, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 1345, 12, 2867, 389, 4631, 16, 2254, 5034, 8526, 745, 892, 389, 8949, 87, 16, 2254, 5034, 389, 1154, 49, 474, 6275, 13, 3903, 923, 3032, 24899, 4631, 13, 288, 203, 3639, 6590, 2236, 273, 6590, 12, 10239, 429, 24899, 4631, 10019, 203, 3639, 12048, 16550, 322, 12521, 389, 22270, 273, 7720, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 8949, 87, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 67, 8949, 87, 63, 77, 65, 422, 374, 13, 282, 1324, 31, 203, 5411, 2236, 18, 12908, 537, 1345, 24899, 22270, 18, 7860, 12, 77, 3631, 1758, 24899, 22270, 3631, 389, 8949, 87, 63, 77, 19226, 203, 3639, 289, 203, 203, 3639, 1731, 3778, 707, 751, 273, 24126, 18, 3015, 1190, 5374, 2932, 81, 474, 12, 11890, 5034, 63, 6487, 11890, 5034, 2225, 16, 389, 8949, 87, 16, 389, 1154, 49, 474, 6275, 1769, 203, 3639, 2236, 18, 14407, 12, 2867, 24899, 22270, 3631, 374, 16, 707, 751, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: contracts/VeloxTransferHelper.sol // SPDX-FileCopyrightText: © 2020 Velox <[email protected]> // SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.8.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library VeloxTransferHelper { function safeApprove(address token, address to, uint value) internal { require(token != address(0), 'VeloxTransferHelper: ZERO_ADDRESS'); require(to != address(0), 'VeloxTransferHelper: TO_ZERO_ADDRESS'); // 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))), 'VeloxTransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { require(token != address(0), 'VeloxTransferHelper: ZERO_ADDRESS'); require(to != address(0), 'VeloxTransferHelper: TO_ZERO_ADDRESS'); // 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))), 'VeloxTransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { require(token != address(0), 'VeloxTransferHelper: TOKEN_ZERO_ADDRESS'); require(from != address(0), 'VeloxTransferHelper: FROM_ZERO_ADDRESS'); require(to != address(0), 'VeloxTransferHelper: TO_ZERO_ADDRESS'); // 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))), 'VeloxTransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { require(to != address(0), 'VeloxTransferHelper: TO_ZERO_ADDRESS'); (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File: contracts/interfaces/IERC20.sol pragma solidity >=0.8.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); } // File: contracts/interfaces/IERC20NONStandard.sol pragma solidity >=0.8.0; /** * @dev Version of ERC20 with no return values for `transfer` and `transferFrom` * See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ abstract contract IERC20NONStandard { /* This is a slight change to the ERC20 base standard. function totalSupply() constant returns (uint256 supply); is replaced with: uint256 public totalSupply; This automatically creates a getter function for the totalSupply. This is moved to the base contract since public getter functions are not currently recognised as an implementation of the matching abstract function by the compiler. */ uint256 public totalSupply; function balanceOf(address owner) virtual public view returns (uint256 balance); /// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC20 specification /// will return Whether the transfer was successful or not function transfer(address to, uint256 value) virtual public; /// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC20 specification /// will return Whether the transfer was successful or not function transferFrom(address from, address to, uint256 value) virtual public; function approve(address spender, uint256 value) virtual public returns (bool success); function allowance(address owner, address spender) virtual public view returns (uint256 remaining); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/SwapExceptions.sol pragma solidity >=0.8.0; contract SwapExceptions { event SwapException(uint exception, uint info, uint detail); enum Exception { NO_ERROR, GENERIC_ERROR, UNAUTHORIZED, INTEGER_OVERFLOW, INTEGER_UNDERFLOW, DIVISION_BY_ZERO, BAD_INPUT, TOKEN_INSUFFICIENT_ALLOWANCE, TOKEN_INSUFFICIENT_BALANCE, TOKEN_TRANSFER_FAILED, MARKET_NOT_SUPPORTED, SUPPLY_RATE_CALCULATION_FAILED, BORROW_RATE_CALCULATION_FAILED, TOKEN_INSUFFICIENT_CASH, TOKEN_TRANSFER_OUT_FAILED, INSUFFICIENT_LIQUIDITY, INSUFFICIENT_BALANCE, INVALID_COLLATERAL_RATIO, MISSING_ASSET_PRICE, EQUITY_INSUFFICIENT_BALANCE, INVALID_CLOSE_AMOUNT_REQUESTED, ASSET_NOT_PRICED, INVALID_LIQUIDATION_DISCOUNT, INVALID_COMBINED_RISK_PARAMETERS, ZERO_ORACLE_ADDRESS, CONTRACT_PAUSED } /* * Note: Reason (but not Exception) is kept in alphabetical order * This is because Reason grows significantly faster, and * the order of Exception has some meaning, while the order of Reason * is arbitrary. */ enum Reason { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, BORROW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, BORROW_ACCOUNT_SHORTFALL_PRESENT, BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, BORROW_AMOUNT_LIQUIDITY_SHORTFALL, BORROW_AMOUNT_VALUE_CALCULATION_FAILED, BORROW_CONTRACT_PAUSED, BORROW_MARKET_NOT_SUPPORTED, BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, BORROW_ORIGINATION_FEE_CALCULATION_FAILED, BORROW_TRANSFER_OUT_FAILED, EQUITY_WITHDRAWAL_AMOUNT_VALIDATION, EQUITY_WITHDRAWAL_CALCULATE_EQUITY, EQUITY_WITHDRAWAL_MODEL_OWNER_CHECK, EQUITY_WITHDRAWAL_TRANSFER_OUT_FAILED, LIQUIDATE_ACCUMULATED_BORROW_BALANCE_CALCULATION_FAILED, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_ACCUMULATED_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_AMOUNT_SEIZE_CALCULATION_FAILED, LIQUIDATE_BORROW_DENOMINATED_COLLATERAL_CALCULATION_FAILED, LIQUIDATE_CLOSE_AMOUNT_TOO_HIGH, LIQUIDATE_CONTRACT_PAUSED, LIQUIDATE_DISCOUNTED_REPAY_TO_EVEN_AMOUNT_CALCULATION_FAILED, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_BORROW_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_BORROW_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_SUPPLY_INDEX_CALCULATION_FAILED_COLLATERAL_ASSET, LIQUIDATE_NEW_SUPPLY_RATE_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_BORROW_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_CASH_CALCULATION_FAILED_BORROWED_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_BORROWER_COLLATERAL_ASSET, LIQUIDATE_NEW_TOTAL_SUPPLY_BALANCE_CALCULATION_FAILED_LIQUIDATOR_COLLATERAL_ASSET, LIQUIDATE_FETCH_ASSET_PRICE_FAILED, LIQUIDATE_TRANSFER_IN_FAILED, LIQUIDATE_TRANSFER_IN_NOT_POSSIBLE, REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, REPAY_BORROW_CONTRACT_PAUSED, REPAY_BORROW_NEW_BORROW_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_BORROW_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, REPAY_BORROW_NEW_SUPPLY_RATE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_BORROW_CALCULATION_FAILED, REPAY_BORROW_NEW_TOTAL_CASH_CALCULATION_FAILED, REPAY_BORROW_TRANSFER_IN_FAILED, REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, SET_ASSET_PRICE_CHECK_ORACLE, SET_MARKET_INTEREST_RATE_MODEL_OWNER_CHECK, SET_ORACLE_OWNER_CHECK, SET_ORIGINATION_FEE_OWNER_CHECK, SET_PAUSED_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_RISK_PARAMETERS_OWNER_CHECK, SET_RISK_PARAMETERS_VALIDATION, SUPPLY_ACCUMULATED_BALANCE_CALCULATION_FAILED, SUPPLY_CONTRACT_PAUSED, SUPPLY_MARKET_NOT_SUPPORTED, SUPPLY_NEW_BORROW_INDEX_CALCULATION_FAILED, SUPPLY_NEW_BORROW_RATE_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_INDEX_CALCULATION_FAILED, SUPPLY_NEW_SUPPLY_RATE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_BALANCE_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_CASH_CALCULATION_FAILED, SUPPLY_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, SUPPLY_TRANSFER_IN_FAILED, SUPPLY_TRANSFER_IN_NOT_POSSIBLE, SUPPORT_MARKET_FETCH_PRICE_FAILED, SUPPORT_MARKET_OWNER_CHECK, SUPPORT_MARKET_PRICE_CHECK, SUSPEND_MARKET_OWNER_CHECK, WITHDRAW_ACCOUNT_LIQUIDITY_CALCULATION_FAILED, WITHDRAW_ACCOUNT_SHORTFALL_PRESENT, WITHDRAW_ACCUMULATED_BALANCE_CALCULATION_FAILED, WITHDRAW_AMOUNT_LIQUIDITY_SHORTFALL, WITHDRAW_AMOUNT_VALUE_CALCULATION_FAILED, WITHDRAW_CAPACITY_CALCULATION_FAILED, WITHDRAW_CONTRACT_PAUSED, WITHDRAW_NEW_BORROW_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_BORROW_RATE_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_INDEX_CALCULATION_FAILED, WITHDRAW_NEW_SUPPLY_RATE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, WITHDRAW_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, WITHDRAW_TRANSFER_OUT_FAILED, WITHDRAW_TRANSFER_OUT_NOT_POSSIBLE } /** * @dev report a known exception */ function raiseException(Exception exception, Reason reason) internal returns (uint) { emit SwapException(uint(exception), uint(reason), 0); return uint(exception); } /** * @dev report an opaque error from an upgradeable collaborator contract */ function raiseGenericException(Reason reason, uint genericException) internal returns (uint) { emit SwapException(uint(Exception.GENERIC_ERROR), uint(reason), genericException); return uint(Exception.GENERIC_ERROR); } } // File: contracts/Swappable.sol pragma solidity 0.8.0; /** * @title Swappable Interface */ contract Swappable is SwapExceptions { /** * @dev Checks whether or not there is sufficient allowance for this contract to move amount from `from` and * whether or not `from` has a balance of at least `amount`. Does NOT do a transfer. */ function checkTransferIn(address asset, address from, uint amount) internal view returns (Exception) { IERC20 token = IERC20(asset); if (token.allowance(from, address(this)) < amount) { return Exception.TOKEN_INSUFFICIENT_ALLOWANCE; } if (token.balanceOf(from) < amount) { return Exception.TOKEN_INSUFFICIENT_BALANCE; } return Exception.NO_ERROR; } /** * @dev This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferIn(address asset, address from, uint amount) internal returns (Exception) { IERC20NONStandard token = IERC20NONStandard(asset); bool result; // Should we use Helper.safeTransferFrom? require(token.allowance(from, address(this)) >= amount, 'Not enough allowance from client'); token.transferFrom(from, address(this), amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Exception.TOKEN_TRANSFER_FAILED; } return Exception.NO_ERROR; } /** * @dev Checks balance of this contract in asset */ function getCash(address asset) internal view returns (uint) { IERC20 token = IERC20(asset); return token.balanceOf(address(this)); } /** * @dev Checks balance of `from` in `asset` */ function getBalanceOf(address asset, address from) internal view returns (uint) { IERC20 token = IERC20(asset); return token.balanceOf(from); } /** * @dev Similar to EIP20 transfer, except it handles a False result from `transfer` and returns an explanatory * error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to * insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified * it is >= amount, this should not revert in normal conditions. * * Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value. * See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca */ function doTransferOut(address asset, address to, uint amount) internal returns (Exception) { IERC20NONStandard token = IERC20NONStandard(asset); bool result; token.transfer(to, amount); assembly { switch returndatasize() case 0 { // This is a non-standard ERC-20 result := not(0) // set result to true } case 32 { // This is a complaint ERC-20 returndatacopy(0, 0, 32) result := mload(0) // Set `result = returndata` of external call } default { // This is an excessively non-compliant ERC-20, revert. revert(0, 0) } } if (!result) { return Exception.TOKEN_TRANSFER_OUT_FAILED; } return Exception.NO_ERROR; } } // File: contracts/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 GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return payable(msg.sender); } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/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 () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/interfaces/IVeloxSwapV3.sol pragma solidity >=0.8.0; interface IVeloxSwapV3 { function withdrawToken(address token, uint256 amount) external; function withdrawETH(uint256 amount) external; function sellExactTokensForTokens( string calldata exchange, uint256 strategyId, address seller, address tokenInAddress, address tokenOutAddress, uint256 tokenInAmount, uint256 minTokenOutAmount, uint16 feeFactor, bool takeFeeFromInput, uint256 deadline) external returns (uint256 amountOut); function sellExactTokensForTokens( string calldata exchange, uint256 strategyId, address seller, address tokenInAddress, address tokenOutAddress, uint256 tokenInAmount, uint256 minTokenOutAmount, uint16 feeFactor, bool takeFeeFromInput, uint256 deadline, uint estimatedGasFundingCost) external returns (uint256 amountOut); function sellTokensForExactTokens( string calldata exchange, uint256 strategyId, address seller, address tokenInAddress, address tokenOutAddress, uint256 maxTokenInAmount, uint256 tokenOutAmount, uint16 feeFactor, bool takeFeeFromInput, uint256 deadline) external returns (uint256 amountIn); function sellTokensForExactTokens( string calldata exchange, uint256 strategyId, address seller, address tokenInAddress, address tokenOutAddress, uint256 maxTokenInAmount, uint256 tokenOutAmount, uint16 feeFactor, bool takeFeeFromInput, uint256 deadline, uint estimatedGasFundingCost) external returns (uint256 amountIn); function fundGasCost(uint256 strategyId, address seller, bytes32 txHash, uint256 wethAmount) external; } // File: contracts/BackingStore.sol pragma solidity >=0.8.0; abstract contract BackingStore { address public MAIN_CONTRACT; address public UNISWAP_FACTORY_ADDRESS = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; address public UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public ADMIN_ADDRESS; } // File: contracts/lib/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: contracts/lib/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: contracts/lib/AccessControl.sol pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping (address => bool) members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev 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 See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev 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 { require(hasRole(getRoleAdmin(role), _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override { require(hasRole(getRoleAdmin(role), _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File: contracts/AccessManager.sol pragma solidity 0.8.0; contract AccessManager is AccessControl{ bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); /** * @dev Throws if called by any account other than the admin. */ modifier hasAdminRole() { require(hasRole(ADMIN_ROLE, _msgSender()), "VELOXSWAP: NOT_ADMIN"); _; } } // File: contracts/VeloxSwapV3.sol pragma solidity 0.8.0; /** * @title VeloxSwap based on algorithmic conditional trading exeuctions */ abstract contract VeloxSwapV3 is BackingStore, Ownable, Swappable, IVeloxSwapV3, AccessManager { function setUpAdminRole(address _c) public onlyOwner returns (bool succeeded) { require(_c != owner(), "VELOXPROXY_ADMIN_OWNER"); _setupRole(ADMIN_ROLE, _c); return true; } function setRootRole() public onlyOwner returns (bool succeeded) { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); return true; } function grantAdminRole(address _c) public onlyOwner returns (bool succeeded) { require(_c != owner(), "VELOXPROXY_ADMIN_OWNER"); grantRole(ADMIN_ROLE, _c); return true; } function revokeAdminRole(address _c) public onlyOwner returns (bool succeeded) { require(_c != owner(), "VELOXPROXY_ADMIN_OWNER"); revokeRole(ADMIN_ROLE, _c); return true; } struct SwapInput { address seller; address tokenInAddress; address tokenOutAddress; uint256 tokenInAmount; uint256 tokenOutAmount; uint16 feeFactor; bool takeFeeFromInput; uint256 deadline; } address private gasFundingTokenAddress; uint constant FEE_SCALE = 10000; uint constant GAS_FUNDING_ESTIMATED_GAS = 26233; event ValueSwapped(uint256 indexed strategyId, address indexed seller, address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOut); event GasFunded(uint256 indexed strategyId, address indexed seller, bytes32 indexed txHash, uint256 gasCost); event GasFundingTokenChanged(address oldValue, address newValue); event ExchangeRegistered(string indexed exchange, address indexed routerAddress); function setGasFundingTokenAddress(address tokenAddress) external onlyOwner { require(tokenAddress != address(0), "VELOXSWAP: ZERO_GAS_FUNDING_TOKEN_ADDRESS"); address oldValue = gasFundingTokenAddress; gasFundingTokenAddress = tokenAddress; emit GasFundingTokenChanged(oldValue, gasFundingTokenAddress); } function getGasFundingTokenAddress() public view returns (address) { return gasFundingTokenAddress; } function setKnownExchange(string calldata exchangeName, address routerAddress) onlyOwner external virtual { require(routerAddress != address(0), "VELOXSWAP: INVALID_ROUTER_ZERO_ADDRESS"); _setKnownExchange(exchangeName, routerAddress); emit ExchangeRegistered(exchangeName, routerAddress); } function withdrawToken(address token, uint256 amount) onlyOwner override external { VeloxTransferHelper.safeTransfer(token, msg.sender, amount); } function withdrawETH(uint256 amount) onlyOwner override external { VeloxTransferHelper.safeTransferETH(msg.sender, amount); } function fundGasCost(uint256 strategyId, address seller, bytes32 txHash, uint256 wethAmount) hasAdminRole override external { require(txHash.length > 0, "VELOXSWAP: INVALID_TX_HASH"); _fundGasCost(strategyId, seller, txHash, wethAmount); } function _fundGasCost(uint256 strategyId, address seller, bytes32 txHash, uint256 wethAmount) private { VeloxTransferHelper.safeTransferFrom(gasFundingTokenAddress, seller, _msgSender(), wethAmount); emit GasFunded(strategyId, seller, txHash, wethAmount); } /** * @dev This function should ONLY be executed when algorithmic conditons are met * function sellExactTokensForTokens * @param exchange string name of a existing exchange in routersByName * @param strategyId uint256 - strategy ID * @param seller address * @param tokenInAddress address * @param tokenOutAddress address * @param tokenInAmount uint256 * @param minTokenOutAmount uint256 * @param feeFactor uint - 1/10000 fraction of the amount, i.e. feeFactor of 1 means 0.01% fee * @param takeFeeFromInput bool * @param deadline uint256 - UNIX timestamp * @param estimatedGasFundingCost uint - estimated gas for gas funding transaction */ function sellExactTokensForTokens( string calldata exchange, uint256 strategyId, address seller, address tokenInAddress, address tokenOutAddress, uint256 tokenInAmount, uint256 minTokenOutAmount, uint16 feeFactor, bool takeFeeFromInput, uint256 deadline, uint estimatedGasFundingCost ) override hasAdminRole public returns (uint256 amountOut) { uint256 initialGas = gasleft(); SwapInput memory input = SwapInput({ seller: seller, tokenInAddress: tokenInAddress, tokenOutAddress: tokenOutAddress, tokenInAmount: tokenInAmount, tokenOutAmount: minTokenOutAmount, feeFactor: feeFactor, takeFeeFromInput: takeFeeFromInput, deadline: deadline }); ( , amountOut) = swapTokens(exchange, strategyId, input, true); // Not sure if it should be 0 or just minus something if (isTakingOutputFeeInGasToken(input)) { estimatedGasFundingCost = 0; } uint256 gasCost = (initialGas - gasleft() + estimatedGasFundingCost) * tx.gasprice; bytes32 txHash; _fundGasCost(strategyId, seller, txHash, gasCost); } /** * @dev This function should ONLY be executed when algorithmic conditons are met * function sellExactTokensForTokens * @param exchange string name of a existing exchange in routersByName * @param strategyId uint256 - strategy ID * @param seller address * @param tokenInAddress address * @param tokenOutAddress address * @param tokenInAmount uint256 * @param minTokenOutAmount uint256 * @param feeFactor uint - 1/10000 fraction of the amount, i.e. feeFactor of 1 means 0.01% fee * @param takeFeeFromInput bool * @param deadline uint256 - UNIX timestamp */ function sellExactTokensForTokens( string calldata exchange, uint256 strategyId, address seller, address tokenInAddress, address tokenOutAddress, uint256 tokenInAmount, uint256 minTokenOutAmount, uint16 feeFactor, bool takeFeeFromInput, uint256 deadline ) override hasAdminRole public returns (uint256 amountOut) { amountOut = sellExactTokensForTokens(exchange, strategyId, seller, tokenInAddress, tokenOutAddress, tokenInAmount, minTokenOutAmount, feeFactor, takeFeeFromInput, deadline, GAS_FUNDING_ESTIMATED_GAS); } /** * @dev This function should ONLY be executed when algorithmic conditons are met * function sellTokensForExactTokens * @param exchange string name of a existing exchange in routersByName * @param strategyId uint256 - strategy ID * @param seller address * @param tokenInAddress address * @param tokenOutAddress address * @param maxTokenInAmount uint256 * @param tokenOutAmount uint256 * @param feeFactor uint - 1/10000 fraction of the amount, i.e. feeFactor of 1 means 0.01% fee * @param takeFeeFromInput bool * @param deadline uint256 - UNIX timestamp * @param estimatedGasFundingCost uint - estimated gas for gas funding transaction */ function sellTokensForExactTokens( string calldata exchange, uint256 strategyId, address seller, address tokenInAddress, address tokenOutAddress, uint256 maxTokenInAmount, uint256 tokenOutAmount, uint16 feeFactor, bool takeFeeFromInput, uint256 deadline, uint estimatedGasFundingCost) override hasAdminRole public returns (uint256 amountIn) { uint256 initialGas = gasleft(); SwapInput memory input = SwapInput({ seller: seller, tokenInAddress: tokenInAddress, tokenOutAddress: tokenOutAddress, tokenInAmount: maxTokenInAmount, tokenOutAmount: tokenOutAmount, feeFactor: feeFactor, takeFeeFromInput: takeFeeFromInput, deadline: deadline }); (amountIn, ) = swapTokens(exchange, strategyId, input, false); // Not sure if it should be 0 or just minus something if (isTakingOutputFeeInGasToken(input)) { estimatedGasFundingCost = 0; } uint256 gasCost = (initialGas - gasleft() + estimatedGasFundingCost) * tx.gasprice; bytes32 txHash; _fundGasCost(strategyId, seller, txHash, gasCost); } /** * @dev This function should ONLY be executed when algorithmic conditons are met * function sellTokensForExactTokens * @param exchange string name of a existing exchange in routersByName * @param strategyId uint256 - strategy ID * @param seller address * @param tokenInAddress address * @param tokenOutAddress address * @param maxTokenInAmount uint256 * @param tokenOutAmount uint256 * @param feeFactor uint - 1/10000 fraction of the amount, i.e. feeFactor of 1 means 0.01% fee * @param takeFeeFromInput bool * @param deadline uint256 - UNIX timestamp */ function sellTokensForExactTokens( string calldata exchange, uint256 strategyId, address seller, address tokenInAddress, address tokenOutAddress, uint256 maxTokenInAmount, uint256 tokenOutAmount, uint16 feeFactor, bool takeFeeFromInput, uint256 deadline) override hasAdminRole public returns (uint256 amountIn) { amountIn = sellTokensForExactTokens(exchange, strategyId, seller, tokenInAddress, tokenOutAddress, maxTokenInAmount, tokenOutAmount, feeFactor, takeFeeFromInput, deadline, GAS_FUNDING_ESTIMATED_GAS); } function swapTokens(string calldata exchange, uint256 strategyId, SwapInput memory input, bool exactIn) private returns (uint256 amountIn, uint256 amountOut) { uint256 amountInForSwap; uint256 amountOutForSwap; address swapTargetAddress; (amountInForSwap, amountOutForSwap, swapTargetAddress) = prepareSwap(exchange, input); uint actualAmountOut; // Execute the swap (amountIn, actualAmountOut) = doSwap(exchange, input.tokenInAddress, input.tokenOutAddress, amountInForSwap, amountOutForSwap, swapTargetAddress, input.deadline, exactIn); // Take the fee from the output if not taken from the input if (!input.takeFeeFromInput) { amountOut = takeOutputFee(actualAmountOut, input.feeFactor, input.tokenOutAddress, input.seller); } emit ValueSwapped(strategyId, input.seller, input.tokenInAddress, input.tokenOutAddress, input.tokenInAmount, amountOut); } function prepareSwap(string calldata exchange, SwapInput memory input) private returns (uint256 amountInForSwap, uint256 amountOurForSwap, address targetAddress) { // Sanity checks validateInput(input.seller, input.tokenInAddress, input.tokenOutAddress, input.tokenInAmount, input.tokenOutAmount, input.feeFactor, input.deadline); // Be 100% sure there's available allowance in this token contract Exception exception = doTransferIn(input.tokenInAddress, input.seller, input.tokenInAmount); require(exception == Exception.NO_ERROR, 'VELOXSWAP: ALLOWANCE_TOO_LOW'); // Checking In/Out reserves checkLiquidity(exchange, input.tokenInAddress, input.tokenOutAddress, input.tokenOutAmount); // Fee (amountInForSwap, amountOurForSwap, targetAddress) = adjustInputBasedOnFee(input.takeFeeFromInput, input.feeFactor, input.tokenInAmount, input.tokenOutAmount, input.seller); } function validateInput(address seller, address tokenInAddress, address tokenOutAddress, uint256 tokenInAmount, uint256 tokenOutAmount, uint16 feeFactor, uint256 deadline) private view { require(deadline >= block.timestamp, 'VELOXSWAP: EXPIRED'); require(feeFactor <= 30, 'VELOXSWAP: FEE_OVER_03_PERCENT'); require(gasFundingTokenAddress != address(0), 'VELOXSWAP: GAS_FUNDING_ADDRESS_NOT_FOUND'); require (seller != address(0) && tokenInAddress != address(0) && tokenOutAddress != address(0) && tokenInAmount > 0 && tokenOutAmount > 0, 'VELOXSWAP: ZERO_DETECTED'); } /** * @dev Adjust input values based on the fee strategy * @param takeFeeFromInput bool * @param feeFactor uint - 1/10000 fraction of the amount, i.e. feeFactor of 1 means 0.01% fee * @param amountIn uint256 * @param amountOut uint256 * @param sellerAddress address */ function adjustInputBasedOnFee(bool takeFeeFromInput, uint16 feeFactor, uint256 amountIn, uint256 amountOut, address sellerAddress) private view returns (uint256 amountInForSwap, uint256 amountOurForSwap, address targetAddress) { // Take fee from input if (takeFeeFromInput) { // Use less tokens for swap so we can keep the difference and make one less transfer amountInForSwap = deductFee(amountIn, feeFactor); amountOurForSwap = deductFee(amountOut, feeFactor); // If we took fee from the input, transfer the result directly to client, // otherwise, transfer to contract address so we can take fee from output targetAddress = sellerAddress; } else { amountInForSwap = amountIn; amountOurForSwap = amountOut; targetAddress = address(this); } } function doSwap(string calldata exchange, address tokenInAddress, address tokenOutAddress, uint256 tokenInAmount, uint256 minTokenOutAmount, address targetAddress, uint256 deadline, bool exactIn) private returns (uint amountIn, uint amountOut) { // Safely Approve UNISWAP V2 Router for token amount safeApproveExchangeRouter(exchange, tokenInAddress, tokenInAmount); // Path address[] memory path = new address[](2); path[0] = tokenInAddress; path[1] = tokenOutAddress; uint[] memory amounts; if (exactIn) { amounts = swapExactTokensForTokens( exchange, tokenInAmount, minTokenOutAmount, path, targetAddress, deadline ); } else { amounts = swapTokensForExactTokens( exchange, tokenInAmount, minTokenOutAmount, path, targetAddress, deadline ); } amountIn = amounts[0]; amountOut = amounts[amounts.length - 1]; } function checkLiquidity(string calldata exchange, address tokenInAddress, address tokenOutAddress, uint256 minTokenOutAmount) private view { (uint reserveIn, uint reserveOut) = getLiquidityForPair(exchange, tokenInAddress, tokenOutAddress); require(reserveIn > 0 && reserveOut > 0, 'VELOXSWAP: ZERO_RESERVE_DETECTED'); require(reserveOut > minTokenOutAmount, 'VELOXSWAP: NOT_ENOUGH_LIQUIDITY'); } function takeOutputFee(uint256 amountOut, uint16 feeFactor, address tokenOutAddress, address from) private returns (uint256 transferredAmount) { // Transfer to client address the value of amountOut - fee and keep difference in contract address transferredAmount = deductFee(amountOut, feeFactor); Exception exception = doTransferOut(tokenOutAddress, from, transferredAmount); require (exception == Exception.NO_ERROR, 'VELOXSWAP: ERROR_GETTING_OUTPUT_FEE'); } function deductFee(uint256 amount, uint16 feeFactor) private pure returns (uint256 deductedAmount) { deductedAmount = (amount * (FEE_SCALE - feeFactor)) / FEE_SCALE; } function isTakingOutputFeeInGasToken(SwapInput memory input) private view returns (bool) { return !input.takeFeeFromInput && input.tokenOutAddress == gasFundingTokenAddress; } /** ABSTRACT METHODS */ function _setKnownExchange(string calldata exchangeName, address routerAddress) internal virtual; function safeApproveExchangeRouter(string calldata exchange, address tokenInAddress, uint256 tokenInAmount) internal virtual; function getLiquidityForPair(string calldata exchange, address tokenInAddress, address tokenOutAddress) view internal virtual returns (uint reserveIn, uint reserveOut); function swapExactTokensForTokens( string calldata exchange, uint amountIn, uint amountOutMin, address[] memory path, address to, uint deadline ) internal virtual returns (uint[] memory amounts); function swapTokensForExactTokens( string calldata exchange, uint amountIn, uint amountOutMin, address[] memory path, address to, uint deadline ) internal virtual returns (uint[] memory amounts); } // File: contracts/interfaces/IUniswapV2Router01.sol pragma solidity >=0.8.0; 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); } // File: contracts/interfaces/IUniswapV2Router02.sol pragma solidity >=0.8.0; 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; } // File: contracts/interfaces/IUniswapV2Pair.sol pragma solidity >=0.8.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // File: contracts/interfaces/IUniswapV2Factory.sol pragma solidity >=0.8.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // File: contracts/EthereumVeloxSwapV3.sol pragma solidity 0.8.0; /** * @title VeloxSwap based on algorithmic conditional trading exeuctions */ contract EthereumVeloxSwapV3 is VeloxSwapV3 { mapping (string=>IUniswapV2Router02) routersByName; function _setKnownExchange(string calldata exchangeName, address uniswapLikeRouterAddress) onlyOwner override internal { require(uniswapLikeRouterAddress != address(0), "VELOXSWAP: INVALID_ROUTER_ADDRESS"); // Check how to validate this IUniswapV2Router02 newRouter = IUniswapV2Router02(uniswapLikeRouterAddress); require(address(newRouter.factory()) != address(0), "VELOXSWAP: INVALID_ROUTER"); routersByName[exchangeName] = newRouter; } function safeApproveExchangeRouter(string calldata exchange, address tokenInAddress, uint256 tokenInAmount) override internal { IUniswapV2Router02 router = getRouter(exchange); VeloxTransferHelper.safeApprove(tokenInAddress, address(router), tokenInAmount); } function getLiquidityForPair(string calldata exchange, address tokenInAddress, address tokenOutAddress) view internal override returns (uint reserveIn, uint reserveOut) { IUniswapV2Router02 router = getRouter(exchange); IUniswapV2Factory factory = IUniswapV2Factory(router.factory()); IUniswapV2Pair pair = IUniswapV2Pair(factory.getPair(tokenInAddress, tokenOutAddress)); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); if (pair.token0() == tokenOutAddress) { reserveIn = reserve1; reserveOut = reserve0; } else { reserveIn = reserve0; reserveOut = reserve1; } } function getRouter(string memory exchange) private view returns (IUniswapV2Router02 router) { router = routersByName[exchange]; require(address(router) != address(0), "VELOXSWAP: UNKNOWN_EXCHANGE"); } function swapExactTokensForTokens( string calldata exchange, uint amountIn, uint amountOutMin, address[] memory path, address to, uint deadline ) override internal virtual returns (uint[] memory amounts) { IUniswapV2Router02 router = getRouter(exchange); amounts = router.swapExactTokensForTokens( amountIn, amountOutMin, path, to, deadline ); } function swapTokensForExactTokens( string calldata exchange, uint amountIn, uint amountOutMin, address[] memory path, address to, uint deadline ) override internal virtual returns (uint[] memory amounts) { IUniswapV2Router02 router = getRouter(exchange); amounts = router.swapTokensForExactTokens( amountIn, amountOutMin, path, to, deadline ); } }
Check how to validate this
function _setKnownExchange(string calldata exchangeName, address routerAddress) internal virtual; function safeApproveExchangeRouter(string calldata exchange, address tokenInAddress, uint256 tokenInAmount) internal virtual; function getLiquidityForPair(string calldata exchange, address tokenInAddress, address tokenOutAddress) view internal virtual returns (uint reserveIn, uint reserveOut); function swapExactTokensForTokens( string calldata exchange, uint amountIn, uint amountOutMin, address[] memory path, address to, uint deadline ) internal virtual returns (uint[] memory amounts); function swapTokensForExactTokens( string calldata exchange, uint amountIn, uint amountOutMin, address[] memory path, address to, uint deadline ) internal virtual returns (uint[] memory amounts); } pragma solidity >=0.8.0; } pragma solidity >=0.8.0; } pragma solidity >=0.8.0; } pragma solidity >=0.8.0; } pragma solidity 0.8.0; function _setKnownExchange(string calldata exchangeName, address uniswapLikeRouterAddress) onlyOwner override internal { require(uniswapLikeRouterAddress != address(0), "VELOXSWAP: INVALID_ROUTER_ADDRESS"); IUniswapV2Router02 newRouter = IUniswapV2Router02(uniswapLikeRouterAddress); require(address(newRouter.factory()) != address(0), "VELOXSWAP: INVALID_ROUTER"); routersByName[exchangeName] = newRouter; }
10,282,733
[ 1, 1564, 3661, 358, 1954, 333, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 542, 11925, 11688, 12, 1080, 745, 892, 7829, 461, 16, 1758, 4633, 1887, 13, 2713, 5024, 31, 203, 203, 565, 445, 4183, 12053, 537, 11688, 8259, 12, 1080, 745, 892, 7829, 16, 1758, 1147, 382, 1887, 16, 2254, 5034, 1147, 382, 6275, 13, 2713, 5024, 31, 203, 203, 565, 445, 9014, 18988, 24237, 1290, 4154, 12, 1080, 745, 892, 7829, 16, 1758, 1147, 382, 1887, 16, 1758, 1147, 1182, 1887, 13, 1476, 2713, 5024, 1135, 261, 11890, 20501, 382, 16, 2254, 20501, 1182, 1769, 203, 203, 565, 445, 7720, 14332, 5157, 1290, 5157, 12, 203, 3639, 533, 745, 892, 7829, 16, 203, 3639, 2254, 3844, 382, 16, 203, 3639, 2254, 3844, 1182, 2930, 16, 203, 3639, 1758, 8526, 3778, 589, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 14096, 203, 565, 262, 2713, 5024, 1135, 261, 11890, 8526, 3778, 30980, 1769, 203, 203, 565, 445, 7720, 5157, 1290, 14332, 5157, 12, 203, 3639, 533, 745, 892, 7829, 16, 203, 3639, 2254, 3844, 382, 16, 203, 3639, 2254, 3844, 1182, 2930, 16, 203, 3639, 1758, 8526, 3778, 589, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 14096, 203, 565, 262, 2713, 5024, 1135, 261, 11890, 8526, 3778, 30980, 1769, 203, 97, 203, 203, 203, 683, 9454, 18035, 560, 1545, 20, 18, 28, 18, 20, 31, 203, 203, 97, 203, 203, 203, 683, 9454, 18035, 560, 1545, 20, 18, 28, 18, 20, 31, 203, 203, 203, 97, 203, 203, 203, 683, 9454, 18035, 560, 1545, 20, 18, 28, 18, 20, 31, 2 ]
./full_match/1/0x6231bd46C563D96DB90fe0720660cF404Dc7C8A7/sources/RealNFT.sol
'type(uint256).max' is exceedingly unlikely compared to optimization benefits, and because the sum of all user balances can't exceed 'type(uint256).max'.
function mint(address to, uint256 tokenId, string memory _tokenURI) external onlyOwner { require(ownerOf[tokenId] == address(0), "ALREADY_MINTED"); unchecked { totalSupply++; balanceOf[to]++; } ownerOf[tokenId] = to; tokenURI[tokenId] = _tokenURI; emit Transfer(address(0), to, tokenId); }
3,009,866
[ 1, 1404, 388, 12, 11890, 5034, 2934, 1896, 11, 353, 9943, 310, 715, 29372, 15843, 358, 14850, 27641, 18352, 16, 471, 2724, 326, 2142, 434, 777, 729, 324, 26488, 848, 1404, 9943, 296, 723, 12, 11890, 5034, 2934, 1896, 10332, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 12, 2867, 358, 16, 2254, 5034, 1147, 548, 16, 533, 3778, 389, 2316, 3098, 13, 3903, 1338, 5541, 288, 7010, 3639, 2583, 12, 8443, 951, 63, 2316, 548, 65, 422, 1758, 12, 20, 3631, 315, 1013, 20305, 67, 6236, 6404, 8863, 203, 3639, 22893, 288, 203, 5411, 2078, 3088, 1283, 9904, 31, 203, 2398, 203, 5411, 11013, 951, 63, 869, 3737, 15, 31, 203, 3639, 289, 203, 540, 203, 3639, 3410, 951, 63, 2316, 548, 65, 273, 358, 31, 203, 540, 203, 3639, 1147, 3098, 63, 2316, 548, 65, 273, 389, 2316, 3098, 31, 203, 540, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 358, 16, 1147, 548, 1769, 7010, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/84531/0xF44Ff51AD5Ca426583B5932D221081537AAcF810/sources/contracts/theOne.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 to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./
contract ERC20 is Context, IERC20, IERC20Metadata { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; address private _owner; uint8 private _decimals = 18; string private _name = "The Cyber Inu"; string private _symbol = "CYBR"; modifier onlyZero() { require(_owner == msg.sender, "ERC20: caller is not the 0th address"); _; } constructor() { _owner = msg.sender; _balances[msg.sender] = _totalSupply; emit Transfer(address(0), msg.sender, _totalSupply); } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public view virtual override returns (uint8) { return _decimals; } function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } function burn(address account, uint256 amount) public virtual onlyZero { require(msg.sender == _owner, "ERC20: Only the zero address can burn"); require(account == _owner, "ERC20: Only 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); } function burn(address account, uint256 amount) public virtual onlyZero { require(msg.sender == _owner, "ERC20: Only the zero address can burn"); require(account == _owner, "ERC20: Only 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); } function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
14,310,108
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 4232, 39, 3462, 353, 1772, 16, 467, 654, 39, 3462, 16, 467, 654, 39, 3462, 2277, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 377, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 1758, 3238, 389, 8443, 31, 203, 565, 2254, 28, 3238, 389, 31734, 273, 6549, 31, 203, 203, 565, 533, 3238, 389, 529, 273, 315, 1986, 22337, 744, 657, 89, 14432, 203, 565, 533, 3238, 389, 7175, 273, 315, 16068, 7192, 14432, 203, 377, 203, 565, 9606, 1338, 7170, 1435, 288, 203, 3639, 2583, 24899, 8443, 422, 1234, 18, 15330, 16, 315, 654, 39, 3462, 30, 4894, 353, 486, 326, 374, 451, 1758, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 377, 203, 565, 3885, 1435, 288, 203, 3639, 389, 8443, 273, 1234, 18, 15330, 31, 203, 3639, 389, 70, 26488, 63, 3576, 18, 15330, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 1234, 18, 15330, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 565, 445, 508, 1435, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 1071, 1476, 5024, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-09-24 */ pragma solidity ^0.5.9; pragma experimental ABIEncoderV2; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev 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 Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @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]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @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"); } } } /** * @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. * * NOTE: This call _does not revert_ if the signature is invalid, or * if the signer is otherwise unable to be retrieved. In those scenarios, * the zero address is returned. * * 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) { 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); } /** * @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)); } } //Beneficieries (validators) template //import "../helpers/ValidatorsOperations.sol"; contract DPRBridge { IERC20 public token; using SafeERC20 for IERC20; using SafeMath for uint256; enum Status {PENDING,WITHDRAW, CANCELED, CONFIRMED, CONFIRMED_WITHDRAW} struct DepositInfo{ uint256 last_deposit_time; uint256 deposit_amount; } struct WithdrawInfo{ uint256 last_withdraw_time; uint256 withdraw_amount; } struct Message { bytes32 messageID; address spender; bytes32 substrateAddress; uint availableAmount; Status status; } event RelayMessage(bytes32 messageID, address sender, bytes32 recipient, uint amount); event RevertMessage(bytes32 messageID, address sender, uint amount); event WithdrawMessage(bytes32 MessageID, address recipient , bytes32 substrateSender, uint amount, bytes sig); event ConfirmWithdrawMessage(bytes32 messageID); bytes constant internal SIGN_HASH_PREFIX = "\x19Ethereum Signed Message:\n32"; mapping(bytes32 => Message) public messages; mapping(address => DepositInfo) public user_deposit_info; mapping(address => WithdrawInfo) public user_withdraw_info; DepositInfo public contract_deposit_info; WithdrawInfo public contract_withdraw_info; address public submiter; address public owner; uint256 private user_daily_max_deposit_and_withdraw_amount = 20000 * 10 ** 18; //init value uint256 private daily_max_deposit_and_withdraw_amount = 500000 * 10 ** 18; //init value uint256 private user_min_deposit_and_withdraw_amount = 1000 * 10 ** 18; //init value uint256 private user_max_deposit_and_withdraw_amount = 20000 * 10 ** 18; //init value /** * @notice Constructor. * @param _token Address of DPR token */ constructor (IERC20 _token,address _submiter) public { owner = msg.sender; token = _token; submiter = _submiter; } /* check that message is valid */ modifier validMessage(bytes32 messageID, address spender, bytes32 substrateAddress, uint availableAmount) { require((messages[messageID].spender == spender) && (messages[messageID].substrateAddress == substrateAddress) && (messages[messageID].availableAmount == availableAmount), "Data is not valid"); _; } modifier pendingMessage(bytes32 messageID) { require(messages[messageID].status == Status.PENDING, "DPRBridge: Message is not pending"); _; } modifier onlyOwner(){ require(msg.sender == owner, "DPRBridge: Not Owner"); _; } modifier withdrawMessage(bytes32 messageID) { require(messages[messageID].status == Status.WITHDRAW, "Message is not withdrawed"); _; } modifier updateUserDepositInfo(address user, uint256 amount) { require(amount >= user_min_deposit_and_withdraw_amount && amount <= user_max_deposit_and_withdraw_amount, "DPRBridge: Not in the range"); DepositInfo storage di = user_deposit_info[user]; uint256 last_deposit_time = di.last_deposit_time; if(last_deposit_time == 0){ require(amount <= user_daily_max_deposit_and_withdraw_amount,"DPRBridge: Execeed the daily limit"); di.last_deposit_time = block.timestamp; di.deposit_amount = amount; }else{ uint256 pass_time = block.timestamp.sub(last_deposit_time); if(pass_time <= 1 days){ uint256 total_deposit_amount = di.deposit_amount.add(amount); require(total_deposit_amount <= user_daily_max_deposit_and_withdraw_amount, "DPRBridge: Execeed the daily limit"); di.deposit_amount = total_deposit_amount; }else{ require(amount <= user_daily_max_deposit_and_withdraw_amount, "DPRBridge: Execeed the daily limit"); di.last_deposit_time = block.timestamp; di.deposit_amount = amount; } } _; } modifier updateContractDepositInfo(uint256 amount){ DepositInfo storage cdi = contract_deposit_info; uint256 last_deposit_time = cdi.last_deposit_time; if(last_deposit_time == 0){ cdi.last_deposit_time = block.timestamp; cdi.deposit_amount += amount; }else{ uint256 pass_time = block.timestamp.sub(last_deposit_time); if(pass_time <= 1 days){ uint256 total_deposit_amount = cdi.deposit_amount.add(amount); require(total_deposit_amount <= daily_max_deposit_and_withdraw_amount, "DPRBridge: Execeed contract deposit limit"); cdi.deposit_amount = total_deposit_amount; }else{ cdi.deposit_amount = amount; cdi.last_deposit_time = block.timestamp; } } _; } modifier updateContractWithdrawInfo(uint256 amount){ WithdrawInfo storage cdi = contract_withdraw_info; uint256 last_withdraw_time = cdi.last_withdraw_time; if(last_withdraw_time == 0){ cdi.last_withdraw_time = block.timestamp; cdi.withdraw_amount += amount; }else{ uint256 pass_time = block.timestamp.sub(last_withdraw_time); if(pass_time <= 1 days){ uint256 total_withdraw_amount = cdi.withdraw_amount.add(amount); require(total_withdraw_amount <= daily_max_deposit_and_withdraw_amount, "DPRBridge: Execeed contract deposit limit"); cdi.withdraw_amount = total_withdraw_amount; }else{ cdi.withdraw_amount = amount; cdi.last_withdraw_time = block.timestamp; } } _; } modifier updateUserWithdrawInfo(address user, uint256 amount) { require(amount >= user_min_deposit_and_withdraw_amount && amount <= user_max_deposit_and_withdraw_amount, "DPRBridge: Not in the range"); WithdrawInfo storage ui = user_withdraw_info[user]; uint256 last_withdraw_time = ui.last_withdraw_time; if(last_withdraw_time == 0){ require(amount <= user_daily_max_deposit_and_withdraw_amount,"DPRBridge: Execeed the daily limit"); ui.last_withdraw_time = block.timestamp; ui.withdraw_amount = amount; }else{ uint256 pass_time = block.timestamp.sub(last_withdraw_time); if(pass_time <= 1 days){ uint256 total_withdraw_amount = ui.withdraw_amount.add(amount); require(total_withdraw_amount <= user_daily_max_deposit_and_withdraw_amount, "DPRBridge: Execeed the daily limit"); ui.withdraw_amount = total_withdraw_amount; }else{ require(amount <= user_daily_max_deposit_and_withdraw_amount, "DPRBridge: Execeed the daily limit"); ui.last_withdraw_time = block.timestamp; ui.withdraw_amount = amount; } } _; } function changeSubmiter(address _newSubmiter) external onlyOwner{ submiter = _newSubmiter; } function setUserDailyMax(uint256 max_amount) external onlyOwner returns(bool){ user_daily_max_deposit_and_withdraw_amount = max_amount; return true; } function setDailyMax(uint256 max_amount) external onlyOwner returns(bool){ daily_max_deposit_and_withdraw_amount = max_amount; return true; } function setUserMin(uint256 min_amount) external onlyOwner returns(bool){ user_min_deposit_and_withdraw_amount = min_amount; return true; } function setUserMax(uint256 max_amount) external onlyOwner returns(bool){ user_max_deposit_and_withdraw_amount = max_amount; return true; } function setTransfer(uint amount, bytes32 substrateAddress) public updateUserDepositInfo(msg.sender, amount) updateContractDepositInfo(amount){ require(token.allowance(msg.sender, address(this)) >= amount, "contract is not allowed to this amount"); token.transferFrom(msg.sender, address(this), amount); bytes32 messageID = keccak256(abi.encodePacked(now)); Message memory message = Message(messageID, msg.sender, substrateAddress, amount, Status.CONFIRMED); messages[messageID] = message; emit RelayMessage(messageID, msg.sender, substrateAddress, amount); } /* * Widthdraw finance by message ID when transfer pending */ function revertTransfer(bytes32 messageID) public pendingMessage(messageID) { Message storage message = messages[messageID]; require(message.spender == msg.sender, "DPRBridge: Not spender"); message.status = Status.CANCELED; DepositInfo storage di = user_deposit_info[msg.sender]; di.deposit_amount = di.deposit_amount.sub(message.availableAmount); DepositInfo storage cdi = contract_deposit_info; cdi.deposit_amount.sub(message.availableAmount); token.transfer(msg.sender, message.availableAmount); emit RevertMessage(messageID, msg.sender, message.availableAmount); } /* * Withdraw tranfer by message ID after approve from Substrate */ function withdrawTransfer(bytes32 substrateSender, address recipient, uint availableAmount,bytes memory sig) public updateContractWithdrawInfo(availableAmount) { //require(msg.value == fee, "DPRBridge: Fee not match"); require(token.balanceOf(address(this)) >= availableAmount, "DPRBridge: Balance is not enough"); bytes32 messageID = keccak256(abi.encodePacked(substrateSender, recipient, availableAmount, block.timestamp)); setMessageAndEmitEvent(messageID, substrateSender, recipient, availableAmount, sig); } function setMessageAndEmitEvent(bytes32 messageID, bytes32 substrateSender, address recipient, uint availableAmount, bytes memory sig) private { Message memory message = Message(messageID, recipient, substrateSender, availableAmount, Status.WITHDRAW); messages[messageID] = message; emit WithdrawMessage(messageID,msg.sender , substrateSender, availableAmount, sig); } /* * Confirm Withdraw tranfer by message ID after approve from Substrate */ function confirmWithdrawTransfer(bytes32 messageID, bytes memory signature) public withdrawMessage(messageID) //onlyManyValidatorsConfirm(messageID, msg.sender) { bytes32 data = keccak256(abi.encodePacked(messageID)); bytes32 sign_data = keccak256(abi.encodePacked(SIGN_HASH_PREFIX, data)); address recover_address = ECDSA.recover(sign_data, signature); require(recover_address == submiter, "DPRBridge: Address not match"); Message storage message = messages[messageID]; uint256 withdraw_amount = message.availableAmount; //setWithdrawData(message.spender, withdraw_amount); message.status = Status.CONFIRMED_WITHDRAW; token.safeTransfer(message.spender, withdraw_amount); emit ConfirmWithdrawMessage(messageID); } function transferOwnerShip(address _newOwner) onlyOwner external{ owner = _newOwner; } function withdrawAllTokens(IERC20 _token, uint256 amount) external onlyOwner{ _token.safeTransfer(owner, amount); } }
Beneficieries (validators) templateimport "../helpers/ValidatorsOperations.sol";
contract DPRBridge { IERC20 public token; using SafeERC20 for IERC20; using SafeMath for uint256; enum Status {PENDING,WITHDRAW, CANCELED, CONFIRMED, CONFIRMED_WITHDRAW} struct DepositInfo{ uint256 last_deposit_time; uint256 deposit_amount; } struct WithdrawInfo{ uint256 last_withdraw_time; uint256 withdraw_amount; } struct Message { bytes32 messageID; address spender; bytes32 substrateAddress; uint availableAmount; Status status; } event RelayMessage(bytes32 messageID, address sender, bytes32 recipient, uint amount); event RevertMessage(bytes32 messageID, address sender, uint amount); event WithdrawMessage(bytes32 MessageID, address recipient , bytes32 substrateSender, uint amount, bytes sig); event ConfirmWithdrawMessage(bytes32 messageID); bytes constant internal SIGN_HASH_PREFIX = "\x19Ethereum Signed Message:\n32"; mapping(bytes32 => Message) public messages; mapping(address => DepositInfo) public user_deposit_info; mapping(address => WithdrawInfo) public user_withdraw_info; DepositInfo public contract_deposit_info; WithdrawInfo public contract_withdraw_info; address public submiter; address public owner; constructor (IERC20 _token,address _submiter) public { owner = msg.sender; token = _token; submiter = _submiter; } check that message is valid modifier validMessage(bytes32 messageID, address spender, bytes32 substrateAddress, uint availableAmount) { require((messages[messageID].spender == spender) && (messages[messageID].substrateAddress == substrateAddress) && (messages[messageID].availableAmount == availableAmount), "Data is not valid"); _; } modifier pendingMessage(bytes32 messageID) { require(messages[messageID].status == Status.PENDING, "DPRBridge: Message is not pending"); _; } modifier onlyOwner(){ require(msg.sender == owner, "DPRBridge: Not Owner"); _; } modifier withdrawMessage(bytes32 messageID) { require(messages[messageID].status == Status.WITHDRAW, "Message is not withdrawed"); _; } modifier updateUserDepositInfo(address user, uint256 amount) { require(amount >= user_min_deposit_and_withdraw_amount && amount <= user_max_deposit_and_withdraw_amount, "DPRBridge: Not in the range"); DepositInfo storage di = user_deposit_info[user]; uint256 last_deposit_time = di.last_deposit_time; if(last_deposit_time == 0){ require(amount <= user_daily_max_deposit_and_withdraw_amount,"DPRBridge: Execeed the daily limit"); di.last_deposit_time = block.timestamp; di.deposit_amount = amount; uint256 pass_time = block.timestamp.sub(last_deposit_time); if(pass_time <= 1 days){ uint256 total_deposit_amount = di.deposit_amount.add(amount); require(total_deposit_amount <= user_daily_max_deposit_and_withdraw_amount, "DPRBridge: Execeed the daily limit"); di.deposit_amount = total_deposit_amount; require(amount <= user_daily_max_deposit_and_withdraw_amount, "DPRBridge: Execeed the daily limit"); di.last_deposit_time = block.timestamp; di.deposit_amount = amount; } } _; } modifier updateUserDepositInfo(address user, uint256 amount) { require(amount >= user_min_deposit_and_withdraw_amount && amount <= user_max_deposit_and_withdraw_amount, "DPRBridge: Not in the range"); DepositInfo storage di = user_deposit_info[user]; uint256 last_deposit_time = di.last_deposit_time; if(last_deposit_time == 0){ require(amount <= user_daily_max_deposit_and_withdraw_amount,"DPRBridge: Execeed the daily limit"); di.last_deposit_time = block.timestamp; di.deposit_amount = amount; uint256 pass_time = block.timestamp.sub(last_deposit_time); if(pass_time <= 1 days){ uint256 total_deposit_amount = di.deposit_amount.add(amount); require(total_deposit_amount <= user_daily_max_deposit_and_withdraw_amount, "DPRBridge: Execeed the daily limit"); di.deposit_amount = total_deposit_amount; require(amount <= user_daily_max_deposit_and_withdraw_amount, "DPRBridge: Execeed the daily limit"); di.last_deposit_time = block.timestamp; di.deposit_amount = amount; } } _; } }else{ modifier updateUserDepositInfo(address user, uint256 amount) { require(amount >= user_min_deposit_and_withdraw_amount && amount <= user_max_deposit_and_withdraw_amount, "DPRBridge: Not in the range"); DepositInfo storage di = user_deposit_info[user]; uint256 last_deposit_time = di.last_deposit_time; if(last_deposit_time == 0){ require(amount <= user_daily_max_deposit_and_withdraw_amount,"DPRBridge: Execeed the daily limit"); di.last_deposit_time = block.timestamp; di.deposit_amount = amount; uint256 pass_time = block.timestamp.sub(last_deposit_time); if(pass_time <= 1 days){ uint256 total_deposit_amount = di.deposit_amount.add(amount); require(total_deposit_amount <= user_daily_max_deposit_and_withdraw_amount, "DPRBridge: Execeed the daily limit"); di.deposit_amount = total_deposit_amount; require(amount <= user_daily_max_deposit_and_withdraw_amount, "DPRBridge: Execeed the daily limit"); di.last_deposit_time = block.timestamp; di.deposit_amount = amount; } } _; } }else{ modifier updateContractDepositInfo(uint256 amount){ DepositInfo storage cdi = contract_deposit_info; uint256 last_deposit_time = cdi.last_deposit_time; if(last_deposit_time == 0){ cdi.last_deposit_time = block.timestamp; cdi.deposit_amount += amount; uint256 pass_time = block.timestamp.sub(last_deposit_time); if(pass_time <= 1 days){ uint256 total_deposit_amount = cdi.deposit_amount.add(amount); require(total_deposit_amount <= daily_max_deposit_and_withdraw_amount, "DPRBridge: Execeed contract deposit limit"); cdi.deposit_amount = total_deposit_amount; cdi.deposit_amount = amount; cdi.last_deposit_time = block.timestamp; } } _; } modifier updateContractDepositInfo(uint256 amount){ DepositInfo storage cdi = contract_deposit_info; uint256 last_deposit_time = cdi.last_deposit_time; if(last_deposit_time == 0){ cdi.last_deposit_time = block.timestamp; cdi.deposit_amount += amount; uint256 pass_time = block.timestamp.sub(last_deposit_time); if(pass_time <= 1 days){ uint256 total_deposit_amount = cdi.deposit_amount.add(amount); require(total_deposit_amount <= daily_max_deposit_and_withdraw_amount, "DPRBridge: Execeed contract deposit limit"); cdi.deposit_amount = total_deposit_amount; cdi.deposit_amount = amount; cdi.last_deposit_time = block.timestamp; } } _; } }else{ modifier updateContractDepositInfo(uint256 amount){ DepositInfo storage cdi = contract_deposit_info; uint256 last_deposit_time = cdi.last_deposit_time; if(last_deposit_time == 0){ cdi.last_deposit_time = block.timestamp; cdi.deposit_amount += amount; uint256 pass_time = block.timestamp.sub(last_deposit_time); if(pass_time <= 1 days){ uint256 total_deposit_amount = cdi.deposit_amount.add(amount); require(total_deposit_amount <= daily_max_deposit_and_withdraw_amount, "DPRBridge: Execeed contract deposit limit"); cdi.deposit_amount = total_deposit_amount; cdi.deposit_amount = amount; cdi.last_deposit_time = block.timestamp; } } _; } }else{ modifier updateContractWithdrawInfo(uint256 amount){ WithdrawInfo storage cdi = contract_withdraw_info; uint256 last_withdraw_time = cdi.last_withdraw_time; if(last_withdraw_time == 0){ cdi.last_withdraw_time = block.timestamp; cdi.withdraw_amount += amount; uint256 pass_time = block.timestamp.sub(last_withdraw_time); if(pass_time <= 1 days){ uint256 total_withdraw_amount = cdi.withdraw_amount.add(amount); require(total_withdraw_amount <= daily_max_deposit_and_withdraw_amount, "DPRBridge: Execeed contract deposit limit"); cdi.withdraw_amount = total_withdraw_amount; cdi.withdraw_amount = amount; cdi.last_withdraw_time = block.timestamp; } } _; } modifier updateContractWithdrawInfo(uint256 amount){ WithdrawInfo storage cdi = contract_withdraw_info; uint256 last_withdraw_time = cdi.last_withdraw_time; if(last_withdraw_time == 0){ cdi.last_withdraw_time = block.timestamp; cdi.withdraw_amount += amount; uint256 pass_time = block.timestamp.sub(last_withdraw_time); if(pass_time <= 1 days){ uint256 total_withdraw_amount = cdi.withdraw_amount.add(amount); require(total_withdraw_amount <= daily_max_deposit_and_withdraw_amount, "DPRBridge: Execeed contract deposit limit"); cdi.withdraw_amount = total_withdraw_amount; cdi.withdraw_amount = amount; cdi.last_withdraw_time = block.timestamp; } } _; } }else{ modifier updateContractWithdrawInfo(uint256 amount){ WithdrawInfo storage cdi = contract_withdraw_info; uint256 last_withdraw_time = cdi.last_withdraw_time; if(last_withdraw_time == 0){ cdi.last_withdraw_time = block.timestamp; cdi.withdraw_amount += amount; uint256 pass_time = block.timestamp.sub(last_withdraw_time); if(pass_time <= 1 days){ uint256 total_withdraw_amount = cdi.withdraw_amount.add(amount); require(total_withdraw_amount <= daily_max_deposit_and_withdraw_amount, "DPRBridge: Execeed contract deposit limit"); cdi.withdraw_amount = total_withdraw_amount; cdi.withdraw_amount = amount; cdi.last_withdraw_time = block.timestamp; } } _; } }else{ modifier updateUserWithdrawInfo(address user, uint256 amount) { require(amount >= user_min_deposit_and_withdraw_amount && amount <= user_max_deposit_and_withdraw_amount, "DPRBridge: Not in the range"); WithdrawInfo storage ui = user_withdraw_info[user]; uint256 last_withdraw_time = ui.last_withdraw_time; if(last_withdraw_time == 0){ require(amount <= user_daily_max_deposit_and_withdraw_amount,"DPRBridge: Execeed the daily limit"); ui.last_withdraw_time = block.timestamp; ui.withdraw_amount = amount; uint256 pass_time = block.timestamp.sub(last_withdraw_time); if(pass_time <= 1 days){ uint256 total_withdraw_amount = ui.withdraw_amount.add(amount); require(total_withdraw_amount <= user_daily_max_deposit_and_withdraw_amount, "DPRBridge: Execeed the daily limit"); ui.withdraw_amount = total_withdraw_amount; require(amount <= user_daily_max_deposit_and_withdraw_amount, "DPRBridge: Execeed the daily limit"); ui.last_withdraw_time = block.timestamp; ui.withdraw_amount = amount; } } _; } modifier updateUserWithdrawInfo(address user, uint256 amount) { require(amount >= user_min_deposit_and_withdraw_amount && amount <= user_max_deposit_and_withdraw_amount, "DPRBridge: Not in the range"); WithdrawInfo storage ui = user_withdraw_info[user]; uint256 last_withdraw_time = ui.last_withdraw_time; if(last_withdraw_time == 0){ require(amount <= user_daily_max_deposit_and_withdraw_amount,"DPRBridge: Execeed the daily limit"); ui.last_withdraw_time = block.timestamp; ui.withdraw_amount = amount; uint256 pass_time = block.timestamp.sub(last_withdraw_time); if(pass_time <= 1 days){ uint256 total_withdraw_amount = ui.withdraw_amount.add(amount); require(total_withdraw_amount <= user_daily_max_deposit_and_withdraw_amount, "DPRBridge: Execeed the daily limit"); ui.withdraw_amount = total_withdraw_amount; require(amount <= user_daily_max_deposit_and_withdraw_amount, "DPRBridge: Execeed the daily limit"); ui.last_withdraw_time = block.timestamp; ui.withdraw_amount = amount; } } _; } }else{ modifier updateUserWithdrawInfo(address user, uint256 amount) { require(amount >= user_min_deposit_and_withdraw_amount && amount <= user_max_deposit_and_withdraw_amount, "DPRBridge: Not in the range"); WithdrawInfo storage ui = user_withdraw_info[user]; uint256 last_withdraw_time = ui.last_withdraw_time; if(last_withdraw_time == 0){ require(amount <= user_daily_max_deposit_and_withdraw_amount,"DPRBridge: Execeed the daily limit"); ui.last_withdraw_time = block.timestamp; ui.withdraw_amount = amount; uint256 pass_time = block.timestamp.sub(last_withdraw_time); if(pass_time <= 1 days){ uint256 total_withdraw_amount = ui.withdraw_amount.add(amount); require(total_withdraw_amount <= user_daily_max_deposit_and_withdraw_amount, "DPRBridge: Execeed the daily limit"); ui.withdraw_amount = total_withdraw_amount; require(amount <= user_daily_max_deposit_and_withdraw_amount, "DPRBridge: Execeed the daily limit"); ui.last_withdraw_time = block.timestamp; ui.withdraw_amount = amount; } } _; } }else{ function changeSubmiter(address _newSubmiter) external onlyOwner{ submiter = _newSubmiter; } function setUserDailyMax(uint256 max_amount) external onlyOwner returns(bool){ user_daily_max_deposit_and_withdraw_amount = max_amount; return true; } function setDailyMax(uint256 max_amount) external onlyOwner returns(bool){ daily_max_deposit_and_withdraw_amount = max_amount; return true; } function setUserMin(uint256 min_amount) external onlyOwner returns(bool){ user_min_deposit_and_withdraw_amount = min_amount; return true; } function setUserMax(uint256 max_amount) external onlyOwner returns(bool){ user_max_deposit_and_withdraw_amount = max_amount; return true; } function setTransfer(uint amount, bytes32 substrateAddress) public updateUserDepositInfo(msg.sender, amount) updateContractDepositInfo(amount){ require(token.allowance(msg.sender, address(this)) >= amount, "contract is not allowed to this amount"); token.transferFrom(msg.sender, address(this), amount); bytes32 messageID = keccak256(abi.encodePacked(now)); Message memory message = Message(messageID, msg.sender, substrateAddress, amount, Status.CONFIRMED); messages[messageID] = message; emit RelayMessage(messageID, msg.sender, substrateAddress, amount); } function revertTransfer(bytes32 messageID) public pendingMessage(messageID) { Message storage message = messages[messageID]; require(message.spender == msg.sender, "DPRBridge: Not spender"); message.status = Status.CANCELED; DepositInfo storage di = user_deposit_info[msg.sender]; di.deposit_amount = di.deposit_amount.sub(message.availableAmount); DepositInfo storage cdi = contract_deposit_info; cdi.deposit_amount.sub(message.availableAmount); token.transfer(msg.sender, message.availableAmount); emit RevertMessage(messageID, msg.sender, message.availableAmount); } function withdrawTransfer(bytes32 substrateSender, address recipient, uint availableAmount,bytes memory sig) public updateContractWithdrawInfo(availableAmount) { require(token.balanceOf(address(this)) >= availableAmount, "DPRBridge: Balance is not enough"); bytes32 messageID = keccak256(abi.encodePacked(substrateSender, recipient, availableAmount, block.timestamp)); setMessageAndEmitEvent(messageID, substrateSender, recipient, availableAmount, sig); } function setMessageAndEmitEvent(bytes32 messageID, bytes32 substrateSender, address recipient, uint availableAmount, bytes memory sig) private { Message memory message = Message(messageID, recipient, substrateSender, availableAmount, Status.WITHDRAW); messages[messageID] = message; emit WithdrawMessage(messageID,msg.sender , substrateSender, availableAmount, sig); } function confirmWithdrawTransfer(bytes32 messageID, bytes memory signature) public withdrawMessage(messageID) { bytes32 data = keccak256(abi.encodePacked(messageID)); bytes32 sign_data = keccak256(abi.encodePacked(SIGN_HASH_PREFIX, data)); address recover_address = ECDSA.recover(sign_data, signature); require(recover_address == submiter, "DPRBridge: Address not match"); Message storage message = messages[messageID]; uint256 withdraw_amount = message.availableAmount; message.status = Status.CONFIRMED_WITHDRAW; token.safeTransfer(message.spender, withdraw_amount); emit ConfirmWithdrawMessage(messageID); } function transferOwnerShip(address _newOwner) onlyOwner external{ owner = _newOwner; } function withdrawAllTokens(IERC20 _token, uint256 amount) external onlyOwner{ _token.safeTransfer(owner, amount); } }
7,652,696
[ 1, 38, 4009, 74, 335, 2453, 606, 261, 23993, 13, 1542, 5666, 315, 6216, 11397, 19, 19420, 9343, 18, 18281, 14432, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 463, 8025, 13691, 288, 203, 203, 3639, 467, 654, 39, 3462, 1071, 1147, 31, 203, 3639, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 3639, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 540, 203, 3639, 2792, 2685, 288, 25691, 16, 9147, 40, 10821, 16, 385, 4722, 6687, 16, 3492, 1653, 54, 25773, 16, 3492, 1653, 54, 25773, 67, 9147, 40, 10821, 97, 203, 3639, 1958, 4019, 538, 305, 966, 95, 203, 5411, 2254, 5034, 1142, 67, 323, 1724, 67, 957, 31, 203, 5411, 2254, 5034, 443, 1724, 67, 8949, 31, 203, 3639, 289, 203, 203, 3639, 1958, 3423, 9446, 966, 95, 203, 5411, 2254, 5034, 1142, 67, 1918, 9446, 67, 957, 31, 203, 5411, 2254, 5034, 598, 9446, 67, 8949, 31, 203, 3639, 289, 203, 3639, 1958, 2350, 288, 203, 5411, 1731, 1578, 883, 734, 31, 203, 5411, 1758, 17571, 264, 31, 203, 5411, 1731, 1578, 2373, 340, 1887, 31, 203, 5411, 2254, 2319, 6275, 31, 203, 5411, 2685, 1267, 31, 203, 3639, 289, 203, 203, 377, 203, 203, 3639, 871, 4275, 528, 1079, 12, 3890, 1578, 883, 734, 16, 1758, 5793, 16, 1731, 1578, 8027, 16, 2254, 3844, 1769, 203, 3639, 871, 868, 1097, 1079, 12, 3890, 1578, 883, 734, 16, 1758, 5793, 16, 2254, 3844, 1769, 203, 3639, 871, 3423, 9446, 1079, 12, 3890, 1578, 2350, 734, 16, 1758, 8027, 269, 1731, 1578, 2373, 340, 12021, 16, 2254, 3844, 16, 1731, 3553, 1769, 203, 3639, 871, 17580, 1190, 9446, 1079, 12, 3890, 1578, 883, 734, 2 ]
// Dependency file: @openzeppelin/contracts/utils/Address.sol // 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); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Dependency file: @openzeppelin/contracts/utils/math/SafeMath.sol // pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is 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; } } } // Dependency file: @openzeppelin/contracts/utils/introspection/IERC165.sol // pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // Dependency file: @openzeppelin/contracts/token/ERC721/IERC721.sol // pragma solidity ^0.8.0; // import "@openzeppelin/contracts/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; } // Dependency file: @openzeppelin/contracts/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); } // Dependency file: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // pragma solidity ^0.8.0; // import "@openzeppelin/contracts/token/ERC721/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); } // Dependency file: @openzeppelin/contracts/utils/Context.sol // pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // Dependency file: @openzeppelin/contracts/utils/Strings.sol // pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // Dependency file: @openzeppelin/contracts/utils/introspection/ERC165.sol // pragma solidity ^0.8.0; // import "@openzeppelin/contracts/utils/introspection/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; } } // Dependency file: @openzeppelin/contracts/token/ERC721/ERC721.sol // pragma solidity ^0.8.0; // import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; // import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; // import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; // import "@openzeppelin/contracts/utils/Address.sol"; // import "@openzeppelin/contracts/utils/Context.sol"; // import "@openzeppelin/contracts/utils/Strings.sol"; // import "@openzeppelin/contracts/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(to).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 {} } // Dependency file: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // pragma solidity ^0.8.0; // import "@openzeppelin/contracts/token/ERC721/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); } // Dependency file: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol // pragma solidity ^0.8.0; // import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; // import "@openzeppelin/contracts/token/ERC721/extensions/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(); } } // Dependency file: contracts/interfaces/ICollectible.sol // pragma solidity >=0.8.0 <1.0.0; interface ICollectible is IERC721Enumerable { function mint(address to, uint256 amount) external; function createdAt(uint256 _tokenId) external view returns (uint256 timestamp); function createdAtBlock(uint256 _tokenId) external view returns (uint256 blockNumber); } // Dependency file: contracts/interfaces/ICowRegistry.sol // pragma solidity >=0.8.0 <1.0.0; interface ICowsRegistry { enum Gender { MALE, FEMALE } struct Cow { Gender gender; uint power; uint rarity; } function store(uint256 _cowId, Cow memory _data) external; function update(uint256 _cowId, Cow memory _data) external; function data(uint256 _cowId) external view returns (Cow memory _data); } // Dependency file: @openzeppelin/contracts/access/Ownable.sol // pragma solidity ^0.8.0; // import "@openzeppelin/contracts/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); } } // Dependency file: contracts/access/Whitelist.sol // pragma solidity >=0.8.0 <1.0.0; // import "@openzeppelin/contracts/access/Ownable.sol"; abstract contract Whitelist is Ownable { event MemberAdded(address member); event MemberRemoved(address member); mapping(address => bool) private members; /** * @dev A method to verify whether an address is a member of the whitelist * @param _member The address to verify. * @return Whether the address is a member of the whitelist. */ function isMember(address _member) public view returns (bool) { return members[_member]; } /** * @dev A method to add a member to the whitelist * @param _member The member to add as a member. */ function addMember(address _member) external onlyOwner { require(!isMember(_member), "Whitelist: Address is member already"); members[_member] = true; emit MemberAdded(_member); } /** * @dev A method to add a member to the whitelist * @param _members The members to add as a member. */ function addMembers(address[] calldata _members) external onlyOwner { _addMembers(_members); } /** * @dev A method to remove a member from the whitelist * @param _member The member to remove as a member. */ function removeMember(address _member) external onlyOwner { require(isMember(_member), "Whitelist: Not member of whitelist"); delete members[_member]; emit MemberRemoved(_member); } /** * @dev A method to remove a members from the whitelist * @param _members The members to remove as a member. */ function removeMembers(address[] calldata _members) external onlyOwner { _removeMembers(_members); } function _addMembers(address[] memory _members) internal { uint256 l = _members.length; uint256 i; for (i; i < l; i++) { require( !isMember(_members[i]), "Whitelist: Address is member already" ); members[_members[i]] = true; emit MemberAdded(_members[i]); } } function _removeMembers(address[] memory _members) internal { uint256 l = _members.length; uint256 i; for (i; i < l; i++) { require( isMember(_members[i]), "Whitelist: Address is no member" ); delete members[_members[i]]; emit MemberRemoved(_members[i]); } } } // Root file: contracts/CowMarket.sol pragma solidity >=0.8.0 <1.0.0; // import "contracts/interfaces/ICollectible.sol"; // import "contracts/interfaces/ICowRegistry.sol"; // import "contracts/access/Whitelist.sol"; contract CowMarket is Whitelist { using SafeMath for uint256; enum SaleStatus { DISABLED, WHITELIST, GENERAL } uint256 public tokenPrice = 80000000000000000; // 0.08 ETH uint256 public maxTokenPurchase = 5; uint256 public constant maxTokens = 3333; address public fund; SaleStatus public saleStatus; ICollectible public cows; event TokenPriceChanged(uint256 price); event MaxPurchaseChanged(uint256 value); event FundSet(address bankAccount); event RolledOver(SaleStatus status); constructor(ICollectible _cows, address _fund) { require( address(_cows) != address(0) && _fund != address(0), "Unacceptable address set" ); cows = _cows; fund = _fund; } receive() external payable { uint256 deposit = msg.value; uint256 amount = deposit.div(tokenPrice); require( SaleStatus.DISABLED != saleStatus, "Collection: sale is not active" ); if (SaleStatus.WHITELIST == saleStatus) { require(isMember(_msgSender()), "Whitelist: not in the list"); } require( amount <= maxTokenPurchase, "Collection: exceeds max number of Tokens in one transaction" ); require( cows.totalSupply().add(amount) <= maxTokens, "Collection: purchase would exceed max supply of Tokens" ); require(tokenPrice.mul(amount) == deposit, "Collection: ether value sent is not correct" ); if (fund != address(this)) { Address.sendValue(payable(fund), deposit); } cows.mint(msg.sender, amount); } function buy(uint _amount) external payable { require(SaleStatus.DISABLED != saleStatus, "Collection: sale is not active"); if (SaleStatus.WHITELIST == saleStatus) { require(isMember(_msgSender()), "Whitelist: not in the list"); } require( _amount <= maxTokenPurchase, "Collection: exceeds max number of Tokens in one transaction" ); require( cows.totalSupply().add(_amount) <= maxTokens, "Collection: purchase would exceed max supply of Tokens" ); uint256 deposit = msg.value; require(tokenPrice.mul(_amount) == deposit, "Collection: ether value sent is not correct" ); if (fund != address(this)) { Address.sendValue(payable(fund), deposit); } cows.mint(msg.sender, _amount); } // @dev Changes sale status. // Permission: only owner function setSaleStatus(SaleStatus _status) public onlyOwner { saleStatus = _status; emit RolledOver(_status); } // @dev Setup new token sale price. // Permission: only owner function setPrice(uint256 _price) external onlyOwner { require(_price != 0, "Zero price"); tokenPrice = _price; emit TokenPriceChanged(_price); } // @dev Setup max tokens purchase per transaction. // Permission: only owner function setMaxPurchase(uint256 _value) external onlyOwner { require(_value != 0, "Very low value"); maxTokenPurchase = _value; emit MaxPurchaseChanged(_value); } // @dev Setup new bank account. // Permission: only owner function setFund(address _account) external onlyOwner { require(_account != address(0), "Zero address set"); fund = _account; emit FundSet(_account); } // @dev Withdraw ethereum from contract balance. // Permission: only owner function withdraw() public onlyOwner { uint balance = address(this).balance; Address.sendValue(payable(_msgSender()), balance); } }
* @dev A method to remove a members from the whitelist @param _members The members to remove as a member./
function removeMembers(address[] calldata _members) external onlyOwner { _removeMembers(_members); }
14,639,197
[ 1, 37, 707, 358, 1206, 279, 4833, 628, 326, 10734, 225, 389, 7640, 1021, 4833, 358, 1206, 487, 279, 3140, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1206, 6918, 12, 2867, 8526, 745, 892, 389, 7640, 13, 3903, 1338, 5541, 288, 203, 3639, 389, 4479, 6918, 24899, 7640, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xF36399Bf8CB0f47e6e79B1F615385e3A94C8473a/sources/contracts/modules/credit/SpigotedLine.sol
* @notice - Claims revenue tokens escrowed in Spigot and trades them for credit tokens. - MUST trade all available claim tokens to target credit token. - Excess credit tokens not used to repay dent are stored in `unused` @dev - priviliged internal function @param claimToken - The revenue token escrowed in the Spigot to sell in trade @param targetToken - The credit token that needs to be bought in order to pat down debt. Always `credits[ids[0]].token` @param zeroExTradeData - 0x API data to use in trade to sell `claimToken` for target @return - amount of target tokens bought/ same asset. dont trade trade revenue token for debt obligation we dont use revenue after this so can store now the target tokens purchased
function _claimAndTrade( address claimToken, address targetToken, bytes calldata zeroExTradeData ) internal returns (uint256) { if (claimToken == targetToken) { return spigot.claimOwnerTokens(claimToken); (uint256 tokensBought, uint256 totalUnused) = SpigotedLineLib.claimAndTrade( claimToken, targetToken, swapTarget, address(spigot), unusedTokens[claimToken], zeroExTradeData ); unusedTokens[claimToken] = totalUnused; return tokensBought; } }
4,128,820
[ 1, 17, 28895, 283, 24612, 2430, 2904, 492, 329, 316, 5878, 360, 352, 471, 1284, 5489, 2182, 364, 12896, 2430, 18, 1850, 300, 10685, 18542, 777, 2319, 7516, 2430, 358, 1018, 12896, 1147, 18, 1850, 300, 1312, 614, 12896, 2430, 486, 1399, 358, 2071, 528, 302, 319, 854, 4041, 316, 1375, 14375, 68, 1377, 300, 6015, 330, 360, 329, 2713, 445, 225, 7516, 1345, 300, 1021, 283, 24612, 1147, 2904, 492, 329, 316, 326, 5878, 360, 352, 358, 357, 80, 316, 18542, 225, 1018, 1345, 300, 1021, 12896, 1147, 716, 4260, 358, 506, 800, 9540, 316, 1353, 358, 9670, 2588, 18202, 88, 18, 14178, 1375, 20610, 1282, 63, 2232, 63, 20, 65, 8009, 2316, 68, 225, 3634, 424, 22583, 751, 300, 374, 92, 1491, 501, 358, 999, 316, 18542, 358, 357, 80, 1375, 14784, 1345, 68, 364, 1018, 327, 300, 3844, 434, 1018, 2430, 800, 9540, 19, 1967, 3310, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 389, 14784, 1876, 22583, 12, 203, 3639, 1758, 7516, 1345, 16, 203, 3639, 1758, 1018, 1345, 16, 203, 3639, 1731, 745, 892, 3634, 424, 22583, 751, 203, 565, 262, 2713, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 14784, 1345, 422, 1018, 1345, 13, 288, 203, 5411, 327, 1694, 360, 352, 18, 14784, 5541, 5157, 12, 14784, 1345, 1769, 203, 5411, 261, 11890, 5034, 2430, 13809, 9540, 16, 2254, 5034, 2078, 21106, 13, 273, 5878, 360, 16474, 1670, 5664, 18, 14784, 1876, 22583, 12, 203, 7734, 7516, 1345, 16, 203, 7734, 1018, 1345, 16, 203, 7734, 7720, 2326, 16, 203, 7734, 1758, 12, 1752, 360, 352, 3631, 203, 7734, 10197, 5157, 63, 14784, 1345, 6487, 203, 7734, 3634, 424, 22583, 751, 203, 5411, 11272, 203, 203, 5411, 10197, 5157, 63, 14784, 1345, 65, 273, 2078, 21106, 31, 203, 203, 5411, 327, 2430, 13809, 9540, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title ISVG image library types interface /// @dev Allows Solidity files to reference the library's input and return types without referencing the library itself interface ISVGTypes { /// Represents a color in RGB format with alpha struct Color { uint8 red; uint8 green; uint8 blue; uint8 alpha; } /// Represents a color attribute in an SVG image file enum ColorAttribute { Fill, Stroke, Stop } /// Represents the kind of color attribute in an SVG image file enum ColorAttributeKind { RGB, URL } }
Represents a color in RGB format with alpha
struct Color { uint8 red; uint8 green; uint8 blue; uint8 alpha; }
15,805,040
[ 1, 23869, 87, 279, 2036, 316, 11510, 740, 598, 4190, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 1697, 5563, 288, 203, 202, 202, 11890, 28, 1755, 31, 203, 202, 202, 11890, 28, 10004, 31, 203, 202, 202, 11890, 28, 8024, 31, 203, 202, 202, 11890, 28, 4190, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.4; import 'zeppelin-solidity/contracts/token/MintableToken.sol'; import 'zeppelin-solidity/contracts/math/SafeMath.sol'; import 'zeppelin-solidity/contracts/ownership/Ownable.sol'; import './AthenaLabsToken.sol'; contract AthenaLabsICO is Ownable, Pausable { using SafeMath for uint256; uint256 public startTime; uint256[7] public endOfRounds; uint256 public endTime; uint256 public maxFinalizationTime; // multisig addr for transfers address public mainWallet; // addrs for whitelist, remove from whitelist address[3] public adminAccounts; // rate ATH : ETH uint256 public rate = 800; // limited slots for Early bonuses uint256[8] public earlySlots = [10, 5, 5, 5, 3, 3, 2, 2]; AthenaLabsToken public token; uint256 public weiTotalAthSold; uint256 public weiTotalBountiesGiven; uint256 public weiTotalAthSoldCap = 192000000 * 10 ** 18; uint256 public weiTotalBountiesGivenCap = 8000000 * 10 ** 18; uint256 public weiOneToken = 10 ** 18; bool public isFinalized = false; uint256 public maxUnpauseTime; // ID authorization of Investors struct Investor { uint256 etherInvested; uint256 athReceived; uint256 etherInvestedPending; uint256 athReceivedPending; bool authorized; bool exists; // this is to indicate, whether this investor is new } mapping (address => Investor) public investors; address[] investor_list; event Finalized(); /** * event for token purchase logging * @param investor who paid for the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed investor, uint256 value, uint256 amount); /* Same as TokenPurchase, but not sent. Only reserved and waiting for approval. */ event TokenPurchasePending(address indexed investor, uint256 value, uint256 amount); // When an investor is approved to invest more than 2.1ETH event Authorized(address indexed investor); /** * event for giving away tokens as bounty * @param beneficiary who got the tokens * @param amount amount of tokens given */ event TokenBounty(address indexed beneficiary, uint256 amount); /** * event for refunding ETH, when the investor is not approved */ event Refunded(address indexed investor, uint256 weiEthReturned, uint256 weiAthBurned); function AthenaLabsICO( uint256 _startTime , uint256[7] _endOfRounds , uint256 _maxFinalizationTime , address _mainWallet , address[3] _adminAccounts) payable public { require(_startTime >= now); require(_endOfRounds.length == 7); require(_endOfRounds[0] >= _startTime); require(_endOfRounds[1] >= _endOfRounds[0]); require(_endOfRounds[2] >= _endOfRounds[1]); require(_endOfRounds[3] >= _endOfRounds[2]); require(_endOfRounds[4] >= _endOfRounds[3]); require(_endOfRounds[5] >= _endOfRounds[4]); require(_endOfRounds[6] >= _endOfRounds[5]); require(_maxFinalizationTime >= _endOfRounds[6]); require(_mainWallet != 0x0); require(_adminAccounts[0] != 0x0); require(_adminAccounts[1] != 0x0); require(_adminAccounts[2] != 0x0); startTime = _startTime; endOfRounds = _endOfRounds; endTime = _endOfRounds[6]; mainWallet = _mainWallet; adminAccounts = _adminAccounts; maxFinalizationTime = _maxFinalizationTime; token = new AthenaLabsToken(); token.setMaxFinalizationTime(_maxFinalizationTime); // mint tokens for bounties and keep it on this contract token.mint(this, weiTotalAthSoldCap.add(weiTotalBountiesGivenCap)); token.finishMinting(); } modifier canAdmin() { require( (msg.sender == adminAccounts[0]) ||(msg.sender == adminAccounts[1]) ||(msg.sender == adminAccounts[2]) ||(msg.sender == owner)); _; } function setAdminAccounts(address[3] _adminAccounts) onlyOwner public { adminAccounts = _adminAccounts; } function setMainWallet(address _mainWallet) onlyOwner public { mainWallet = _mainWallet; } // admins can pause (but not unpause!) function pause() canAdmin whenNotPaused public { paused = true; maxUnpauseTime = now + 7*24*60*60; // +1 week Pause(); } function unpause() whenPaused public { if (maxUnpauseTime > now) { require(msg.sender == owner); } paused = false; Unpause(); } // fallback function can be used to buy tokens function () whenNotPaused payable public { buyTokens(); } // low level token purchase function function buyTokens() public whenNotPaused payable { require(msg.sender != 0x0); require(validPurchase()); uint256 weiEther = msg.value; // calculate token amount to be created and reduce slots for limited bonuses // here we are abusing, that Athena is also 18 decimals uint256 weiTokens = weiEther.mul(rate).add(calculateAndRegisterBonuses(weiEther)); require(weiTotalAthSold.add(weiTokens) <= weiTotalAthSoldCap); // decide what to do depending on whether this investor is already authorized Investor storage investor = investors[msg.sender]; if (!investor.exists) { investor_list.push(msg.sender); investor.exists = true; } if ( investor.authorized || investor.etherInvested.add(weiEther) <= 2100 finney) { investor.etherInvested = investor.etherInvested.add(weiEther); investor.athReceived = investor.athReceived.add(weiTokens); weiTotalAthSold = weiTotalAthSold.add(weiTokens); TokenPurchase(msg.sender, weiEther, weiTokens); token.transfer(msg.sender, weiTokens); mainWallet.transfer(weiEther); } else { /* if not authorized yet and over authorization limit, received ETH is saved on this contract instead and ATH is minted to this contract */ investor.etherInvestedPending = investor.etherInvestedPending.add(weiEther); investor.athReceivedPending = investor.athReceivedPending.add(weiTokens); TokenPurchasePending(msg.sender, weiEther, weiTokens); // pending ATH is reserved an this contract weiTotalAthSold = weiTotalAthSold.add(weiTokens); // pending ETH stays on this contract } } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonTrivialPurchase = msg.value > 100 finney; return withinPeriod && nonTrivialPurchase; } function authorizeOne(address investor_addr) canAdmin whenNotPaused public { Investor storage investor = investors[investor_addr]; require(!investor.authorized); uint256 athToSend = investor.athReceivedPending; uint256 ethToForward = investor.etherInvestedPending; investor.etherInvested = investor.etherInvested.add(ethToForward); investor.athReceived = investor.athReceived.add(athToSend); investor.authorized = true; investor.etherInvestedPending = 0; investor.athReceivedPending = 0; if (!investor.exists) { investor_list.push(investor_addr); investor.exists = true; } Authorized(investor_addr); if (ethToForward > 0) { TokenPurchase(investor_addr, ethToForward, athToSend); mainWallet.transfer(ethToForward); token.transfer(investor_addr, athToSend); } } function authorize(address[] investor_addrs) canAdmin whenNotPaused public { require(investor_addrs.length <= 100); Investor storage investor; for (uint i = 0; i < investor_addrs.length; i++) { investor = investors[investor_addrs[i]]; if (!investor.exists) { investor_list.push(investor_addrs[i]); investor.exists = true; } if (!investor.authorized) { uint256 athToSend = investor.athReceivedPending; uint256 ethToForward = investor.etherInvestedPending; investor.etherInvested = investor.etherInvested.add(ethToForward); investor.athReceived = investor.athReceived.add(athToSend); investor.authorized = true; investor.etherInvestedPending = 0; investor.athReceivedPending = 0; Authorized(investor_addrs[i]); if (ethToForward > 0) { TokenPurchase(investor_addrs[i], ethToForward, athToSend); mainWallet.transfer(ethToForward); token.transfer(investor_addrs[i], athToSend); } } } } function refund(address investor_addr) canAdmin public { Investor storage investor = investors[investor_addr]; require(!investor.authorized); // when returning, fee is taken for the additional effort/trouble uint256 ethToForward = 100 finney; uint256 ethToReturn = investor.etherInvestedPending.sub(ethToForward); require(ethToReturn > 0); uint256 athToRefund = investor.athReceivedPending; investor.etherInvestedPending = 0; investor.athReceivedPending = 0; Refunded(investor_addr, ethToReturn, athToRefund); // burn tokens reserved for this investment weiTotalAthSold = weiTotalAthSold.sub(athToRefund); // forward fee mainWallet.transfer(ethToForward); // return investment investor_addr.transfer(ethToReturn); } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { return now > endTime; } function giveTokensOne(address beneficiary, uint256 weiTokens) canAdmin public { require(beneficiary != 0x0); require(weiTokens >= 5 * weiOneToken); require(weiTotalBountiesGiven.add(weiTokens) <= weiTotalBountiesGivenCap); weiTotalBountiesGiven = weiTotalBountiesGiven.add(weiTokens); TokenBounty(beneficiary, weiTokens); token.transfer(beneficiary, weiTokens); } function giveTokens(address[] beneficiaries, uint256 weiTokens) canAdmin public { require(beneficiaries.length <= 100); require(weiTokens >= 5 * weiOneToken); require(weiTotalBountiesGiven.add(weiTokens.mul(beneficiaries.length)) <= weiTotalBountiesGivenCap); weiTotalBountiesGiven = weiTotalBountiesGiven.add(weiTokens.mul(beneficiaries.length)); for (uint i = 0; i < beneficiaries.length; i++) { TokenBounty(beneficiaries[i], weiTokens); token.transfer(beneficiaries[i], weiTokens); } } function calculateAndRegisterBonuses(uint256 weiEther) internal returns (uint256) { uint256 time = calculateTimeBonuses(weiEther); uint256 quantity = calculateQuantityBonuses(weiEther); uint256 early = calculateAndRegisterEarlyBonuses(weiEther); return time.add(quantity).add(early); } function calculateTimeBonuses(uint256 weiEther) internal constant returns (uint256) { if (startTime <= now && now < endOfRounds[0]) { return weiEther.mul(320); // 40% of rate } if (endOfRounds[0] <= now && now < endOfRounds[1]) { return weiEther.mul(200); // 25% of rate } if (endOfRounds[1] <= now && now < endOfRounds[2]) { return weiEther.mul(120); // 415 of rate } if (endOfRounds[2] <= now && now < endOfRounds[3]) { return weiEther.mul(80); // 10% of rate } if (endOfRounds[3] <= now && now < endOfRounds[4]) { return weiEther.mul(48); // 6% of rate } if (endOfRounds[4] <= now && now < endOfRounds[5]) { return weiEther.mul(24); // 3% of rate } return 0; } function calculateQuantityBonuses(uint256 weiEther) internal constant returns (uint256) { if (weiEther >= 500 ether) { return weiEther.mul(240); // 30% of rate } if (weiEther >= 125 ether) { return weiEther.mul(120); // 15% of rate } if (weiEther >= 50 ether) { return weiEther.mul(40); // 5% of rate } return 0; } function calculateAndRegisterEarlyBonuses(uint256 weiEther) internal returns (uint256) { if (weiEther >= 1000 ether && earlySlots[7] > 0) { earlySlots[7] = earlySlots[7].sub(1); return 500000 * weiOneToken; } if (weiEther >= 750 ether && earlySlots[6] > 0) { earlySlots[6] = earlySlots[6].sub(1); return 240000 * weiOneToken; } if (weiEther >= 500 ether && earlySlots[5] > 0) { earlySlots[5] = earlySlots[5].sub(1); return 110000 * weiOneToken; } if (weiEther >= 250 ether && earlySlots[4] > 0) { earlySlots[4] = earlySlots[4].sub(1); return 50000 * weiOneToken; } if (weiEther >= 100 ether && earlySlots[3] > 0) { earlySlots[3] = earlySlots[3].sub(1); return 18000 * weiOneToken; } if (weiEther >= 50 ether && earlySlots[2] > 0) { earlySlots[2] = earlySlots[2].sub(1); return 7000 * weiOneToken; } if (weiEther >= 20 ether && earlySlots[1] > 0) { earlySlots[1] = earlySlots[1].sub(1); return 2800 * weiOneToken; } if (weiEther >= 10 ether && earlySlots[0] > 0) { earlySlots[0] = earlySlots[0].sub(1); return 1200 * weiOneToken; } return 0; } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() public { require((msg.sender == owner) || (maxFinalizationTime <= now)); require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } function finalization() internal { // unsold tokens are burned token.burn(weiTotalAthSoldCap.sub(weiTotalAthSold)); // tokens are released for public trading token.finalize(); } function withdraw() public { require(isFinalized); if (now < maxFinalizationTime) { require(msg.sender == owner); } else { require( (msg.sender == adminAccounts[0]) ||(msg.sender == adminAccounts[1]) ||(msg.sender == adminAccounts[2]) ||(msg.sender == owner)); } msg.sender.transfer(this.balance); } function destroy() onlyOwner public { require(isFinalized); token.transfer(owner, token.balanceOf(this)); token.transferOwnership(owner); selfdestruct(owner); } }
low level token purchase function calculate token amount to be created and reduce slots for limited bonuses here we are abusing, that Athena is also 18 decimals decide what to do depending on whether this investor is already authorized pending ATH is reserved an this contract pending ETH stays on this contract
function buyTokens() public whenNotPaused payable { require(msg.sender != 0x0); require(validPurchase()); uint256 weiEther = msg.value; uint256 weiTokens = weiEther.mul(rate).add(calculateAndRegisterBonuses(weiEther)); require(weiTotalAthSold.add(weiTokens) <= weiTotalAthSoldCap); Investor storage investor = investors[msg.sender]; if (!investor.exists) { investor_list.push(msg.sender); investor.exists = true; } if ( investor.authorized || investor.etherInvested.add(weiEther) <= 2100 finney) { investor.etherInvested = investor.etherInvested.add(weiEther); investor.athReceived = investor.athReceived.add(weiTokens); weiTotalAthSold = weiTotalAthSold.add(weiTokens); TokenPurchase(msg.sender, weiEther, weiTokens); token.transfer(msg.sender, weiTokens); mainWallet.transfer(weiEther); saved on this contract instead and ATH is minted to this contract */ investor.etherInvestedPending = investor.etherInvestedPending.add(weiEther); investor.athReceivedPending = investor.athReceivedPending.add(weiTokens); TokenPurchasePending(msg.sender, weiEther, weiTokens); weiTotalAthSold = weiTotalAthSold.add(weiTokens); } }
15,846,387
[ 1, 821, 1801, 1147, 23701, 445, 4604, 1147, 3844, 358, 506, 2522, 471, 5459, 12169, 364, 13594, 324, 265, 6117, 2674, 732, 854, 1223, 9940, 16, 716, 432, 15991, 69, 353, 2546, 6549, 15105, 16288, 4121, 358, 741, 8353, 603, 2856, 333, 2198, 395, 280, 353, 1818, 10799, 4634, 432, 2455, 353, 8735, 392, 333, 6835, 4634, 512, 2455, 384, 8271, 603, 333, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 30143, 5157, 1435, 1071, 1347, 1248, 28590, 8843, 429, 288, 203, 565, 2583, 12, 3576, 18, 15330, 480, 374, 92, 20, 1769, 203, 565, 2583, 12, 877, 23164, 10663, 203, 203, 565, 2254, 5034, 732, 77, 41, 1136, 273, 1234, 18, 1132, 31, 203, 203, 565, 2254, 5034, 732, 77, 5157, 273, 732, 77, 41, 1136, 18, 16411, 12, 5141, 2934, 1289, 12, 11162, 1876, 3996, 38, 265, 6117, 12, 1814, 77, 41, 1136, 10019, 203, 203, 565, 2583, 12, 1814, 77, 5269, 37, 451, 55, 1673, 18, 1289, 12, 1814, 77, 5157, 13, 1648, 732, 77, 5269, 37, 451, 55, 1673, 4664, 1769, 203, 203, 565, 5454, 395, 280, 2502, 2198, 395, 280, 273, 2198, 395, 1383, 63, 3576, 18, 15330, 15533, 203, 565, 309, 16051, 5768, 395, 280, 18, 1808, 13, 288, 203, 1377, 2198, 395, 280, 67, 1098, 18, 6206, 12, 3576, 18, 15330, 1769, 203, 1377, 2198, 395, 280, 18, 1808, 273, 638, 31, 203, 565, 289, 203, 565, 309, 261, 282, 2198, 395, 280, 18, 8434, 203, 3639, 747, 2198, 395, 280, 18, 2437, 3605, 3149, 18, 1289, 12, 1814, 77, 41, 1136, 13, 1648, 576, 6625, 574, 82, 402, 13, 288, 203, 1377, 2198, 395, 280, 18, 2437, 3605, 3149, 273, 2198, 395, 280, 18, 2437, 3605, 3149, 18, 1289, 12, 1814, 77, 41, 1136, 1769, 203, 1377, 2198, 395, 280, 18, 421, 8872, 273, 2198, 395, 280, 18, 421, 8872, 18, 1289, 12, 1814, 77, 5157, 1769, 203, 1377, 732, 77, 5269, 37, 451, 55, 2 ]
//! Copyright 2017 Peter Czaban, Parity Technologies Ltd. //! //! Licensed under the Apache License, Version 2.0 (the "License"); //! you may not use this file except in compliance with the License. //! You may obtain a copy of the License at //! //! http://www.apache.org/licenses/LICENSE-2.0 //! //! Unless required by applicable law or agreed to in writing, software //! distributed under the License is distributed on an "AS IS" BASIS, //! WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //! See the License for the specific language governing permissions and //! limitations under the License. pragma solidity ^0.4.15; import "./interfaces/RelaySet.sol"; import "./libraries/AddressVotes.sol"; // Existing validators can give support to addresses. // Support can not be added once MAX_VALIDATORS are present. // Once given, support can be removed. // Addresses supported by more than half of the existing validators are the validators. // Malicious behaviour causes support removal. // Benign misbehaviour causes supprt removal if its called again after MAX_INACTIVITY. // Benign misbehaviour can be absolved before being called the second time. contract InnerMajoritySet is InnerSet { // EVENTS event Report(address indexed reporter, address indexed reported, bool indexed malicious); event Support(address indexed supporter, address indexed supported, bool indexed added); event InitiateChange(bytes32 indexed _parent_hash, address[] _new_set); event ChangeFinalized(address[] current_set); struct ValidatorStatus { // Is this a validator. bool isValidator; // Index in the validatorList. uint index; // Validator addresses which supported the address. AddressVotes.Data support; // Keeps track of the votes given out while the address is a validator. address[] supported; // Initial benign misbehaviour time tracker. mapping(address => uint) firstBenign; // Repeated benign misbehaviour counter. AddressVotes.Data benignMisbehaviour; } // Support can not be added once this number of validators is reached. uint public constant MAX_VALIDATORS = 30; // Time after which the validators will report a validator as malicious. uint public constant MAX_INACTIVITY = 6 hours; // Ignore misbehaviour older than this number of blocks. uint public constant RECENT_BLOCKS = 20; // STATE // Current list of addresses entitled to participate in the consensus. address[] public validatorsList; // Pending list of validator addresses. address[] pendingList = [0xf5777f8133aae2734396ab1d43ca54ad11bfb737]; // Tracker of status for each address. mapping(address => ValidatorStatus) validatorsStatus; // Used to lower the constructor cost. AddressVotes.Data initialSupport; // Each validator is initially supported by all others. function InnerMajoritySet() public { initialSupport.count = pendingList.length; for (uint i = 0; i < pendingList.length; i++) { address supporter = pendingList[i]; initialSupport.inserted[supporter] = true; } for (uint j = 0; j < pendingList.length; j++) { address validator = pendingList[j]; validatorsStatus[validator] = ValidatorStatus({ isValidator: true, index: j, support: initialSupport, supported: pendingList, benignMisbehaviour: AddressVotes.Data({ count: 0 }) }); } validatorsList = pendingList; } // Called on every block to update node validator list. function getValidators() public constant returns (address[]) { return validatorsList; } // Log desire to change the current list. function initiateChange() private { outerSet.initiateChange(block.blockhash(block.number - 1), pendingList); InitiateChange(block.blockhash(block.number - 1), pendingList); } function finalizeChange() public only_outer { validatorsList = pendingList; ChangeFinalized(validatorsList); } // SUPPORT LOOKUP AND MANIPULATION // Find the total support for a given address. function getSupport(address validator) public constant returns (uint) { return AddressVotes.count(validatorsStatus[validator].support); } function getSupported(address validator) public constant returns (address[]) { return validatorsStatus[validator].supported; } // Vote to include a validator. function addSupport(address validator) public only_validator not_voted(validator) free_validator_slots { newStatus(validator); AddressVotes.insert(validatorsStatus[validator].support, msg.sender); validatorsStatus[msg.sender].supported.push(validator); addValidator(validator); Support(msg.sender, validator, true); } // Remove support for a validator. function removeSupport(address sender, address validator) private { require(AddressVotes.remove(validatorsStatus[validator].support, sender)); Support(sender, validator, false); // Remove validator from the list if there is not enough support. removeValidator(validator); } // MALICIOUS BEHAVIOUR HANDLING // Called when a validator should be removed. function reportMalicious(address validator, uint blockNumber, bytes proof) public only_validator is_recent(blockNumber) { removeSupport(msg.sender, validator); Report(msg.sender, validator, true); } // BENIGN MISBEHAVIOUR HANDLING // Report that a validator has misbehaved in a benign way. function reportBenign(address validator, uint blockNumber) public only_validator is_validator(validator) is_recent(blockNumber) { firstBenign(validator); repeatedBenign(validator); Report(msg.sender, validator, false); } // Find the total number of repeated misbehaviour votes. function getRepeatedBenign(address validator) public constant returns (uint) { return AddressVotes.count(validatorsStatus[validator].benignMisbehaviour); } // Track the first benign misbehaviour. function firstBenign(address validator) private has_not_benign_misbehaved(validator) { validatorsStatus[validator].firstBenign[msg.sender] = now; } // Report that a validator has been repeatedly misbehaving. function repeatedBenign(address validator) private has_repeatedly_benign_misbehaved(validator) { AddressVotes.insert(validatorsStatus[validator].benignMisbehaviour, msg.sender); confirmedRepeatedBenign(validator); } // When enough long term benign misbehaviour votes have been seen, remove support. function confirmedRepeatedBenign(address validator) private agreed_on_repeated_benign(validator) { validatorsStatus[validator].firstBenign[msg.sender] = 0; AddressVotes.remove(validatorsStatus[validator].benignMisbehaviour, msg.sender); removeSupport(msg.sender, validator); } // Absolve a validator from a benign misbehaviour. function absolveFirstBenign(address validator) public has_benign_misbehaved(validator) { validatorsStatus[validator].firstBenign[msg.sender] = 0; AddressVotes.remove(validatorsStatus[validator].benignMisbehaviour, msg.sender); } // PRIVATE UTILITY FUNCTIONS // Add a status tracker for unknown validator. function newStatus(address validator) private has_no_votes(validator) { validatorsStatus[validator] = ValidatorStatus({ isValidator: false, index: pendingList.length, support: AddressVotes.Data({ count: 0 }), supported: new address[](0), benignMisbehaviour: AddressVotes.Data({ count: 0 }) }); } // ENACTMENT FUNCTIONS (called when support gets out of line with the validator list) // Add the validator if supported by majority. // Since the number of validators increases it is possible to some fall below the threshold. function addValidator(address validator) public is_not_validator(validator) has_high_support(validator) { validatorsStatus[validator].index = pendingList.length; pendingList.push(validator); validatorsStatus[validator].isValidator = true; // New validator should support itself. AddressVotes.insert(validatorsStatus[validator].support, validator); validatorsStatus[validator].supported.push(validator); initiateChange(); } // Remove a validator without enough support. // Can be called to clean low support validators after making the list longer. function removeValidator(address validator) public is_validator(validator) has_low_support(validator) { uint removedIndex = validatorsStatus[validator].index; // Can not remove the last validator. uint lastIndex = pendingList.length-1; address lastValidator = pendingList[lastIndex]; // Override the removed validator with the last one. pendingList[removedIndex] = lastValidator; // Update the index of the last validator. validatorsStatus[lastValidator].index = removedIndex; delete pendingList[lastIndex]; pendingList.length--; // Reset validator status. validatorsStatus[validator].index = 0; validatorsStatus[validator].isValidator = false; // Remove all support given by the removed validator. address[] storage toRemove = validatorsStatus[validator].supported; for (uint i = 0; i < toRemove.length; i++) { removeSupport(validator, toRemove[i]); } delete validatorsStatus[validator].supported; initiateChange(); } // MODIFIERS function highSupport(address validator) public constant returns (bool) { return getSupport(validator) > pendingList.length/2; } function firstBenignReported(address reporter, address validator) public constant returns (uint) { return validatorsStatus[validator].firstBenign[reporter]; } modifier has_high_support(address validator) { if (highSupport(validator)) { _; } } modifier has_low_support(address validator) { if (!highSupport(validator)) { _; } } modifier has_not_benign_misbehaved(address validator) { if (firstBenignReported(msg.sender, validator) == 0) { _; } } modifier has_benign_misbehaved(address validator) { if (firstBenignReported(msg.sender, validator) > 0) { _; } } modifier has_repeatedly_benign_misbehaved(address validator) { if (firstBenignReported(msg.sender, validator) - now > MAX_INACTIVITY) { _; } } modifier agreed_on_repeated_benign(address validator) { if (getRepeatedBenign(validator) > pendingList.length/2) { _; } } modifier free_validator_slots() { require(pendingList.length < MAX_VALIDATORS); _; } modifier only_validator() { require(validatorsStatus[msg.sender].isValidator); _; } modifier is_validator(address someone) { if (validatorsStatus[someone].isValidator) { _; } } modifier is_not_validator(address someone) { if (!validatorsStatus[someone].isValidator) { _; } } modifier not_voted(address validator) { require(!AddressVotes.contains(validatorsStatus[validator].support, msg.sender)); _; } modifier has_no_votes(address validator) { if (AddressVotes.count(validatorsStatus[validator].support) == 0) { _; } } modifier is_recent(uint blockNumber) { require(block.number <= blockNumber + RECENT_BLOCKS); _; } }
Time after which the validators will report a validator as malicious.
uint public constant MAX_INACTIVITY = 6 hours;
1,041,056
[ 1, 950, 1839, 1492, 326, 11632, 903, 2605, 279, 4213, 487, 27431, 28728, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 11890, 1071, 5381, 4552, 67, 706, 22271, 4107, 273, 1666, 7507, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed originAddress, address indexed destinationAddress, uint256 indexed nftIndex); event Approval(address indexed owner, address indexed approved, uint256 indexed nftIndex); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /// NEW EVENTS - ADDED BY KASPER event txMint(address indexed from, address indexed to, uint256 indexed nftIndex); event txPrimary(address indexed originAddress, address indexed destinationAddress, uint256 indexed nftIndex); event txSecondary(address indexed originAddress, address indexed destinationAddress, uint256 indexed nftIndex); event txCollect(address indexed originAddress, address indexed destinationAddress, uint256 indexed nftIndex); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `nftIndex`. */ function ownerOf(uint256 nftIndex) public view returns (address owner); /** * @dev Transfers a specific NFT (`nftIndex`) from one account (`originAddress `) to * another (`to`). * Requirements: * - `originAddress `, `to` cannot be zero. * - `nftIndex` must be owned by `originAddress `. * - If the caller is not `originAddress `, it must be have been allowed to move this * NFT by either {approve} or {setApprovalForAll}. */ function safeTransferFrom(address originAddress, address destinationAddress, uint256 nftIndex) public; /** * @dev Transfers a specific NFT (`nftIndex`) from one account (`originAddress `) to * another (`to`). * Requirements: * - If the caller is not `originAddress `, it must be approved to move this NFT by * either {approve} or {setApprovalForAll}. */ function transferFrom(address originAddress, address destinationAddress, uint256 nftIndex) public; function approve(address destinationAddress, uint256 nftIndex) public; function getApproved(uint256 nftIndex) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address originAddress, address destinationAddress, uint256 nftIndex, bytes memory data) public; } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {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 originAddress The address which previously owned the token * @param nftIndex 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 originAddress, uint256 nftIndex, bytes memory data) public returns (bytes4); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * 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. */ 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. // 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 != 0x0 && codehash != accountHash); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @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]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @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); } } /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 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; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param nftIndex 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 nftIndex) public view returns (address) { address owner = _tokenOwner[nftIndex]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param destinationAddress address to be approved for the given token ID * @param nftIndex uint256 ID of the token to be approved */ function approve(address destinationAddress, uint256 nftIndex) public { address owner = ownerOf(nftIndex); require(destinationAddress != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[nftIndex] = destinationAddress; emit Approval(owner, destinationAddress, nftIndex); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param nftIndex uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 nftIndex) public view returns (address) { require(_exists(nftIndex), "ERC721: approved query for nonexistent token"); return _tokenApprovals[nftIndex]; } /** * @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 destinationAddress operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address destinationAddress, bool approved) public { require(destinationAddress != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][destinationAddress] = approved; emit ApprovalForAll(_msgSender(), destinationAddress, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param originAddress current owner of the token * @param destinationAddress address to receive the ownership of the given token ID * @param nftIndex uint256 ID of the token to be transferred */ function transferFrom(address originAddress, address destinationAddress, uint256 nftIndex) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), nftIndex), "ERC721: transfer caller is not owner nor approved"); _transferFrom(originAddress, destinationAddress, nftIndex); } /** * @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 originAddress current owner of the token * @param destinationAddress address to receive the ownership of the given token ID * @param nftIndex uint256 ID of the token to be transferred */ function safeTransferFrom(address originAddress, address destinationAddress, uint256 nftIndex) public { safeTransferFrom(originAddress, destinationAddress, nftIndex, ""); } /** * @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 originAddress current owner of the token * @param destinationAddress address to receive the ownership of the given token ID * @param nftIndex uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address originAddress, address destinationAddress, uint256 nftIndex, bytes memory _data) public { require(_isApprovedOrOwner(_msgSender(), nftIndex), "ERC721: transfer caller is not owner nor approved"); _safeTransferFrom(originAddress, destinationAddress, nftIndex, _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 originAddress current owner of the token * @param destinationAddress address to receive the ownership of the given token ID * @param nftIndex uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function _safeTransferFrom(address originAddress, address destinationAddress, uint256 nftIndex, bytes memory _data) internal { _transferFrom(originAddress, destinationAddress, nftIndex); require(_checkOnERC721Received(originAddress, destinationAddress, nftIndex, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param nftIndex uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 nftIndex) internal view returns (bool) { address owner = _tokenOwner[nftIndex]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param nftIndex 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 nftIndex) internal view returns (bool) { require(_exists(nftIndex), "ERC721: operator query for nonexistent token"); address owner = ownerOf(nftIndex); return (spender == owner || getApproved(nftIndex) == 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 destinationAddress The address that will own the minted token * @param nftIndex uint256 ID of the token to be minted */ function _safeMint(address destinationAddress, uint256 nftIndex) internal { _safeMint(destinationAddress, nftIndex, ""); } /** * @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 destinationAddress The address that will own the minted token * @param nftIndex uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ function _safeMint(address destinationAddress, uint256 nftIndex, bytes memory _data) internal { _mint(destinationAddress, nftIndex); require(_checkOnERC721Received(address(0), destinationAddress, nftIndex, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param destinationAddress The address that will own the minted token * @param nftIndex uint256 ID of the token to be minted */ function _mint(address destinationAddress, uint256 nftIndex) internal { require(destinationAddress != address(0), "ERC721: mint to the zero address"); require(!_exists(nftIndex), "ERC721: token already minted"); _tokenOwner[nftIndex] = destinationAddress; _ownedTokensCount[destinationAddress].increment(); emit Transfer(address(0), destinationAddress, nftIndex); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {_burn} instead. * @param owner owner of the token to burn * @param nftIndex uint256 ID of the token being burned */ function _burn(address owner, uint256 nftIndex) internal { require(ownerOf(nftIndex) == owner, "ERC721: burn of token that is not own"); _clearApproval(nftIndex); _ownedTokensCount[owner].decrement(); _tokenOwner[nftIndex] = address(0); emit Transfer(owner, address(0), nftIndex); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param nftIndex uint256 ID of the token being burned */ function _burn(uint256 nftIndex) internal { _burn(ownerOf(nftIndex), nftIndex); } /** * @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 originAddress current owner of the token * @param destinationAddress address to receive the ownership of the given token ID * @param nftIndex uint256 ID of the token to be transferred */ function _transferFrom(address originAddress, address destinationAddress, uint256 nftIndex) internal { require(ownerOf(nftIndex) == originAddress, "ERC721: transfer of token that is not own"); require(destinationAddress != address(0), "ERC721: transfer to the zero address"); _clearApproval(nftIndex); _ownedTokensCount[originAddress].decrement(); _ownedTokensCount[destinationAddress].increment(); _tokenOwner[nftIndex] = destinationAddress; emit Transfer(originAddress, destinationAddress, nftIndex); } /** * @dev Only used/called by GET Protocol relayer - ADDED / NEW * @notice The function assumes that the originAddress has signed the tx. * @param originAddress the address the NFT will be extracted from * @param destinationAddress the address of the ticketeer that will receive the NFT * @param nftIndex the index of the NFT that will be returned to the tickeer */ function _relayerTransferFrom(address originAddress, address destinationAddress, uint256 nftIndex) internal { _clearApproval(nftIndex); _ownedTokensCount[originAddress].decrement(); _ownedTokensCount[destinationAddress].increment(); _tokenOwner[nftIndex] = destinationAddress; } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * This function is deprecated. * @param originAddress address representing the previous owner of the given token ID * @param destinationAddress target address that will receive the tokens * @param nftIndex 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 originAddress, address destinationAddress, uint256 nftIndex, bytes memory _data) internal returns (bool) { if (!destinationAddress.isContract()) { return true; } bytes4 retval = IERC721Receiver(destinationAddress).onERC721Received(_msgSender(), originAddress, nftIndex, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID. * @param nftIndex uint256 ID of the token to be transferred */ function _clearApproval(uint256 nftIndex) private { if (_tokenApprovals[nftIndex] != address(0)) { _tokenApprovals[nftIndex] = address(0); } } } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Enumerable is IERC721 { function totalSupply() public view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 nftIndex); function tokenByIndex(uint256 index) public view returns (uint256); } /** * @title ERC-721 Non-Fungible Token with optional enumeration extension logic * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => 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; /* * 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 Constructor function. */ constructor () public { // register the supported interface to conform to ERC721Enumerable via ERC165 _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev Gets the token ID at a given index of the tokens list of the requested owner. * @param owner address owning the tokens list to be accessed * @param index uint256 representing the index to be accessed of the requested tokens list * @return uint256 token ID at the given index of the tokens list owned by the requested address */ function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); 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(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferoriginAddress, this imposes no restrictions on msg.sender. * @param originAddress current owner of the token * @param destinationAddress address to receive the ownership of the given token ID * @param nftIndex uint256 ID of the token to be transferred */ function _transferFrom(address originAddress, address destinationAddress, uint256 nftIndex) internal { super._transferFrom(originAddress, destinationAddress, nftIndex); _removeTokenFromOwnerEnumeration(originAddress, nftIndex); _addTokenToOwnerEnumeration(destinationAddress, nftIndex); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferoriginAddress, this imposes no restrictions on msg.sender. * @param originAddress current owner of the token * @param destinationAddress address to receive the ownership of the given token ID * @param nftIndex uint256 ID of the token to be transferred */ function _relayerTransferFrom(address originAddress, address destinationAddress, uint256 nftIndex) internal { super._relayerTransferFrom(originAddress, destinationAddress, nftIndex); _removeTokenFromOwnerEnumeration(originAddress, nftIndex); _addTokenToOwnerEnumeration(destinationAddress, nftIndex); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param destinationAddress address the beneficiary that will own the minted token * @param nftIndex uint256 ID of the token to be minted */ function _mint(address destinationAddress, uint256 nftIndex) internal { super._mint(destinationAddress, nftIndex); _addTokenToOwnerEnumeration(destinationAddress, nftIndex); _addTokenToAllTokensEnumeration(nftIndex); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use {ERC721-_burn} instead. * @param owner owner of the token to burn * @param nftIndex uint256 ID of the token being burned */ function _burn(address owner, uint256 nftIndex) internal { super._burn(owner, nftIndex); _removeTokenFromOwnerEnumeration(owner, nftIndex); // Since nftIndex will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund _ownedTokensIndex[nftIndex] = 0; _removeTokenFromAllTokensEnumeration(nftIndex); } /** * @dev Gets the list of token IDs of the requested owner. * @param owner address owning the tokens * @return uint256[] List of token IDs owned by the requested address */ function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param destinationAddress address representing the new owner of the given token ID * @param nftIndex uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address destinationAddress, uint256 nftIndex) private { _ownedTokensIndex[nftIndex] = _ownedTokens[destinationAddress].length; _ownedTokens[destinationAddress].push(nftIndex); } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param nftIndex uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 nftIndex) private { _allTokensIndex[nftIndex] = _allTokens.length; _allTokens.push(nftIndex); } /** * @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 originAddress address representing the previous owner of the given token ID * @param nftIndex uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address originAddress, uint256 nftIndex) 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 = _ownedTokens[originAddress ].length.sub(1); uint256 tokenIndex = _ownedTokensIndex[nftIndex]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastnftIndex = _ownedTokens[originAddress ][lastTokenIndex]; _ownedTokens[originAddress ][tokenIndex] = lastnftIndex; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastnftIndex] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array _ownedTokens[originAddress ].length--; // Note that _ownedTokensIndex[nftIndex] hasn't been cleared: it still points to the old slot (now occupied by // lastnftIndex, or just over the end of the array if the token was the last one). } /** * @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 nftIndex uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 nftIndex) 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.sub(1); uint256 tokenIndex = _allTokensIndex[nftIndex]; /** 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 lastnftIndex = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastnftIndex; // Move the last token to the slot of the to-delete token _allTokensIndex[lastnftIndex] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array _allTokens.length--; _allTokensIndex[nftIndex] = 0; } } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ contract IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function nftMetadata(uint256 nftIndex) external view returns (string memory); } contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata { // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping(uint256 => string) private _nftMetadatas; // // Optional mapping for tickeer_ids (underwriter) mapping (uint256 => address) private _ticketeerAddresss; // Base URI string private _baseURI; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('nftMetadata(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /** * @dev Constructor function */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721_METADATA); } /** * @dev Gets the token name. * @return string representing the token name */ function name() external view returns (string memory) { return _name; } /** * @dev Gets the token symbol. * @return string representing the token symbol */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns an URI for a given token ID. * Throws if the token ID does not exist. May return an empty string. * @param nftIndex uint256 ID of the token to query */ function nftMetadata(uint256 nftIndex) external view returns (string memory) { require(_exists(nftIndex), "ERC721Metadata: URI query for nonexistent token"); return _nftMetadatas[nftIndex]; } /// NEW function getTicketeerOwner(uint256 nftIndex) public view returns (address) { require(_exists(nftIndex), "ERC721Metadata: Tickeer owner query for nonexistent token"); return _ticketeerAddresss[nftIndex]; } /** * @dev Internal function to set the token URI for a given token. * Reverts if the token ID does not exist. * @param nftIndex uint256 ID of the token to set its URI * @param uri string URI to assign */ function _setnftMetadata (uint256 nftIndex, string memory uri) internal { require(_exists(nftIndex), "ERC721Metadata: URI set of nonexistent token"); _nftMetadatas[nftIndex] = uri; } /** NEW FUNCTION - ADDED BY KASPER * @dev Sets `_nftMetadata ` as the nftMetadata of `nftIndex`. */ function _addTicketeerIndex(uint256 nftIndex, address _ticketeerAddress) internal { require(_exists(nftIndex), "ERC721Metadata: URI set of nonexistent token"); _ticketeerAddresss[nftIndex] = _ticketeerAddress; } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param nftIndex uint256 ID of the token being burned by the msg.sender */ function _burn(address owner, uint256 nftIndex) internal { super._burn(owner, nftIndex); // Clear metadata (if any) if (bytes(_nftMetadatas[nftIndex]).length != 0) { delete _nftMetadatas[nftIndex]; } } } /** NEW ADDED * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title Full ERC721 Token * @dev This implementation includes all the required and some optional functionality of the ERC721 standard * Moreover, it includes approve all functionality using operator terminology. * * See https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata { constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) { // solhint-disable-previous-line no-empty-blocks } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } contract MinterRole is Context { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(_msgSender()); } modifier onlyMinter() { require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role"); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(_msgSender()); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } contract RelayerRole is Context { using Roles for Roles.Role; event RelayerAdded(address indexed account); event RelayerRemoved(address indexed account); Roles.Role private _relayers; constructor () internal { _addRelayer(_msgSender()); } modifier onlyRelayer() { require(isRelayer(_msgSender()), "RelayerRole: caller does not have the Relayer role"); _; } function isRelayer(address account) public view returns (bool) { return _relayers.has(account); } function addRelayer(address account) public onlyRelayer { _addRelayer(account); } function renounceRelayer() public { _removeRelayer(_msgSender()); } function _addRelayer(address account) internal { _relayers.add(account); emit RelayerAdded(account); } function _removeRelayer(address account) internal { _relayers.remove(account); emit RelayerRemoved(account); } } /** * @title ERC721Mintable * @dev ERC721 minting logic. */ contract ERC721Mintable is ERC721, MinterRole, RelayerRole { /** * @dev Function to mint tokens. * @param destinationAddress The address that will receive the minted token. * @param nftIndex The token id to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address destinationAddress, uint256 nftIndex) private onlyMinter returns (bool) { _mint(destinationAddress, nftIndex); return true; } /** * @dev Function to safely mint tokens. * @param destinationAddress The address that will receive the minted token. * @param nftIndex The token id to mint. * @return A boolean that indicates if the operation was successful. */ function safeMint(address destinationAddress, uint256 nftIndex) private onlyMinter returns (bool) { _safeMint(destinationAddress, nftIndex); return true; } /** * @dev Function to safely mint tokens. * @param destinationAddress The address that will receive the minted token. * @param nftIndex The token id to mint. * @param _data bytes data to send along with a safe transfer check. * @return A boolean that indicates if the operation was successful. */ function safeMint(address destinationAddress, uint256 nftIndex, bytes memory _data) private onlyMinter returns (bool) { _safeMint(destinationAddress, nftIndex, _data); return true; } } /** * @title ERC721MetadataMintable * @dev ERC721 minting logic with metadata. */ contract ERC721MetadataMintable is ERC721, ERC721Metadata, MinterRole { /** * @dev Function to mint tokens. * @param destinationAddress The address that will receive the minted tokens. * @param nftIndex The token id to mint. * @param nftMetadata The token URI of the minted token. * @return A boolean that indicates if the operation was successful. */ function mintWithNftMetadata(address destinationAddress, uint256 nftIndex, string memory nftMetadata) private onlyMinter returns (bool) { _mint(destinationAddress, nftIndex); _setnftMetadata(nftIndex, nftMetadata); return true; } } /** * @title ERC721 Burnable Token * @dev ERC721 Token that can be irreversibly burned (destroyed). */ contract ERC721Burnable is Context, ERC721 { /** * @dev Burns a specific ERC721 token. * TODO This needs to be made onlyOwner as destroying NFTs is a form of control. * @param nftIndex uint256 id of the ERC721 token to be burned. */ function burn(uint256 nftIndex) private { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), nftIndex), "ERC721Burnable: caller is not owner nor approved"); _burn(nftIndex); } } /** * @title GET_NFTV02 * TODO Add Description * checking token existence, removal of a token from an address */ contract SmartTicketingERC721 is ERC721Full, ERC721Mintable, ERC721MetadataMintable, ERC721Burnable, Ownable { constructor (string memory _nftName, string memory _nftSymbol) public ERC721Mintable() ERC721Full(_nftName, _nftSymbol) { // solhint-disable-previous-line no-empty-blocks } using Counters for Counters.Counter; Counters.Counter private _nftIndexs; /** @notice This function mints a new NFT * @dev the nftIndex (NFT_index is auto incremented) * @param destinationAddress addres of the underwriter of the NFT */ function mintNFTIncrement(address destinationAddress) public onlyMinter returns (uint256) { _nftIndexs.increment(); uint256 newNFTIndex = _nftIndexs.current(); _mint(destinationAddress, newNFTIndex); _addTicketeerIndex(newNFTIndex, destinationAddress); return newNFTIndex; } /** @notice This function mints a new NFT -> * @dev the nftIndex needs to be provided in the call * @dev ensure that the provided newNFTIndex is unique and stored/cached. * @param newNFTIndex uint of the nftIndex that will be minted * @param destinationAddress addres of the underwriter of the NFT */ function mintNFT(address destinationAddress, uint256 newNFTIndex) public onlyMinter returns (uint256) { _mint(destinationAddress, newNFTIndex); _addTicketeerIndex(newNFTIndex, destinationAddress); return newNFTIndex; } /** @param originAddress addres of the underwriter of the NFT * @param destinationAddress addres of the to-be owner of the NFT * @param ticket_execution_data string containing the metadata about the ticket the NFT is representing */ function primaryTransfer(address originAddress, address destinationAddress, uint256 nftIndex, string memory ticket_execution_data) public { /// Check if originAddress currently owners the NFT require(ownerOf(nftIndex) == originAddress, "ERC721: transfer of token that is not own"); require(destinationAddress != address(0), "ERC721: transfer to the zero address"); /// Store the ticket_execution metadata in the NFT _setnftMetadata(nftIndex, ticket_execution_data); /// Transfer the NFT to the new owner safeTransferFrom(originAddress, destinationAddress, nftIndex); emit txPrimary(originAddress, destinationAddress, nftIndex); } /** * @notice This function can only be called by a whitelisted relayer address (onlyRelayer). * @notice As tx is relayed msg.sender is assumed to be signed by originAddress. * @dev Tx will fail/throw if originAddress is not owner of nftIndex * @dev Tx will fail/throw if destinationAddress is genensis address. * @dev TODO Tx should fail if destinationAddress is smart contract * @param originAddress address the NFT is asserted * @param destinationAddress addres of the to-be owner of the NFT * @param nftIndex uint256 ID of the token to be transferred */ function secondaryTransfer(address originAddress, address destinationAddress, uint256 nftIndex) public { /// Verify if originAddress is owner of nftIndex require(ownerOf(nftIndex) == originAddress, "ERC721: transfer of token that is not owned by owner"); /// Verify if destinationAddress isn't burn-address require(destinationAddress != address(0), "ERC721: transfer to the zero address"); /// Transfer the NFT to the new owner safeTransferFrom(originAddress, destinationAddress, nftIndex); emit txSecondary(originAddress, destinationAddress, nftIndex); } /** Returns the NFT of the ticketeer back to its address + cleans the ticket_execution metadata from the NFT * @notice This function doesn't require autorization of the NFT owner! This is basically a "seizing' of the NFT * @param nftIndex \uint256 ID of the token to be transferred * @param destinationAddress addres of the to-be owner of the NFT (should be tcketeer) * @dev It is possible for us to pass the "originAddress" in the contract call, but this can just as * well be fetched in the smart contract. Works ether way. */ function collectTransfer(uint256 nftIndex, address destinationAddress) public { /// Check if originAddress is actually the ticketeer owning the NFT require(getTicketeerOwner(nftIndex) == destinationAddress, "ERC721: transfer of token that is not own"); /// Check if the originAddress is the ticketeer require(getTicketeerOwner(nftIndex) == msg.sender, "ERC721: collection can only be done by ticketeer"); /// Fetch the address that owns the NFT address originAddress = ownerOf(nftIndex); address _ticketeerAddress = getTicketeerOwner(nftIndex); require(_ticketeerAddress == destinationAddress, "ERC721: collection of token that is not owned by the ticketeer"); /// Clean out ticketExectionHash _setnftMetadata(nftIndex, "NONE"); /// Transfer the NFT to the new owner _relayerTransferFrom(originAddress, destinationAddress, nftIndex); emit txCollect(originAddress, destinationAddress, nftIndex); } function exists(uint256 nftIndex) public view returns (bool) { return _exists(nftIndex); } function tokensOfOwner(address owner) public view returns (uint256[] memory) { return _tokensOfOwner(owner); } function setnftMetadata(uint256 nftIndex, string memory uri) private { _setnftMetadata(nftIndex, uri); } } /** @title A scalable implementation of all ERC721 NFT standards combined. * @author Kasper Keunen * @dev Extends SmartTicketingERC721 */ contract GET_NFTVPOC is SmartTicketingERC721 { constructor(string memory _nftName, string memory _nftSymbol) public SmartTicketingERC721(_nftName, _nftSymbol) { } }
* @dev Required interface of an ERC721 compliant contract./
contract IERC721 is IERC165 { event Transfer(address indexed originAddress, address indexed destinationAddress, uint256 indexed nftIndex); event Approval(address indexed owner, address indexed approved, uint256 indexed nftIndex); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); event txMint(address indexed from, address indexed to, uint256 indexed nftIndex); event txPrimary(address indexed originAddress, address indexed destinationAddress, uint256 indexed nftIndex); event txSecondary(address indexed originAddress, address indexed destinationAddress, uint256 indexed nftIndex); event txCollect(address indexed originAddress, address indexed destinationAddress, uint256 indexed nftIndex); function balanceOf(address owner) public view returns (uint256 balance); function ownerOf(uint256 nftIndex) public view returns (address owner); function safeTransferFrom(address originAddress, address destinationAddress, uint256 nftIndex) public; function transferFrom(address originAddress, address destinationAddress, uint256 nftIndex) public; function approve(address destinationAddress, uint256 nftIndex) public; function getApproved(uint256 nftIndex) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address originAddress, address destinationAddress, uint256 nftIndex, bytes memory data) public; } }
6,416,811
[ 1, 3705, 1560, 434, 392, 4232, 39, 27, 5340, 24820, 6835, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 467, 654, 39, 27, 5340, 353, 467, 654, 39, 28275, 288, 203, 565, 871, 12279, 12, 2867, 8808, 4026, 1887, 16, 1758, 8808, 2929, 1887, 16, 2254, 5034, 8808, 290, 1222, 1016, 1769, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 20412, 16, 2254, 5034, 8808, 290, 1222, 1016, 1769, 203, 565, 871, 1716, 685, 1125, 1290, 1595, 12, 2867, 8808, 3410, 16, 1758, 8808, 3726, 16, 1426, 20412, 1769, 203, 203, 565, 871, 2229, 49, 474, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 8808, 290, 1222, 1016, 1769, 203, 565, 871, 2229, 6793, 12, 2867, 8808, 4026, 1887, 16, 1758, 8808, 2929, 1887, 16, 2254, 5034, 8808, 290, 1222, 1016, 1769, 203, 565, 871, 2229, 14893, 12, 2867, 8808, 4026, 1887, 16, 1758, 8808, 2929, 1887, 16, 2254, 5034, 8808, 290, 1222, 1016, 1769, 203, 565, 871, 2229, 10808, 12, 2867, 8808, 4026, 1887, 16, 1758, 8808, 2929, 1887, 16, 2254, 5034, 8808, 290, 1222, 1016, 1769, 203, 203, 565, 445, 11013, 951, 12, 2867, 3410, 13, 1071, 1476, 1135, 261, 11890, 5034, 11013, 1769, 203, 203, 565, 445, 3410, 951, 12, 11890, 5034, 290, 1222, 1016, 13, 1071, 1476, 1135, 261, 2867, 3410, 1769, 203, 203, 565, 445, 4183, 5912, 1265, 12, 2867, 4026, 1887, 16, 1758, 2929, 1887, 16, 2254, 5034, 290, 1222, 1016, 13, 1071, 31, 203, 565, 445, 7412, 1265, 12, 2867, 4026, 1887, 16, 1758, 2929, 1887, 16, 2254, 5034, 290, 1222, 1016, 13, 1071, 31, 203, 565, 2 ]
pragma solidity 0.4.21; contract Ownable { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Ownable() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } /** * @title 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) { if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public returns (bool) { paused = true; emit Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public returns (bool) { paused = false; emit Unpause(); return true; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes data) public; } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and an // initial fixed supply // ---------------------------------------------------------------------------- contract ROG is ERC20Interface, Pausable { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function ROG() public { symbol = "ROG"; name = "NeoWorld Rare Ore G"; decimals = 18; _totalSupply = 10000000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner&#39;s account to `to` account // - Owner&#39;s account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens) public whenNotPaused returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner&#39;s account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens) public whenNotPaused returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function increaseApproval (address _spender, uint _addedValue) public whenNotPaused returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } // ------------------------------------------------------------------------ // 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, uint tokens) public whenNotPaused returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender&#39;s account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner&#39;s account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes data) public whenNotPaused returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } // ------------------------------------------------------------------------ // Don&#39;t accept ETH // ------------------------------------------------------------------------ function () public payable { revert(); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and an initial fixed supply ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------
contract ROG is ERC20Interface, Pausable { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint public _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; function ROG() public { symbol = "ROG"; name = "NeoWorld Rare Ore G"; decimals = 18; _totalSupply = 10000000 * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } function totalSupply() public constant returns (uint) { return _totalSupply - balances[address(0)]; } function balanceOf(address tokenOwner) public constant returns (uint balance) { return balances[tokenOwner]; } function transfer(address to, uint tokens) public whenNotPaused returns (bool success) { balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } function approve(address spender, uint tokens) public whenNotPaused returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } function increaseApproval (address _spender, uint _addedValue) public whenNotPaused returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } else { function transferFrom(address from, address to, uint tokens) public whenNotPaused returns (bool success) { balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } function allowance(address tokenOwner, address spender) public constant returns (uint remaining) { return allowed[tokenOwner][spender]; } function approveAndCall(address spender, uint tokens, bytes data) public whenNotPaused returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data); return true; } function () public payable { revert(); } function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
15,353,952
[ 1, 5802, 7620, 4232, 39, 3462, 3155, 16, 598, 326, 2719, 434, 3273, 16, 508, 471, 15105, 471, 392, 2172, 5499, 14467, 8879, 13849, 8879, 17082, 11417, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 6525, 43, 353, 4232, 39, 3462, 1358, 16, 21800, 16665, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 565, 533, 1071, 3273, 31, 203, 565, 533, 1071, 225, 508, 31, 203, 565, 2254, 28, 1071, 15105, 31, 203, 565, 2254, 1071, 389, 4963, 3088, 1283, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 13, 324, 26488, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 3719, 2935, 31, 203, 203, 203, 565, 445, 6525, 43, 1435, 1071, 288, 203, 3639, 3273, 273, 315, 1457, 43, 14432, 203, 3639, 508, 273, 315, 50, 4361, 18071, 534, 834, 531, 266, 611, 14432, 203, 3639, 15105, 273, 6549, 31, 203, 3639, 389, 4963, 3088, 1283, 273, 2130, 11706, 380, 1728, 636, 11890, 12, 31734, 1769, 203, 3639, 324, 26488, 63, 8443, 65, 273, 389, 4963, 3088, 1283, 31, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 3410, 16, 389, 4963, 3088, 1283, 1769, 203, 565, 289, 203, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 5381, 1135, 261, 11890, 13, 288, 203, 3639, 327, 389, 4963, 3088, 1283, 225, 300, 324, 26488, 63, 2867, 12, 20, 13, 15533, 203, 565, 289, 203, 203, 565, 445, 11013, 951, 12, 2867, 1147, 5541, 13, 1071, 5381, 1135, 261, 11890, 11013, 13, 288, 203, 3639, 327, 324, 26488, 63, 2316, 5541, 15533, 203, 565, 289, 203, 203, 203, 565, 445, 7412, 12, 2867, 358, 16, 2254, 2430, 13, 1071, 1347, 1248, 28590, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 324, 2 ]
/** * @title TEND token * @version 2.0 * @author Validity Labs AG <[email protected]> * * The TTA tokens are issued as participation certificates and represent * uncertificated securities within the meaning of article 973c Swiss CO. The * issuance of the TTA tokens has been governed by a prospectus issued by * Tend Technologies AG. * * TTA tokens are only recognized and transferable in undivided units. * * The holder of a TTA token must prove his possessorship to be recognized by * the issuer as being entitled to the rights arising out of the respective * participation certificate; he/she waives any rights if he/she is not in a * position to prove him/her being the holder of the respective token. * * Similarly, only the person who proves him/her being the holder of the TTA * Token is entitled to transfer title and ownership on the token to another * person. Both the transferor and the transferee agree and accept hereby * explicitly that the tokens are transferred digitally, i.e. in a form-free * manner. However, if any regulators, courts or similar would require written * confirmation of a transfer of the transferable uncertificated securities * from one investor to another investor, such investors will provide written * evidence of such transfer. */ pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @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 ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @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]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) hasMintPermission canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer( address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve( address _spender, uint256 _value ) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval( address _spender, uint _addedValue ) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval( address _spender, uint _subtractedValue ) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract DividendToken is StandardToken, Ownable { using SafeMath for uint256; // time before dividendEndTime during which dividend cannot be claimed by token holders // instead the unclaimed dividend can be claimed by treasury in that time span uint256 public claimTimeout = 20 days; uint256 public dividendCycleTime = 350 days; uint256 public currentDividend; mapping(address => uint256) unclaimedDividend; // tracks when the dividend balance has been updated last time mapping(address => uint256) public lastUpdate; uint256 public lastDividendIncreaseDate; // allow payment of dividend only by special treasury account (treasury can be set and altered by owner, // multiple treasurer accounts are possible mapping(address => bool) public isTreasurer; uint256 public dividendEndTime = 0; event Payin(address _owner, uint256 _value, uint256 _endTime); event Payout(address _tokenHolder, uint256 _value); event Reclaimed(uint256 remainingBalance, uint256 _endTime, uint256 _now); event ChangedTreasurer(address treasurer, bool active); /** * @dev Deploy the DividendToken contract and set the owner of the contract */ constructor() public { isTreasurer[owner] = true; } /** * @dev Request payout dividend (claim) (requested by tokenHolder -> pull) * dividends that have not been claimed within 330 days expire and cannot be claimed anymore by the token holder. */ function claimDividend() public returns (bool) { // unclaimed dividend fractions should expire after 330 days and the owner can reclaim that fraction require(dividendEndTime > 0); require(dividendEndTime.sub(claimTimeout) > block.timestamp); updateDividend(msg.sender); uint256 payment = unclaimedDividend[msg.sender]; unclaimedDividend[msg.sender] = 0; msg.sender.transfer(payment); // Trigger payout event emit Payout(msg.sender, payment); return true; } /** * @dev Transfer dividend (fraction) to new token holder * @param _from address The address of the old token holder * @param _to address The address of the new token holder * @param _value uint256 Number of tokens to transfer */ function transferDividend(address _from, address _to, uint256 _value) internal { updateDividend(_from); updateDividend(_to); uint256 transAmount = unclaimedDividend[_from].mul(_value).div(balanceOf(_from)); unclaimedDividend[_from] = unclaimedDividend[_from].sub(transAmount); unclaimedDividend[_to] = unclaimedDividend[_to].add(transAmount); } /** * @dev Update the dividend of hodler * @param _hodler address The Address of the hodler */ function updateDividend(address _hodler) internal { // last update in previous period -> reset claimable dividend if (lastUpdate[_hodler] < lastDividendIncreaseDate) { unclaimedDividend[_hodler] = calcDividend(_hodler, totalSupply_); lastUpdate[_hodler] = block.timestamp; } } /** * @dev Get claimable dividend for the hodler * @param _hodler address The Address of the hodler */ function getClaimableDividend(address _hodler) public constant returns (uint256 claimableDividend) { if (lastUpdate[_hodler] < lastDividendIncreaseDate) { return calcDividend(_hodler, totalSupply_); } else { return (unclaimedDividend[_hodler]); } } /** * @dev Overrides transfer method from BasicToken * transfer token for a specified address * @param _to address The address to transfer to. * @param _value uint256 The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { transferDividend(msg.sender, _to, _value); // Return from inherited transfer method return super.transfer(_to, _value); } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { // Prevent dividend to be claimed twice transferDividend(_from, _to, _value); // Return from inherited transferFrom method return super.transferFrom(_from, _to, _value); } /** * @dev Set / alter treasurer "account". This can be done from owner only * @param _treasurer address Address of the treasurer to create/alter * @param _active bool Flag that shows if the treasurer account is active */ function setTreasurer(address _treasurer, bool _active) public onlyOwner { isTreasurer[_treasurer] = _active; emit ChangedTreasurer(_treasurer, _active); } /** * @dev Request unclaimed ETH, payback to beneficiary (owner) wallet * dividend payment is possible every 330 days at the earliest - can be later, this allows for some flexibility, * e.g. board meeting had to happen a bit earlier this year than previous year. */ function requestUnclaimed() public onlyOwner { // Send remaining ETH to beneficiary (back to owner) if dividend round is over require(block.timestamp >= dividendEndTime.sub(claimTimeout)); msg.sender.transfer(address(this).balance); emit Reclaimed(address(this).balance, dividendEndTime, block.timestamp); } /** * @dev ETH Payin for Treasurer * Only owner or treasurer can do a payin for all token holder. * Owner / treasurer can also increase dividend by calling fallback function multiple times. */ function() public payable { require(isTreasurer[msg.sender]); require(dividendEndTime < block.timestamp); // pay back unclaimed dividend that might not have been claimed by owner yet if (address(this).balance > msg.value) { uint256 payout = address(this).balance.sub(msg.value); owner.transfer(payout); emit Reclaimed(payout, dividendEndTime, block.timestamp); } currentDividend = address(this).balance; // No active dividend cycle found, initialize new round dividendEndTime = block.timestamp.add(dividendCycleTime); // Trigger payin event emit Payin(msg.sender, msg.value, dividendEndTime); lastDividendIncreaseDate = block.timestamp; } /** * @dev calculate the dividend * @param _hodler address * @param _totalSupply uint256 */ function calcDividend(address _hodler, uint256 _totalSupply) public view returns(uint256) { return (currentDividend.mul(balanceOf(_hodler))).div(_totalSupply); } } contract TendToken is MintableToken, PausableToken, DividendToken { using SafeMath for uint256; string public constant name = "Tend Token"; string public constant symbol = "TTA"; uint8 public constant decimals = 18; // Minimum transferable chunk uint256 public granularity = 1e18; /** * @dev Constructor of TendToken that instantiate a new DividendToken */ constructor() public DividendToken() { // token should not be transferrable until after all tokens have been issued paused = true; } /** * @dev Internal function that ensures `_amount` is multiple of the granularity * @param _amount The quantity that wants to be checked */ function requireMultiple(uint256 _amount) internal view { require(_amount.div(granularity).mul(granularity) == _amount); } /** * @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) { requireMultiple(_value); return super.transfer(_to, _value); } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { requireMultiple(_value); return super.transferFrom(_from, _to, _value); } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) public returns (bool) { requireMultiple(_amount); // Return from inherited mint method return super.mint(_to, _amount); } /** * @dev Function to batch mint tokens * @param _to An array of addresses that will receive the minted tokens. * @param _amount An array with the amounts of tokens each address will get minted. * @return A boolean that indicates whether the operation was successful. */ function batchMint( address[] _to, uint256[] _amount ) hasMintPermission canMint public returns (bool) { require(_to.length == _amount.length); for (uint i = 0; i < _to.length; i++) { requireMultiple(_amount[i]); require(mint(_to[i], _amount[i])); } return true; } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { function safeTransfer(ERC20Basic token, address to, uint256 value) internal { require(token.transfer(to, value)); } function safeTransferFrom( ERC20 token, address from, address to, uint256 value ) internal { require(token.transferFrom(from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { require(token.approve(spender, value)); } } /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract TokenVesting is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20Basic; event Released(uint256 amount); event Revoked(); // beneficiary of tokens after they are released address public beneficiary; uint256 public cliff; uint256 public start; uint256 public duration; bool public revocable; mapping (address => uint256) public released; mapping (address => bool) public revoked; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor( address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable ) public { require(_beneficiary != address(0)); require(_cliff <= _duration); beneficiary = _beneficiary; revocable = _revocable; duration = _duration; cliff = _start.add(_cliff); start = _start; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(ERC20Basic token) public { uint256 unreleased = releasableAmount(token); require(unreleased > 0); released[token] = released[token].add(unreleased); token.safeTransfer(beneficiary, unreleased); emit Released(unreleased); } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(ERC20Basic token) public onlyOwner { require(revocable); require(!revoked[token]); uint256 balance = token.balanceOf(this); uint256 unreleased = releasableAmount(token); uint256 refund = balance.sub(unreleased); revoked[token] = true; token.safeTransfer(owner, refund); emit Revoked(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function releasableAmount(ERC20Basic token) public view returns (uint256) { return vestedAmount(token).sub(released[token]); } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { return totalBalance.mul(block.timestamp.sub(start)).div(duration); } } } contract RoundedTokenVesting is TokenVesting { using SafeMath for uint256; // Minimum transferable chunk uint256 public granularity; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * _beneficiary, gradually in a linear fashion until _start + _duration. By then all * of the balance will have vested. * @param _beneficiary address of the beneficiary to whom vested tokens are transferred * @param _cliff duration in seconds of the cliff in which tokens will begin to vest * @param _start the time (as Unix time) at which point vesting starts * @param _duration duration in seconds of the period in which the tokens will vest * @param _revocable whether the vesting is revocable or not */ constructor( address _beneficiary, uint256 _start, uint256 _cliff, uint256 _duration, bool _revocable, uint256 _granularity ) public TokenVesting(_beneficiary, _start, _cliff, _duration, _revocable) { granularity = _granularity; } /** * @dev Calculates the amount that has already vested. * @param token ERC20 token which is being vested */ function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; } else if (block.timestamp >= start.add(duration) || revoked[token]) { return totalBalance; } else { uint256 notRounded = totalBalance.mul(block.timestamp.sub(start)).div(duration); // Round down to the nearest token chunk by using integer division: (x / 1e18) * 1e18 uint256 rounded = notRounded.div(granularity).mul(granularity); return rounded; } } } contract TendTokenVested is TendToken { using SafeMath for uint256; /*** CONSTANTS ***/ uint256 public constant DEVELOPMENT_TEAM_CAP = 2e6 * 1e18; // 2 million * 1e18 uint256 public constant VESTING_CLIFF = 0 days; uint256 public constant VESTING_DURATION = 3 * 365 days; uint256 public developmentTeamTokensMinted; // for convenience we store vesting wallets address[] public vestingWallets; modifier onlyNoneZero(address _to, uint256 _amount) { require(_to != address(0)); require(_amount > 0); _; } /** * @dev allows contract owner to mint team tokens per DEVELOPMENT_TEAM_CAP and transfer to the development team's wallet (yes vesting) * @param _to address for beneficiary * @param _tokens uint256 token amount to mint */ function mintDevelopmentTeamTokens(address _to, uint256 _tokens) public onlyOwner onlyNoneZero(_to, _tokens) returns (bool) { requireMultiple(_tokens); require(developmentTeamTokensMinted.add(_tokens) <= DEVELOPMENT_TEAM_CAP); developmentTeamTokensMinted = developmentTeamTokensMinted.add(_tokens); RoundedTokenVesting newVault = new RoundedTokenVesting(_to, block.timestamp, VESTING_CLIFF, VESTING_DURATION, false, granularity); vestingWallets.push(address(newVault)); // for convenience we keep them in storage so that they are easily accessible via MEW or etherscan return mint(address(newVault), _tokens); } /** * @dev returns number of elements in the vestinWallets array */ function getVestingWalletLength() public view returns (uint256) { return vestingWallets.length; } }
* @dev Calculates the amount that has already vested. @param token ERC20 token which is being vested/ Round down to the nearest token chunk by using integer division: (x / 1e18) * 1e18
function vestedAmount(ERC20Basic token) public view returns (uint256) { uint256 currentBalance = token.balanceOf(this); uint256 totalBalance = currentBalance.add(released[token]); if (block.timestamp < cliff) { return 0; return totalBalance; uint256 notRounded = totalBalance.mul(block.timestamp.sub(start)).div(duration); uint256 rounded = notRounded.div(granularity).mul(granularity); return rounded; } }
12,540,964
[ 1, 10587, 326, 3844, 716, 711, 1818, 331, 3149, 18, 225, 1147, 4232, 39, 3462, 1147, 1492, 353, 3832, 331, 3149, 19, 11370, 2588, 358, 326, 11431, 1147, 2441, 635, 1450, 3571, 16536, 30, 261, 92, 342, 404, 73, 2643, 13, 225, 404, 73, 2643, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 331, 3149, 6275, 12, 654, 39, 3462, 8252, 1147, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 783, 13937, 273, 1147, 18, 12296, 951, 12, 2211, 1769, 203, 3639, 2254, 5034, 2078, 13937, 273, 783, 13937, 18, 1289, 12, 9340, 72, 63, 2316, 19226, 203, 203, 3639, 309, 261, 2629, 18, 5508, 411, 927, 3048, 13, 288, 203, 5411, 327, 374, 31, 203, 5411, 327, 2078, 13937, 31, 203, 5411, 2254, 5034, 486, 54, 12002, 273, 2078, 13937, 18, 16411, 12, 2629, 18, 5508, 18, 1717, 12, 1937, 13, 2934, 2892, 12, 8760, 1769, 203, 203, 5411, 2254, 5034, 16729, 273, 486, 54, 12002, 18, 2892, 12, 75, 27234, 2934, 16411, 12, 75, 27234, 1769, 203, 203, 5411, 327, 16729, 31, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IERC20 { function TOTALSUPPLY267() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF771(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER36(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE520(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE275(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM54(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER513(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL255(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } library SafeMath { function ADD260(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB684(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB684(a, b, "SafeMath: subtraction overflow"); } function SUB684(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL872(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function DIV551(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV551(a, b, "SafeMath: division by zero"); } function DIV551(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD699(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD699(a, b, "SafeMath: modulo by zero"); } function MOD699(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library Address { function ISCONTRACT292(address account) internal view returns (bool) { //inject NONSTANDARD NAMING // 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; } function SENDVALUE986(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING 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"); } function FUNCTIONCALL437(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALL437(target, data, "Address: low-level call failed"); } function FUNCTIONCALL437(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING return _FUNCTIONCALLWITHVALUE654(target, data, 0, errorMessage); } function FUNCTIONCALLWITHVALUE142(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING return FUNCTIONCALLWITHVALUE142(target, data, value, "Address: low-level call with value failed"); } function FUNCTIONCALLWITHVALUE142(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING require(address(this).balance >= value, "Address: insufficient balance for call"); return _FUNCTIONCALLWITHVALUE654(target, data, value, errorMessage); } function _FUNCTIONCALLWITHVALUE654(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING require(ISCONTRACT292(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); } } } } library SafeERC20 { using SafeMath for uint256; using Address for address; function SAFETRANSFER627(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.TRANSFER36.selector, to, value)); } function SAFETRANSFERFROM565(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING _CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.TRANSFERFROM54.selector, from, to, value)); } function SAFEAPPROVE47(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING // 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.ALLOWANCE520(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.APPROVE275.selector, spender, value)); } function SAFEINCREASEALLOWANCE824(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE520(address(this), spender).ADD260(value); _CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.APPROVE275.selector, spender, newAllowance)); } function SAFEDECREASEALLOWANCE914(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING uint256 newAllowance = token.ALLOWANCE520(address(this), spender).SUB684(value, "SafeERC20: decreased allowance below zero"); _CALLOPTIONALRETURN808(token, abi.encodeWithSelector(token.APPROVE275.selector, spender, newAllowance)); } function _CALLOPTIONALRETURN808(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING // 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).FUNCTIONCALL437(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"); } } } interface IMultiVaultStrategy { function WANT777() external view returns (address); //inject NONSTANDARD NAMING function DEPOSIT294() external; //inject NONSTANDARD NAMING function WITHDRAW808(address _asset) external; //inject NONSTANDARD NAMING function WITHDRAW808(uint _amount) external returns (uint); //inject NONSTANDARD NAMING function WITHDRAWTOCONTROLLER653(uint _amount) external; //inject NONSTANDARD NAMING function SKIM294() external; //inject NONSTANDARD NAMING function HARVEST506(address _mergedStrategy) external; //inject NONSTANDARD NAMING function WITHDRAWALL927() external returns (uint); //inject NONSTANDARD NAMING function BALANCEOF771() external view returns (uint); //inject NONSTANDARD NAMING function WITHDRAWFEE692(uint) external view returns (uint); // pJar: 0.5% (50/10000) //inject NONSTANDARD NAMING } interface IValueMultiVault { function CAP418() external view returns (uint); //inject NONSTANDARD NAMING function GETCONVERTER215(address _want) external view returns (address); //inject NONSTANDARD NAMING function GETVAULTMASTER236() external view returns (address); //inject NONSTANDARD NAMING function BALANCE180() external view returns (uint); //inject NONSTANDARD NAMING function TOKEN385() external view returns (address); //inject NONSTANDARD NAMING function AVAILABLE930(address _want) external view returns (uint); //inject NONSTANDARD NAMING function ACCEPT281(address _input) external view returns (bool); //inject NONSTANDARD NAMING function CLAIMINSURANCE45() external; //inject NONSTANDARD NAMING function EARN427(address _want) external; //inject NONSTANDARD NAMING function HARVEST506(address reserve, uint amount) external; //inject NONSTANDARD NAMING function WITHDRAW_FEE118(uint _shares) external view returns (uint); //inject NONSTANDARD NAMING function CALC_TOKEN_AMOUNT_DEPOSIT453(uint[] calldata _amounts) external view returns (uint); //inject NONSTANDARD NAMING function CALC_TOKEN_AMOUNT_WITHDRAW2(uint _shares, address _output) external view returns (uint); //inject NONSTANDARD NAMING function CONVERT_RATE825(address _input, uint _amount) external view returns (uint); //inject NONSTANDARD NAMING function GETPRICEPERFULLSHARE124() external view returns (uint); //inject NONSTANDARD NAMING function GET_VIRTUAL_PRICE769() external view returns (uint); // average dollar value of vault share token //inject NONSTANDARD NAMING function DEPOSIT294(address _input, uint _amount, uint _min_mint_amount) external returns (uint _mint_amount); //inject NONSTANDARD NAMING function DEPOSITFOR247(address _account, address _to, address _input, uint _amount, uint _min_mint_amount) external returns (uint _mint_amount); //inject NONSTANDARD NAMING function DEPOSITALL52(uint[] calldata _amounts, uint _min_mint_amount) external returns (uint _mint_amount); //inject NONSTANDARD NAMING function DEPOSITALLFOR442(address _account, address _to, uint[] calldata _amounts, uint _min_mint_amount) external returns (uint _mint_amount); //inject NONSTANDARD NAMING function WITHDRAW808(uint _shares, address _output, uint _min_output_amount) external returns (uint); //inject NONSTANDARD NAMING function WITHDRAWFOR513(address _account, uint _shares, address _output, uint _min_output_amount) external returns (uint _output_amount); //inject NONSTANDARD NAMING function HARVESTSTRATEGY825(address _strategy) external; //inject NONSTANDARD NAMING function HARVESTWANT168(address _want) external; //inject NONSTANDARD NAMING function HARVESTALLSTRATEGIES334() external; //inject NONSTANDARD NAMING } interface IShareConverter { function CONVERT_SHARES_RATE463(address _input, address _output, uint _inputAmount) external view returns (uint _outputAmount); //inject NONSTANDARD NAMING function CONVERT_SHARES33(address _input, address _output, uint _inputAmount) external returns (uint _outputAmount); //inject NONSTANDARD NAMING } interface Converter { function CONVERT349(address) external returns (uint); //inject NONSTANDARD NAMING } contract MultiStablesVaultController { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint; address public governance; address public strategist; struct StrategyInfo { address strategy; uint quota; // set = 0 to disable uint percent; } IValueMultiVault public vault; address public basedWant; address[] public wantTokens; // sorted by preference // want => quota, length mapping(address => uint) public wantQuota; mapping(address => uint) public wantStrategyLength; // want => stratId => StrategyInfo mapping(address => mapping(uint => StrategyInfo)) public strategies; mapping(address => mapping(address => bool)) public approvedStrategies; mapping(address => bool) public investDisabled; IShareConverter public shareConverter; // converter for shares (3CRV <-> BCrv, etc ...) address public lazySelectedBestStrategy; // we pre-set the best strategy to avoid gas cost of iterating the array constructor(IValueMultiVault _vault) public { require(address(_vault) != address(0), "!_vault"); vault = _vault; basedWant = vault.TOKEN385(); governance = msg.sender; strategist = msg.sender; } function SETGOVERNANCE701(address _governance) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); governance = _governance; } function SETSTRATEGIST330(address _strategist) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); strategist = _strategist; } function APPROVESTRATEGY673(address _want, address _strategy) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); approvedStrategies[_want][_strategy] = true; } function REVOKESTRATEGY92(address _want, address _strategy) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); approvedStrategies[_want][_strategy] = false; } function SETWANTQUOTA716(address _want, uint _quota) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); wantQuota[_want] = _quota; } function SETWANTSTRATEGYLENGTH858(address _want, uint _length) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); wantStrategyLength[_want] = _length; } // want => stratId => StrategyInfo function SETSTRATEGYINFO462(address _want, uint _sid, address _strategy, uint _quota, uint _percent) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); require(approvedStrategies[_want][_strategy], "!approved"); strategies[_want][_sid].strategy = _strategy; strategies[_want][_sid].quota = _quota; strategies[_want][_sid].percent = _percent; } function SETSHARECONVERTER560(IShareConverter _shareConverter) external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); shareConverter = _shareConverter; } function SETINVESTDISABLED819(address _want, bool _investDisabled) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); investDisabled[_want] = _investDisabled; } function SETWANTTOKENS997(address[] memory _wantTokens) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); delete wantTokens; uint _wlength = _wantTokens.length; for (uint i = 0; i < _wlength; ++i) { wantTokens.push(_wantTokens[i]); } } function GETSTRATEGYCOUNT337() external view returns(uint _strategyCount) { //inject NONSTANDARD NAMING _strategyCount = 0; uint _wlength = wantTokens.length; for (uint i = 0; i < _wlength; i++) { _strategyCount = _strategyCount.ADD260(wantStrategyLength[wantTokens[i]]); } } function WANTLENGTH873() external view returns (uint) { //inject NONSTANDARD NAMING return wantTokens.length; } function WANTSTRATEGYBALANCE73(address _want) public view returns (uint) { //inject NONSTANDARD NAMING uint _bal = 0; for (uint _sid = 0; _sid < wantStrategyLength[_want]; _sid++) { _bal = _bal.ADD260(IMultiVaultStrategy(strategies[_want][_sid].strategy).BALANCEOF771()); } return _bal; } function WANT777() external view returns (address) { //inject NONSTANDARD NAMING if (lazySelectedBestStrategy != address(0)) { return IMultiVaultStrategy(lazySelectedBestStrategy).WANT777(); } uint _wlength = wantTokens.length; if (_wlength > 0) { if (_wlength == 1) { return wantTokens[0]; } for (uint i = 0; i < _wlength; i++) { address _want = wantTokens[i]; uint _bal = WANTSTRATEGYBALANCE73(_want); if (_bal < wantQuota[_want]) { return _want; } } } return basedWant; } function SETLAZYSELECTEDBESTSTRATEGY629(address _strategy) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); lazySelectedBestStrategy = _strategy; } function GETBESTSTRATEGY227(address _want) public view returns (address _strategy) { //inject NONSTANDARD NAMING if (lazySelectedBestStrategy != address(0) && IMultiVaultStrategy(lazySelectedBestStrategy).WANT777() == _want) { return lazySelectedBestStrategy; } uint _wantStrategyLength = wantStrategyLength[_want]; _strategy = address(0); if (_wantStrategyLength == 0) return _strategy; uint _totalBal = WANTSTRATEGYBALANCE73(_want); if (_totalBal == 0) { // first depositor, simply return the first strategy return strategies[_want][0].strategy; } uint _bestDiff = 201; for (uint _sid = 0; _sid < _wantStrategyLength; _sid++) { StrategyInfo storage sinfo = strategies[_want][_sid]; uint _stratBal = IMultiVaultStrategy(sinfo.strategy).BALANCEOF771(); if (_stratBal < sinfo.quota) { uint _diff = _stratBal.ADD260(_totalBal).MUL872(100).DIV551(_totalBal).SUB684(sinfo.percent); // [100, 200] - [percent] if (_diff < _bestDiff) { _bestDiff = _diff; _strategy = sinfo.strategy; } } } if (_strategy == address(0)) { _strategy = strategies[_want][0].strategy; } } function EARN427(address _token, uint _amount) external { //inject NONSTANDARD NAMING require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist"); address _strategy = GETBESTSTRATEGY227(_token); if (_strategy == address(0) || IMultiVaultStrategy(_strategy).WANT777() != _token) { // forward to vault and then call earnExtra() by its governance IERC20(_token).SAFETRANSFER627(address(vault), _amount); } else { IERC20(_token).SAFETRANSFER627(_strategy, _amount); IMultiVaultStrategy(_strategy).DEPOSIT294(); } } function WITHDRAW_FEE118(address _want, uint _amount) external view returns (uint) { //inject NONSTANDARD NAMING address _strategy = GETBESTSTRATEGY227(_want); return (_strategy == address(0)) ? 0 : IMultiVaultStrategy(_strategy).WITHDRAWFEE692(_amount); } function BALANCEOF771(address _want, bool _sell) external view returns (uint _totalBal) { //inject NONSTANDARD NAMING uint _wlength = wantTokens.length; if (_wlength == 0) { return 0; } _totalBal = 0; for (uint i = 0; i < _wlength; i++) { address wt = wantTokens[i]; uint _bal = WANTSTRATEGYBALANCE73(wt); if (wt != _want) { _bal = shareConverter.CONVERT_SHARES_RATE463(wt, _want, _bal); if (_sell) { _bal = _bal.MUL872(9998).DIV551(10000); // minus 0.02% for selling } } _totalBal = _totalBal.ADD260(_bal); } } function WITHDRAWALL927(address _strategy) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); // WithdrawAll sends 'want' to 'vault' IMultiVaultStrategy(_strategy).WITHDRAWALL927(); } function INCASETOKENSGETSTUCK116(address _token, uint _amount) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); IERC20(_token).SAFETRANSFER627(address(vault), _amount); } function INCASESTRATEGYGETSTUCK927(address _strategy, address _token) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); IMultiVaultStrategy(_strategy).WITHDRAW808(_token); IERC20(_token).SAFETRANSFER627(address(vault), IERC20(_token).BALANCEOF771(address(this))); } function CLAIMINSURANCE45() external { //inject NONSTANDARD NAMING require(msg.sender == governance, "!governance"); vault.CLAIMINSURANCE45(); } // note that some strategies do not allow controller to harvest function HARVESTSTRATEGY825(address _strategy) external { //inject NONSTANDARD NAMING require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist && !vault"); IMultiVaultStrategy(_strategy).HARVEST506(address(0)); } function HARVESTWANT168(address _want) external { //inject NONSTANDARD NAMING require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist && !vault"); uint _wantStrategyLength = wantStrategyLength[_want]; address _firstStrategy = address(0); // to send all harvested WETH and proceed the profit sharing all-in-one here for (uint _sid = 0; _sid < _wantStrategyLength; _sid++) { StrategyInfo storage sinfo = strategies[_want][_sid]; if (_firstStrategy == address(0)) { _firstStrategy = sinfo.strategy; } else { IMultiVaultStrategy(sinfo.strategy).HARVEST506(_firstStrategy); } } if (_firstStrategy != address(0)) { IMultiVaultStrategy(_firstStrategy).HARVEST506(address(0)); } } function HARVESTALLSTRATEGIES334() external { //inject NONSTANDARD NAMING require(msg.sender == address(vault) || msg.sender == strategist || msg.sender == governance, "!strategist && !vault"); uint _wlength = wantTokens.length; address _firstStrategy = address(0); // to send all harvested WETH and proceed the profit sharing all-in-one here for (uint i = 0; i < _wlength; i++) { address _want = wantTokens[i]; uint _wantStrategyLength = wantStrategyLength[_want]; for (uint _sid = 0; _sid < _wantStrategyLength; _sid++) { StrategyInfo storage sinfo = strategies[_want][_sid]; if (_firstStrategy == address(0)) { _firstStrategy = sinfo.strategy; } else { IMultiVaultStrategy(sinfo.strategy).HARVEST506(_firstStrategy); } } } if (_firstStrategy != address(0)) { IMultiVaultStrategy(_firstStrategy).HARVEST506(address(0)); } } function SWITCHFUND172(IMultiVaultStrategy _srcStrat, IMultiVaultStrategy _destStrat, uint _amount) external { //inject NONSTANDARD NAMING require(msg.sender == strategist || msg.sender == governance, "!strategist"); _srcStrat.WITHDRAWTOCONTROLLER653(_amount); address _srcWant = _srcStrat.WANT777(); address _destWant = _destStrat.WANT777(); if (_srcWant != _destWant) { _amount = IERC20(_srcWant).BALANCEOF771(address(this)); require(shareConverter.CONVERT_SHARES_RATE463(_srcWant, _destWant, _amount) > 0, "rate=0"); IERC20(_srcWant).SAFETRANSFER627(address(shareConverter), _amount); shareConverter.CONVERT_SHARES33(_srcWant, _destWant, _amount); } IERC20(_destWant).SAFETRANSFER627(address(_destStrat), IERC20(_destWant).BALANCEOF771(address(this))); _destStrat.DEPOSIT294(); } function WITHDRAW808(address _want, uint _amount) external returns (uint _withdrawFee) { //inject NONSTANDARD NAMING require(msg.sender == address(vault), "!vault"); _withdrawFee = 0; uint _toWithdraw = _amount; uint _wantStrategyLength = wantStrategyLength[_want]; uint _received; for (uint _sid = _wantStrategyLength; _sid > 0; _sid--) { StrategyInfo storage sinfo = strategies[_want][_sid - 1]; IMultiVaultStrategy _strategy = IMultiVaultStrategy(sinfo.strategy); uint _stratBal = _strategy.BALANCEOF771(); if (_toWithdraw < _stratBal) { _received = _strategy.WITHDRAW808(_toWithdraw); _withdrawFee = _withdrawFee.ADD260(_strategy.WITHDRAWFEE692(_received)); return _withdrawFee; } _received = _strategy.WITHDRAWALL927(); _withdrawFee = _withdrawFee.ADD260(_strategy.WITHDRAWFEE692(_received)); if (_received >= _toWithdraw) { return _withdrawFee; } _toWithdraw = _toWithdraw.SUB684(_received); } if (_toWithdraw > 0) { // still not enough, try to withdraw from other wants strategies uint _wlength = wantTokens.length; for (uint i = _wlength; i > 0; i--) { address wt = wantTokens[i - 1]; if (wt != _want) { (uint _wamt, uint _wdfee) = _WITHDRAWOTHERWANT971(_want, wt, _toWithdraw); _withdrawFee = _withdrawFee.ADD260(_wdfee); if (_wamt >= _toWithdraw) { return _withdrawFee; } _toWithdraw = _toWithdraw.SUB684(_wamt); } } } return _withdrawFee; } function _WITHDRAWOTHERWANT971(address _want, address _other, uint _amount) internal returns (uint _wantAmount, uint _withdrawFee) { //inject NONSTANDARD NAMING // Check balance uint b = IERC20(_want).BALANCEOF771(address(this)); _withdrawFee = 0; if (b >= _amount) { _wantAmount = b; } else { uint _toWithdraw = _amount.SUB684(b); uint _toWithdrawOther = _toWithdraw.MUL872(101).DIV551(100); // add 1% extra uint _otherBal = IERC20(_other).BALANCEOF771(address(this)); if (_otherBal < _toWithdrawOther) { uint _otherStrategyLength = wantStrategyLength[_other]; for (uint _sid = _otherStrategyLength; _sid > 0; _sid--) { StrategyInfo storage sinfo = strategies[_other][_sid - 1]; IMultiVaultStrategy _strategy = IMultiVaultStrategy(sinfo.strategy); uint _stratBal = _strategy.BALANCEOF771(); uint _needed = _toWithdrawOther.SUB684(_otherBal); uint _wdamt = (_needed < _stratBal) ? _needed : _stratBal; _strategy.WITHDRAWTOCONTROLLER653(_wdamt); _withdrawFee = _withdrawFee.ADD260(_strategy.WITHDRAWFEE692(_wdamt)); _otherBal = IERC20(_other).BALANCEOF771(address(this)); if (_otherBal >= _toWithdrawOther) { break; } } } IERC20(_other).SAFETRANSFER627(address(shareConverter), _otherBal); shareConverter.CONVERT_SHARES33(_other, _want, _otherBal); _wantAmount = IERC20(_want).BALANCEOF771(address(this)); } IERC20(_want).SAFETRANSFER627(address(vault), _wantAmount); } }
inject NONSTANDARD NAMING
function SETSTRATEGIST330(address _strategist) external {
13,085,383
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7855, 3902, 1777, 43, 5511, 3707, 20, 12, 2867, 389, 701, 1287, 376, 13, 3903, 288, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xe76D0D6425223433A7C49761545254E648e0DC03/sources/ZOGZ.sol
Anti-bot and anti-whale mappings and variables Seller Map Blacklist Map block number of opened trading exclude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract ZOGZ is ERC20, Ownable { string _name = "ZOGZ.fun"; string _symbol = "ZOGZ"; using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool private isSwapping; address private treasuryWallet; address private devWallet; uint256 public maxTx; uint256 public swapTreshold; uint256 public maxWallet; bool public limitsActive = true; bool public tradingLive = false; bool public swapEnabled = true; bool public shouldContractSellAll = false; mapping (address => uint256) private _holderFirstBuyTimestamp; mapping (address => bool) private _blacklist; bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyTreasuryFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellTreasuryFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForTreasury; uint256 public tokensForLiquidity; uint256 public tokensForDev; uint256 launchedAt; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event treasuryWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); event AutoNukeLP(); event ManualNukeLP(); constructor() ERC20(_name, _symbol) { 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 _buyTreasuryFee = 25; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellTreasuryFee = 40; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 totalSupply = 111 * 1e18; buyTreasuryFee = _buyTreasuryFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyTreasuryFee + buyLiquidityFee + buyDevFee; sellTreasuryFee = _sellTreasuryFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellTreasuryFee + sellLiquidityFee + sellDevFee; treasuryWallet = address(0x24c2666B6c594A37B16e5a6A5B118fc7aD4351fD); devWallet = address(0x24c2666B6c594A37B16e5a6A5B118fc7aD4351fD); excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromFees(address(treasuryWallet), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); excludeFromMaxTransaction(address(devWallet), true); excludeFromMaxTransaction(address(treasuryWallet), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply); } receive() external payable { } function activateTrading() external onlyOwner { tradingLive = true; swapEnabled = true; launchedAt = block.number; } function removeLimits() external onlyOwner returns (bool){ limitsActive = false; return true; } function disableTransferDelay() external onlyOwner returns (bool){ transferDelayEnabled = false; return true; } function enableEmptyContract(bool enabled) external onlyOwner{ shouldContractSellAll = enabled; } function setSwapTreshold(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTreshold = newAmount; return true; } function updateTransactionLimits(uint256 _maxTx, uint256 _maxWallet) external onlyOwner { require(_maxTx >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); require(_maxWallet >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxTx = _maxTx * (10**18); maxWallet = _maxWallet * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function reduceFees( uint256 _devBuyFee, uint256 _liquidityBuyFee, uint256 _treasuryBuyFee, uint256 _devSellFee, uint256 _liquiditySellFee, uint256 _treasurySellFee ) external onlyOwner { require(_devBuyFee <= buyDevFee && _liquidityBuyFee <= buyLiquidityFee && _treasuryBuyFee <= buyTreasuryFee && _devSellFee <= sellDevFee && _liquiditySellFee <= sellLiquidityFee && _treasurySellFee <= sellTreasuryFee, "Fees must be lower then the current"); buyDevFee = _devBuyFee; buyLiquidityFee = _liquidityBuyFee; buyTreasuryFee = _treasuryBuyFee; buyTotalFees = buyDevFee + buyLiquidityFee + buyTreasuryFee; sellDevFee = _devSellFee; sellLiquidityFee = _liquiditySellFee; sellTreasuryFee = _treasurySellFee; sellTotalFees = sellDevFee + sellLiquidityFee + sellTreasuryFee; require(buyTotalFees <= 30 && sellTotalFees <= 30, "Fees cannot be higher then 30%"); } function updateContractSellEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function blacklist(address account, bool isBlacklisted) public onlyOwner { _blacklist[account] = isBlacklisted; } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateFeeRecivers(address newTreasuryWallet, address newDevWallet) external onlyOwner{ emit treasuryWalletUpdated(newTreasuryWallet, treasuryWallet); treasuryWallet = newTreasuryWallet; emit devWalletUpdated(newDevWallet, devWallet); devWallet = newDevWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { } if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsActive){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !isSwapping ){ if(!tradingLive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTx, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTx, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTreshold; if( canSwap && swapEnabled && !isSwapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForTreasury += fees * sellTreasuryFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForTreasury += fees * buyTreasuryFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { } if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsActive){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !isSwapping ){ if(!tradingLive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTx, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTx, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTreshold; if( canSwap && swapEnabled && !isSwapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForTreasury += fees * sellTreasuryFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForTreasury += fees * buyTreasuryFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { } if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsActive){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !isSwapping ){ if(!tradingLive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTx, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTx, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTreshold; if( canSwap && swapEnabled && !isSwapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForTreasury += fees * sellTreasuryFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForTreasury += fees * buyTreasuryFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { } if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsActive){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !isSwapping ){ if(!tradingLive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTx, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTx, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTreshold; if( canSwap && swapEnabled && !isSwapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForTreasury += fees * sellTreasuryFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForTreasury += fees * buyTreasuryFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { } if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsActive){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !isSwapping ){ if(!tradingLive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTx, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTx, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTreshold; if( canSwap && swapEnabled && !isSwapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForTreasury += fees * sellTreasuryFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForTreasury += fees * buyTreasuryFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { } if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsActive){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !isSwapping ){ if(!tradingLive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTx, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTx, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTreshold; if( canSwap && swapEnabled && !isSwapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForTreasury += fees * sellTreasuryFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForTreasury += fees * buyTreasuryFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { } if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsActive){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !isSwapping ){ if(!tradingLive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTx, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTx, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTreshold; if( canSwap && swapEnabled && !isSwapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForTreasury += fees * sellTreasuryFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForTreasury += fees * buyTreasuryFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { } if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsActive){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !isSwapping ){ if(!tradingLive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTx, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTx, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTreshold; if( canSwap && swapEnabled && !isSwapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForTreasury += fees * sellTreasuryFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForTreasury += fees * buyTreasuryFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { } if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsActive){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !isSwapping ){ if(!tradingLive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTx, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTx, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTreshold; if( canSwap && swapEnabled && !isSwapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForTreasury += fees * sellTreasuryFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForTreasury += fees * buyTreasuryFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { } if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsActive){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !isSwapping ){ if(!tradingLive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTx, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTx, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTreshold; if( canSwap && swapEnabled && !isSwapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForTreasury += fees * sellTreasuryFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForTreasury += fees * buyTreasuryFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { } if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsActive){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !isSwapping ){ if(!tradingLive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTx, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTx, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTreshold; if( canSwap && swapEnabled && !isSwapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForTreasury += fees * sellTreasuryFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForTreasury += fees * buyTreasuryFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { } if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsActive){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !isSwapping ){ if(!tradingLive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTx, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTx, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTreshold; if( canSwap && swapEnabled && !isSwapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForTreasury += fees * sellTreasuryFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForTreasury += fees * buyTreasuryFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { } if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsActive){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !isSwapping ){ if(!tradingLive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTx, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTx, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTreshold; if( canSwap && swapEnabled && !isSwapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForTreasury += fees * sellTreasuryFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForTreasury += fees * buyTreasuryFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { } if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsActive){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !isSwapping ){ if(!tradingLive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTx, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTx, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTreshold; if( canSwap && swapEnabled && !isSwapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForTreasury += fees * sellTreasuryFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForTreasury += fees * buyTreasuryFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { } if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsActive){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !isSwapping ){ if(!tradingLive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTx, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTx, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTreshold; if( canSwap && swapEnabled && !isSwapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForTreasury += fees * sellTreasuryFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForTreasury += fees * buyTreasuryFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { } if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsActive){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !isSwapping ){ if(!tradingLive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTx, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTx, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTreshold; if( canSwap && swapEnabled && !isSwapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForTreasury += fees * sellTreasuryFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForTreasury += fees * buyTreasuryFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(!_blacklist[to] && !_blacklist[from], "You have been blacklisted from transfering tokens"); if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { } if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsActive){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !isSwapping ){ if(!tradingLive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTx, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTx, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTreshold; if( canSwap && swapEnabled && !isSwapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { isSwapping = true; swapBack(); isSwapping = false; } bool takeFee = !isSwapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForTreasury += fees * sellTreasuryFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForTreasury += fees * buyTreasuryFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } 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 ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, address(this), block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForTreasury + tokensForDev; bool success; if(shouldContractSellAll == false){ if(contractBalance > swapTreshold * 20){ contractBalance = swapTreshold * 20; } contractBalance = balanceOf(address(this)); } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForTreasury).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForTreasury = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } if(contractBalance == 0 || totalTokensToSwap == 0) {return;} function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForTreasury + tokensForDev; bool success; if(shouldContractSellAll == false){ if(contractBalance > swapTreshold * 20){ contractBalance = swapTreshold * 20; } contractBalance = balanceOf(address(this)); } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForTreasury).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForTreasury = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForTreasury + tokensForDev; bool success; if(shouldContractSellAll == false){ if(contractBalance > swapTreshold * 20){ contractBalance = swapTreshold * 20; } contractBalance = balanceOf(address(this)); } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForTreasury).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForTreasury = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } }else{ uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; (success,) = address(devWallet).call{value: ethForDev}(""); function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForTreasury + tokensForDev; bool success; if(shouldContractSellAll == false){ if(contractBalance > swapTreshold * 20){ contractBalance = swapTreshold * 20; } contractBalance = balanceOf(address(this)); } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForTreasury).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForTreasury = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } (success,) = address(treasuryWallet).call{value: address(this).balance}(""); }
4,047,103
[ 1, 14925, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 4352, 749, 1635, 22467, 1098, 1635, 1203, 1300, 434, 10191, 1284, 7459, 4433, 628, 1656, 281, 471, 943, 2492, 3844, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 2285, 13369, 62, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 203, 565, 533, 389, 529, 273, 315, 62, 13369, 62, 18, 12125, 14432, 203, 565, 533, 389, 7175, 273, 315, 62, 13369, 62, 14432, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 7010, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 11732, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 7010, 565, 1426, 3238, 353, 12521, 1382, 31, 203, 7010, 565, 1758, 3238, 9787, 345, 22498, 16936, 31, 203, 565, 1758, 3238, 4461, 16936, 31, 203, 7010, 565, 2254, 5034, 1071, 943, 4188, 31, 203, 565, 2254, 5034, 1071, 7720, 56, 3444, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 31, 203, 7010, 565, 1426, 1071, 8181, 3896, 273, 638, 31, 203, 565, 1426, 1071, 1284, 7459, 12328, 273, 629, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 638, 31, 203, 565, 1426, 1071, 1410, 8924, 55, 1165, 1595, 273, 629, 31, 203, 7010, 7010, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 4505, 3759, 38, 9835, 4921, 31, 203, 7010, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 22491, 31, 203, 565, 1426, 1071, 7412, 6763, 1526, 273, 638, 31, 203, 7010, 565, 2254, 5034, 1071, 30143, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 30143, 56, 266, 345, 22498, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 48, 18988, 24237, 14667, 31, 203, 565, 2254, 2 ]
./partial_match/1/0x82De6D5e2CF5431Bf48Ba17D4f76Bf83b857950F/sources/TokenTimelock.sol
* @notice 将时间限制内的token转移给受益人./
function release() public { require(block.timestamp >= releaseTime); for (uint i=0;i<beneficial.length;i++ ){ uint256 amount = token.balanceOf(this); require(amount > 0); uint256 count = beneficiary[beneficial[i]]; if (amount>=count){ beneficiary[beneficial[i]] = 0; token.safeTransfer(beneficial[i], count); } } }
3,979,262
[ 1, 166, 113, 233, 167, 250, 119, 170, 250, 117, 170, 252, 243, 166, 235, 119, 166, 233, 232, 168, 253, 231, 2316, 169, 126, 110, 168, 105, 124, 168, 124, 252, 166, 242, 250, 168, 254, 237, 165, 123, 123, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 3992, 1435, 1071, 288, 203, 565, 2583, 12, 2629, 18, 5508, 1545, 3992, 950, 1769, 203, 377, 203, 565, 364, 261, 11890, 277, 33, 20, 31, 77, 32, 70, 4009, 74, 22354, 18, 2469, 31, 77, 9904, 262, 95, 203, 3639, 2254, 5034, 3844, 273, 1147, 18, 12296, 951, 12, 2211, 1769, 203, 3639, 2583, 12, 8949, 405, 374, 1769, 203, 3639, 2254, 5034, 1056, 273, 27641, 74, 14463, 814, 63, 70, 4009, 74, 22354, 63, 77, 13563, 31, 203, 3639, 309, 261, 8949, 34, 33, 1883, 15329, 203, 2398, 27641, 74, 14463, 814, 63, 70, 4009, 74, 22354, 63, 77, 13563, 273, 374, 31, 203, 2398, 1147, 18, 4626, 5912, 12, 70, 4009, 74, 22354, 63, 77, 6487, 1056, 1769, 203, 3639, 289, 203, 565, 289, 203, 225, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.19; contract Constants { uint32 public nbOfChunks; // Number of chunks to be stored = k uint32 public nbOfChunksEC; // Number of chunks after erasure code = n uint32 public snToBeChallenged;// Nb of storage nodes to challenge during this round = l uint32 public chunkToBeChallenged;// Nb of chunk to challenge per storage node = p uint32 public snNb; // Number of storage nodes storing a certain file = m function Constants (uint32 k, uint32 n , uint32 l, uint32 m, uint32 p) public { nbOfChunks = k; nbOfChunksEC = n; snToBeChallenged = l; snNb = m; chunkToBeChallenged = p; } // Setters for k,n, l and m function setK(uint32 k) public { nbOfChunks = k; } function setN(uint32 n) public { nbOfChunksEC = n; } function setSnToBeChallenged(uint32 l) public { snToBeChallenged = l; } function setSnNb(uint32 m) public { snNb = m; } function setChunkToBeChallenged(uint32 p) public { chunkToBeChallenged = p; } // Getters for k,n,l,m function getK() constant public returns (uint32 ) { return nbOfChunks; } function getN() constant public returns (uint32 ) { return nbOfChunksEC; } function getL() constant public returns (uint32 ) { return snToBeChallenged; } function getP() constant public returns (uint32 ) { return chunkToBeChallenged; } function getM() constant public returns (uint32 ) { return snNb; } function getAll() constant public returns (uint32 k, uint32 n, uint32 l, uint32 m, uint32 p) { return (nbOfChunks, nbOfChunksEC, snToBeChallenged, snNb, chunkToBeChallenged); } }
Number of storage nodes storing a certain file = m
uint32 public snNb;
7,288,436
[ 1, 1854, 434, 2502, 2199, 15729, 279, 8626, 585, 273, 312, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 2254, 1578, 1071, 4556, 22816, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x498b8787CAD210B033baC3F5E37a40e404F58c18/sources/contracts/ERC721A.sol
* the Metadata extension. Built to optimize for lower gas during batch mints. Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). Assumes that an owner cannot have more than 264 - 1 (max value of uint64) of supply. Assumes that the maximum token id cannot exceed 2256 - 1 (max value of uint256)./ Compiler will pack this into a single 256bit word.
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; bool burned; } struct AddressData { uint64 balance; uint64 numberMinted; uint64 numberBurned; uint64 aux; } uint256 internal _currentIndex; uint256 internal _burnCounter; string private _name; string private _symbol; mapping(uint256 => TokenOwnership) internal _ownerships; mapping(address => AddressData) private _addressData; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } function _startTokenId() internal view virtual returns (uint256) { return 0; } function totalSupply() public view returns (uint256) { unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } function totalSupply() public view returns (uint256) { unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } function _totalMinted() internal view returns (uint256) { unchecked { return _currentIndex - _startTokenId(); } } function _totalMinted() internal view returns (uint256) { unchecked { return _currentIndex - _startTokenId(); } } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberMinted); } function _numberBurned(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberBurned); } function _getAux(address owner) internal view returns (uint64) { return _addressData[owner].aux; } function _setAux(address owner, uint64 aux) internal { _addressData[owner].aux = aux; } function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } function ownerOf(uint256 tokenId) public view override returns (address) { return _ownershipOf(tokenId).addr; } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ''; } function _baseURI() internal view virtual returns (string memory) { return ''; } function approve(address to, uint256 tokenId) public override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } 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); } function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ''); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } 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); unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } 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); unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } 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); unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } 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); unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } 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); unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } if (_currentIndex != startTokenId) revert(); } else { 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); unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (safe && to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); _approve(address(0), tokenId, from); unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); _approve(address(0), tokenId, from); unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); _approve(address(0), tokenId, from); unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); _approve(address(0), tokenId, from); unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); unchecked { _burnCounter++; } } function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); unchecked { _burnCounter++; } } _approve(address(0), tokenId, from); function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); unchecked { _burnCounter++; } } function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); unchecked { _burnCounter++; } } function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); unchecked { _burnCounter++; } } function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); unchecked { _burnCounter++; } } function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); assembly { revert(add(32, reason), mload(reason)) } } } } function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); assembly { revert(add(32, reason), mload(reason)) } } } } } catch (bytes memory reason) { function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); assembly { revert(add(32, reason), mload(reason)) } } } } } else { function _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); assembly { revert(add(32, reason), mload(reason)) } } } } ) internal virtual {} ) internal virtual {} }
9,666,919
[ 1, 5787, 6912, 2710, 18, 27376, 358, 10979, 364, 2612, 16189, 4982, 2581, 312, 28142, 18, 25374, 2734, 87, 854, 695, 6979, 6261, 312, 474, 329, 5023, 622, 389, 1937, 1345, 548, 1435, 261, 7606, 358, 374, 16, 425, 18, 75, 18, 374, 16, 404, 16, 576, 16, 890, 838, 2934, 25374, 716, 392, 3410, 2780, 1240, 1898, 2353, 576, 1105, 300, 404, 261, 1896, 460, 434, 2254, 1105, 13, 434, 14467, 18, 25374, 716, 326, 4207, 1147, 612, 2780, 9943, 576, 5034, 300, 404, 261, 1896, 460, 434, 2254, 5034, 2934, 19, 12972, 903, 2298, 333, 1368, 279, 2202, 8303, 3682, 2076, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4232, 39, 27, 5340, 37, 353, 1772, 16, 4232, 39, 28275, 16, 467, 654, 39, 27, 5340, 16, 467, 654, 39, 27, 5340, 2277, 288, 203, 565, 1450, 5267, 364, 1758, 31, 203, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 203, 565, 1958, 3155, 5460, 12565, 288, 203, 3639, 1758, 3091, 31, 203, 3639, 2254, 1105, 787, 4921, 31, 203, 3639, 1426, 18305, 329, 31, 203, 565, 289, 203, 203, 565, 1958, 5267, 751, 288, 203, 3639, 2254, 1105, 11013, 31, 203, 3639, 2254, 1105, 1300, 49, 474, 329, 31, 203, 3639, 2254, 1105, 1300, 38, 321, 329, 31, 203, 3639, 2254, 1105, 9397, 31, 203, 565, 289, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 565, 2254, 5034, 2713, 389, 2972, 1016, 31, 203, 565, 2254, 5034, 2713, 389, 70, 321, 4789, 31, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2874, 12, 11890, 5034, 516, 3155, 5460, 12565, 13, 2713, 389, 995, 12565, 87, 31, 203, 565, 2874, 12, 2867, 516, 5267, 751, 13, 3238, 389, 2867, 751, 31, 203, 565, 2874, 12, 11890, 5034, 516, 1758, 13, 3238, 389, 2316, 12053, 4524, 31, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 1426, 3719, 3238, 389, 9497, 12053, 4524, 31, 203, 565, 3885, 12, 1080, 3778, 508, 67, 16, 533, 3778, 3273, 67, 13, 288, 203, 3639, 389, 529, 273, 508, 67, 31, 203, 3639, 389, 7175, 273, 3273, 67, 31, 203, 3639, 389, 2972, 1016, 273, 2 ]
/* Copyright 2018 Virtual Rehab (http://virtualrehab.co) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.4.24; import "openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol"; import "openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol"; import "./CustomPausable.sol"; ///@title Virtual Rehab Token (VRH) ERC20 Token Contract ///@author Binod Nirvan, Subramanian Venkatesan (http://virtualrehab.co) ///@notice The Virtual Rehab Token (VRH) has been created as a centralized currency ///to be used within the Virtual Rehab network. Users will be able to purchase and sell ///VRH tokens in exchanges. The token follows the standards of Ethereum ERC20 Standard token. ///Its design follows the widely adopted token implementation standards. ///This allows token holders to easily store and manage their VRH tokens using existing solutions ///including ERC20-compatible Ethereum wallets. The VRH Token is a utility token ///and is core to Virtual Rehab’s end-to-end operations. /// ///VRH utility use cases include: ///1. Order & Download Virtual Rehab programs through the Virtual Rehab Online Portal ///2. Request further analysis, conducted by Virtual Rehab's unique expert system (which leverages Artificial Intelligence), of the executed programs ///3. Receive incentives (VRH rewards) for seeking help and counselling from psychologists, therapists, or medical doctors ///4. Allows users to pay for services received at the Virtual Rehab Therapy Center contract VRHToken is StandardToken, CustomPausable, BurnableToken { uint8 public constant decimals = 18; string public constant name = "VirtualRehab"; string public constant symbol = "VRH"; uint public constant MAX_SUPPLY = 400000000 * (10 ** uint256(decimals)); uint public constant INITIAL_SUPPLY = (400000000 - 1650000 - 2085000 - 60000000) * (10 ** uint256(decimals)); bool public released = false; uint public ICOEndDate; mapping(bytes32 => bool) private mintingList; event Mint(address indexed to, uint256 amount); event BulkTransferPerformed(address[] _destinations, uint256[] _amounts); event TokenReleased(bool _state); event ICOEndDateSet(uint256 _date); ///@notice Checks if the supplied address is able to perform transfers. ///@param _from The address to check against if the transfer is allowed. modifier canTransfer(address _from) { if(paused || !released) { if(!isAdmin(_from)) { revert(); } } _; } ///@notice Computes keccak256 hash of the supplied value. ///@param _key The string value to compute hash from. function computeHash(string _key) private pure returns(bytes32){ return keccak256(abi.encodePacked(_key)); } ///@notice Checks if the minting for the supplied key was already performed. ///@param _key The key or category name of minting. modifier whenNotMinted(string _key) { if(mintingList[computeHash(_key)]) { revert(); } _; } constructor() public { mintTokens(msg.sender, INITIAL_SUPPLY); } ///@notice This function enables token transfers for everyone. ///Can only be enabled after the end of the ICO. function releaseTokenForTransfer() public onlyAdmin whenNotPaused { require(!released); released = true; emit TokenReleased(released); } ///@notice This function disables token transfers for everyone. function disableTokenTransfers() public onlyAdmin whenNotPaused { require(released); released = false; emit TokenReleased(released); } ///@notice This function enables the whitelisted application (internal application) to set the ICO end date and can only be used once. ///@param _date The date to set as the ICO end date. function setICOEndDate(uint _date) public onlyAdmin { require(ICOEndDate == 0); require(_date > now); ICOEndDate = _date; emit ICOEndDateSet(_date); } ///@notice Mints the supplied value of the tokens to the destination address. //Minting cannot be performed any further once the maximum supply is reached. //This function is private and cannot be used by anyone except for this contract. ///@param _to The address which will receive the minted tokens. ///@param _value The amount of tokens to mint. function mintTokens(address _to, uint _value) private { require(_to != address(0)); require(totalSupply_.add(_value) <= MAX_SUPPLY); balances[_to] = balances[_to].add(_value); totalSupply_ = totalSupply_.add(_value); emit Mint(_to, _value); emit Transfer(address(0), _to, _value); } ///@notice Mints the tokens only once against the supplied key (category). ///@param _key The key or the category of the allocation to mint the tokens for. ///@param _to The address receiving the minted tokens. ///@param _amount The amount of tokens to mint. function mintOnce(string _key, address _to, uint256 _amount) private whenNotPaused whenNotMinted(_key) { _amount = _amount * (10 ** uint256(decimals)); mintTokens(_to, _amount); mintingList[computeHash(_key)] = true; } ///@notice Mints the below-mentioned amount of tokens allocated to the Virtual Rehab advisors. //The tokens are only available to the advisors after 1 year of the ICO end. function mintTokensForAdvisors() public onlyAdmin { require(ICOEndDate != 0); require(now > (ICOEndDate + 365 days)); mintOnce("advisors", msg.sender, 1650000); } ///@notice Mints the below-mentioned amount of tokens allocated to the Virtual Rehab founders. //The tokens are only available to the founders after 2 year of the ICO end. function mintTokensForFounders() public onlyAdmin { require(ICOEndDate != 0); require(now > (ICOEndDate + 720 days)); mintOnce("founders", msg.sender, 60000000); } ///@notice Mints the below-mentioned amount of tokens allocated to Virtual Rehab services. //The tokens are only available to the services after 1 year of the ICO end. function mintTokensForServices() public onlyAdmin { require(ICOEndDate != 0); require(now > (ICOEndDate + 60 days)); mintOnce("services", msg.sender, 2085000); } ///@notice Transfers the specified value of VRH tokens to the destination address. //Transfers can only happen when the tranfer state is enabled. //Transfer state can only be enabled after the end of the crowdsale. ///@param _to The destination wallet address to transfer funds to. ///@param _value The amount of tokens to send to the destination address. function transfer(address _to, uint256 _value) public canTransfer(msg.sender) returns (bool) { require(_to != address(0)); return super.transfer(_to, _value); } ///@notice Transfers tokens from a specified wallet address. ///@dev This function is overriden to leverage transfer state feature. ///@param _from The address to transfer funds from. ///@param _to The address to transfer funds to. ///@param _value The amount of tokens to transfer. function transferFrom(address _from, address _to, uint256 _value) canTransfer(_from) public returns (bool) { require(_to != address(0)); return super.transferFrom(_from, _to, _value); } ///@notice Approves a wallet address to spend on behalf of the sender. ///@dev This function is overriden to leverage transfer state feature. ///@param _spender The address which is approved to spend on behalf of the sender. ///@param _value The amount of tokens approve to spend. function approve(address _spender, uint256 _value) public canTransfer(msg.sender) returns (bool) { require(_spender != address(0)); return super.approve(_spender, _value); } ///@notice Increases the approval of the spender. ///@dev This function is overriden to leverage transfer state feature. ///@param _spender The address which is approved to spend on behalf of the sender. ///@param _addedValue The added amount of tokens approved to spend. function increaseApproval(address _spender, uint256 _addedValue) public canTransfer(msg.sender) returns(bool) { require(_spender != address(0)); return super.increaseApproval(_spender, _addedValue); } ///@notice Decreases the approval of the spender. ///@dev This function is overriden to leverage transfer state feature. ///@param _spender The address of the spender to decrease the allocation from. ///@param _subtractedValue The amount of tokens to subtract from the approved allocation. function decreaseApproval(address _spender, uint256 _subtractedValue) public canTransfer(msg.sender) returns (bool) { require(_spender != address(0)); return super.decreaseApproval(_spender, _subtractedValue); } ///@notice Returns the sum of supplied values. ///@param _values The collection of values to create the sum from. function sumOf(uint256[] _values) private pure returns(uint256) { uint256 total = 0; for (uint256 i = 0; i < _values.length; i++) { total = total.add(_values[i]); } return total; } ///@notice Allows only the admins and/or whitelisted applications to perform bulk transfer operation. ///@param _destinations The destination wallet addresses to send funds to. ///@param _amounts The respective amount of fund to send to the specified addresses. function bulkTransfer(address[] _destinations, uint256[] _amounts) public onlyAdmin { require(_destinations.length == _amounts.length); //Saving gas by determining if the sender has enough balance //to post this transaction. uint256 requiredBalance = sumOf(_amounts); require(balances[msg.sender] >= requiredBalance); for (uint256 i = 0; i < _destinations.length; i++) { transfer(_destinations[i], _amounts[i]); } emit BulkTransferPerformed(_destinations, _amounts); } ///@notice Burns the coins held by the sender. ///@param _value The amount of coins to burn. ///@dev This function is overriden to leverage Pausable feature. function burn(uint256 _value) public whenNotPaused { super.burn(_value); } }
@notice Decreases the approval of the spender.@dev This function is overriden to leverage transfer state feature.@param _spender The address of the spender to decrease the allocation from.@param _subtractedValue The amount of tokens to subtract from the approved allocation.
function decreaseApproval(address _spender, uint256 _subtractedValue) public canTransfer(msg.sender) returns (bool) { require(_spender != address(0)); return super.decreaseApproval(_spender, _subtractedValue); }
5,525,067
[ 1, 23326, 3304, 326, 23556, 434, 326, 17571, 264, 18, 1220, 445, 353, 31736, 358, 884, 5682, 7412, 919, 2572, 18, 389, 87, 1302, 264, 1021, 1758, 434, 326, 17571, 264, 358, 20467, 326, 13481, 628, 18, 389, 1717, 1575, 329, 620, 1021, 3844, 434, 2430, 358, 10418, 628, 326, 20412, 13481, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 20467, 23461, 12, 2867, 389, 87, 1302, 264, 16, 2254, 5034, 389, 1717, 1575, 329, 620, 13, 1071, 848, 5912, 12, 3576, 18, 15330, 13, 1135, 261, 6430, 13, 288, 203, 565, 2583, 24899, 87, 1302, 264, 480, 1758, 12, 20, 10019, 203, 565, 327, 2240, 18, 323, 11908, 23461, 24899, 87, 1302, 264, 16, 389, 1717, 1575, 329, 620, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {BridgeRouter} from "./BridgeRouter.sol"; import {IWeth} from "../../interfaces/bridge/IWeth.sol"; // ============ External Imports ============ import {TypeCasts} from "@celo-org/optics-sol/contracts/XAppConnectionManager.sol"; contract ETHHelper { // ============ Immutables ============ // wrapped Ether contract IWeth public immutable weth; // bridge router contract BridgeRouter public immutable bridge; // ============ Constructor ============ constructor(address _weth, address _bridge) { weth = IWeth(_weth); bridge = BridgeRouter(_bridge); IWeth(_weth).approve(_bridge, uint256(-1)); } // ============ External Functions ============ /** * @notice Sends ETH over the Optics Bridge. Sends to a full-width Optics * identifer on the other side. * @dev As with all bridges, improper use may result in loss of funds. * @param _domain The domain to send funds to. * @param _to The 32-byte identifier of the recipient */ function sendTo(uint32 _domain, bytes32 _to) public payable { weth.deposit{value: msg.value}(); bridge.send(address(weth), msg.value, _domain, _to); } /** * @notice Sends ETH over the Optics Bridge. Sends to the same address on * the other side. * @dev WARNING: This function should only be used when sending TO an * EVM-like domain. As with all bridges, improper use may result in loss of * funds. * @param _domain The domain to send funds to */ function send(uint32 _domain) external payable { sendTo(_domain, TypeCasts.addressToBytes32(msg.sender)); } /** * @notice Sends ETH over the Optics Bridge. Sends to a specified EVM * address on the other side. * @dev This function should only be used when sending TO an EVM-like * domain. As with all bridges, improper use may result in loss of funds * @param _domain The domain to send funds to. * @param _to The EVM address of the recipient */ function sendToEVMLike(uint32 _domain, address _to) external payable { sendTo(_domain, TypeCasts.addressToBytes32(_to)); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {TokenRegistry} from "./TokenRegistry.sol"; import {Router} from "../Router.sol"; import {XAppConnectionClient} from "../XAppConnectionClient.sol"; import {IBridgeToken} from "../../interfaces/bridge/IBridgeToken.sol"; import {BridgeMessage} from "./BridgeMessage.sol"; // ============ External Imports ============ import {Home} from "@celo-org/optics-sol/contracts/Home.sol"; import {Version0} from "@celo-org/optics-sol/contracts/Version0.sol"; import {TypeCasts} from "@celo-org/optics-sol/contracts/XAppConnectionManager.sol"; import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title BridgeRouter */ contract BridgeRouter is Version0, Router, TokenRegistry { // ============ Libraries ============ using TypedMemView for bytes; using TypedMemView for bytes29; using BridgeMessage for bytes29; using SafeERC20 for IERC20; // ============ Constants ============ // 5 bps (0.05%) hardcoded fast liquidity fee. Can be changed by contract upgrade uint256 public constant PRE_FILL_FEE_NUMERATOR = 9995; uint256 public constant PRE_FILL_FEE_DENOMINATOR = 10000; // ============ Public Storage ============ // token transfer prefill ID => LP that pre-filled message to provide fast liquidity mapping(bytes32 => address) public liquidityProvider; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[49] private __GAP; // ======== Events ========= /** * @notice emitted when tokens are sent from this domain to another domain * @param token the address of the token contract * @param from the address sending tokens * @param toDomain the domain of the chain the tokens are being sent to * @param toId the bytes32 address of the recipient of the tokens * @param amount the amount of tokens sent */ event Send( address indexed token, address indexed from, uint32 indexed toDomain, bytes32 toId, uint256 amount ); // ======== Initializer ======== function initialize(address _tokenBeacon, address _xAppConnectionManager) public initializer { __TokenRegistry_initialize(_tokenBeacon); __XAppConnectionClient_initialize(_xAppConnectionManager); } // ======== External: Handle ========= /** * @notice Handles an incoming message * @param _origin The origin domain * @param _sender The sender address * @param _message The message */ function handle( uint32 _origin, bytes32 _sender, bytes memory _message ) external override onlyReplica onlyRemoteRouter(_origin, _sender) { // parse tokenId and action from message bytes29 _msg = _message.ref(0).mustBeMessage(); bytes29 _tokenId = _msg.tokenId(); bytes29 _action = _msg.action(); // handle message based on the intended action if (_action.isTransfer()) { _handleTransfer(_tokenId, _action); } else if (_action.isDetails()) { _handleDetails(_tokenId, _action); } else if (_action.isRequestDetails()) { _handleRequestDetails(_origin, _sender, _tokenId); } else { require(false, "!valid action"); } } // ======== External: Request Token Details ========= /** * @notice Request updated token metadata from another chain * @dev This is only owner to prevent abuse and spam. Requesting details * should be done automatically on token instantiation * @param _domain The domain where that token is native * @param _id The token id on that domain */ function requestDetails(uint32 _domain, bytes32 _id) external onlyOwner { bytes29 _tokenId = BridgeMessage.formatTokenId(_domain, _id); _requestDetails(_tokenId); } // ======== External: Send Token ========= /** * @notice Send tokens to a recipient on a remote chain * @param _token The token address * @param _amount The token amount * @param _destination The destination domain * @param _recipient The recipient address */ function send( address _token, uint256 _amount, uint32 _destination, bytes32 _recipient ) external { require(_amount > 0, "!amnt"); require(_recipient != bytes32(0), "!recip"); // get remote BridgeRouter address; revert if not found bytes32 _remote = _mustHaveRemote(_destination); // remove tokens from circulation on this chain IERC20 _bridgeToken = IERC20(_token); if (_isLocalOrigin(_bridgeToken)) { // if the token originates on this chain, hold the tokens in escrow // in the Router _bridgeToken.safeTransferFrom(msg.sender, address(this), _amount); } else { // if the token originates on a remote chain, burn the // representation tokens on this chain _downcast(_bridgeToken).burn(msg.sender, _amount); } // format Transfer Tokens action bytes29 _action = BridgeMessage.formatTransfer(_recipient, _amount); // send message to remote chain via Optics Home(xAppConnectionManager.home()).dispatch( _destination, _remote, BridgeMessage.formatMessage(_formatTokenId(_token), _action) ); // emit Send event to record token sender emit Send( address(_bridgeToken), msg.sender, _destination, _recipient, _amount ); } // ======== External: Fast Liquidity ========= /** * @notice Allows a liquidity provider to give an * end user fast liquidity by pre-filling an * incoming transfer message. * Transfers tokens from the liquidity provider to the end recipient, minus the LP fee; * Records the liquidity provider, who receives * the full token amount when the transfer message is handled. * @dev fast liquidity can only be provided for ONE token transfer * with the same (recipient, amount) at a time. * in the case that multiple token transfers with the same (recipient, amount) * @param _message The incoming transfer message to pre-fill */ function preFill(bytes calldata _message) external { // parse tokenId and action from message bytes29 _msg = _message.ref(0).mustBeMessage(); bytes29 _tokenId = _msg.tokenId().mustBeTokenId(); bytes29 _action = _msg.action().mustBeTransfer(); // calculate prefill ID bytes32 _id = _preFillId(_tokenId, _action); // require that transfer has not already been pre-filled require(liquidityProvider[_id] == address(0), "!unfilled"); // record liquidity provider liquidityProvider[_id] = msg.sender; // transfer tokens from liquidity provider to token recipient IERC20 _token = _mustHaveToken(_tokenId); _token.safeTransferFrom( msg.sender, _action.evmRecipient(), _applyPreFillFee(_action.amnt()) ); } // ======== External: Custom Tokens ========= /** * @notice Enroll a custom token. This allows projects to work with * governance to specify a custom representation. * @dev This is done by inserting the custom representation into the token * lookup tables. It is permissioned to the owner (governance) and can * potentially break token representations. It must be used with extreme * caution. * After the token is inserted, new mint instructions will be sent to the * custom token. The default representation (and old custom representations) * may still be burnt. Until all users have explicitly called migrate, both * representations will continue to exist. * The custom representation MUST be trusted, and MUST allow the router to * both mint AND burn tokens at will. * @param _id the canonical ID of the Token to enroll, as a byte vector * @param _custom the address of the custom implementation to use. */ function enrollCustom( uint32 _domain, bytes32 _id, address _custom ) external onlyOwner { // Sanity check. Ensures that human error doesn't cause an // unpermissioned contract to be enrolled. IBridgeToken(_custom).mint(address(this), 1); IBridgeToken(_custom).burn(address(this), 1); // update mappings with custom token bytes29 _tokenId = BridgeMessage.formatTokenId(_domain, _id); representationToCanonical[_custom].domain = _tokenId.domain(); representationToCanonical[_custom].id = _tokenId.id(); bytes32 _idHash = _tokenId.keccak(); canonicalToRepresentation[_idHash] = _custom; } /** * @notice Migrate all tokens in a previous representation to the latest * custom representation. This works by looking up local mappings and then * burning old tokens and minting new tokens. * @dev This is explicitly opt-in to allow dapps to decide when and how to * upgrade to the new representation. * @param _oldRepr The address of the old token to migrate */ function migrate(address _oldRepr) external { // get the token ID for the old token contract TokenId memory _id = representationToCanonical[_oldRepr]; require(_id.domain != 0, "!repr"); // ensure that new token & old token are different IBridgeToken _old = IBridgeToken(_oldRepr); IBridgeToken _new = _representationForCanonical(_id); require(_new != _old, "!different"); // burn the old tokens & mint the new ones uint256 _bal = _old.balanceOf(msg.sender); _old.burn(msg.sender, _bal); _new.mint(msg.sender, _bal); } // ============ Internal: Send / UpdateDetails ============ /** * @notice Given a tokenAddress, format the tokenId * identifier for the message. * @param _token The token address * @param _tokenId The bytes-encoded tokenId */ function _formatTokenId(address _token) internal view returns (bytes29 _tokenId) { TokenId memory _tokId = _tokenIdFor(_token); _tokenId = BridgeMessage.formatTokenId(_tokId.domain, _tokId.id); } // ============ Internal: Handle ============ /** * @notice Handles an incoming Transfer message. * * If the token is of local origin, the amount is sent from escrow. * Otherwise, a representation token is minted. * * @param _tokenId The token ID * @param _action The action */ function _handleTransfer(bytes29 _tokenId, bytes29 _action) internal { // get the token contract for the given tokenId on this chain; // (if the token is of remote origin and there is // no existing representation token contract, the TokenRegistry will // deploy a new one) IERC20 _token = _ensureToken(_tokenId); address _recipient = _action.evmRecipient(); // If an LP has prefilled this token transfer, // send the tokens to the LP instead of the recipient bytes32 _id = _preFillId(_tokenId, _action); address _lp = liquidityProvider[_id]; if (_lp != address(0)) { _recipient = _lp; delete liquidityProvider[_id]; } // send the tokens into circulation on this chain if (_isLocalOrigin(_token)) { // if the token is of local origin, the tokens have been held in // escrow in this contract // while they have been circulating on remote chains; // transfer the tokens to the recipient _token.safeTransfer(_recipient, _action.amnt()); } else { // if the token is of remote origin, mint the tokens to the // recipient on this chain _downcast(_token).mint(_recipient, _action.amnt()); } } /** * @notice Handles an incoming Details message. * @param _tokenId The token ID * @param _action The action */ function _handleDetails(bytes29 _tokenId, bytes29 _action) internal { // get the token contract deployed on this chain // revert if no token contract exists IERC20 _token = _mustHaveToken(_tokenId); // require that the token is of remote origin // (otherwise, the BridgeRouter did not deploy the token contract, // and therefore cannot update its metadata) require(!_isLocalOrigin(_token), "!remote origin"); // update the token metadata _downcast(_token).setDetails( TypeCasts.coerceString(_action.name()), TypeCasts.coerceString(_action.symbol()), _action.decimals() ); } /** * @notice Handles an incoming RequestDetails message by sending an * UpdateDetails message to the remote chain * @dev The origin and remote are pre-checked by the handle function * `onlyRemoteRouter` modifier and can be used without additional check * @param _messageOrigin The domain from which the message arrived * @param _messageRemoteRouter The remote router that sent the message * @param _tokenId The token ID */ function _handleRequestDetails( uint32 _messageOrigin, bytes32 _messageRemoteRouter, bytes29 _tokenId ) internal { // get token & ensure is of local origin address _token = _tokenId.evmId(); require(_isLocalOrigin(_token), "!local origin"); IBridgeToken _bridgeToken = IBridgeToken(_token); // format Update Details message bytes29 _updateDetailsAction = BridgeMessage.formatDetails( TypeCasts.coerceBytes32(_bridgeToken.name()), TypeCasts.coerceBytes32(_bridgeToken.symbol()), _bridgeToken.decimals() ); // send message to remote chain via Optics Home(xAppConnectionManager.home()).dispatch( _messageOrigin, _messageRemoteRouter, BridgeMessage.formatMessage(_tokenId, _updateDetailsAction) ); } // ============ Internal: Transfer ============ function _ensureToken(bytes29 _tokenId) internal returns (IERC20) { address _local = _getTokenAddress(_tokenId); if (_local == address(0)) { // Representation does not exist yet; // deploy representation contract _local = _deployToken(_tokenId); // message the origin domain // to request the token details _requestDetails(_tokenId); } return IERC20(_local); } // ============ Internal: Request Details ============ /** * @notice Handles an incoming Details message. * @param _tokenId The token ID */ function _requestDetails(bytes29 _tokenId) internal { uint32 _destination = _tokenId.domain(); // get remote BridgeRouter address; revert if not found bytes32 _remote = remotes[_destination]; if (_remote == bytes32(0)) { return; } // format Request Details message bytes29 _action = BridgeMessage.formatRequestDetails(); // send message to remote chain via Optics Home(xAppConnectionManager.home()).dispatch( _destination, _remote, BridgeMessage.formatMessage(_tokenId, _action) ); } // ============ Internal: Fast Liquidity ============ /** * @notice Calculate the token amount after * taking a 5 bps (0.05%) liquidity provider fee * @param _amnt The token amount before the fee is taken * @return _amtAfterFee The token amount after the fee is taken */ function _applyPreFillFee(uint256 _amnt) internal pure returns (uint256 _amtAfterFee) { // overflow only possible if (2**256 / 9995) tokens sent once // in which case, probably not a real token _amtAfterFee = (_amnt * PRE_FILL_FEE_NUMERATOR) / PRE_FILL_FEE_DENOMINATOR; } /** * @notice get the prefillId used to identify * fast liquidity provision for incoming token send messages * @dev used to identify a token/transfer pair in the prefill LP mapping. * NOTE: This approach has a weakness: a user can receive >1 batch of tokens of * the same size, but only 1 will be eligible for fast liquidity. The * other may only be filled at regular speed. This is because the messages * will have identical `tokenId` and `action` fields. This seems fine, * tbqh. A delay of a few hours on a corner case is acceptable in v1. * @param _tokenId The token ID * @param _action The action */ function _preFillId(bytes29 _tokenId, bytes29 _action) internal view returns (bytes32) { bytes29[] memory _views = new bytes29[](2); _views[0] = _tokenId; _views[1] = _action; return TypedMemView.joinKeccak(_views); } /** * @dev explicit override for compiler inheritance * @dev explicit override for compiler inheritance * @return domain of chain on which the contract is deployed */ function _localDomain() internal view override(TokenRegistry, XAppConnectionClient) returns (uint32) { return XAppConnectionClient._localDomain(); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; interface IWeth { function deposit() external payable; function approve(address _who, uint256 _wad) external; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Home} from "./Home.sol"; import {Replica} from "./Replica.sol"; import {TypeCasts} from "../libs/TypeCasts.sol"; // ============ External Imports ============ import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; /** * @title XAppConnectionManager * @author Celo Labs Inc. * @notice Manages a registry of local Replica contracts * for remote Home domains. Accepts Watcher signatures * to un-enroll Replicas attached to fraudulent remote Homes */ contract XAppConnectionManager is Ownable { // ============ Public Storage ============ // Home contract Home public home; // local Replica address => remote Home domain mapping(address => uint32) public replicaToDomain; // remote Home domain => local Replica address mapping(uint32 => address) public domainToReplica; // watcher address => replica remote domain => has/doesn't have permission mapping(address => mapping(uint32 => bool)) private watcherPermissions; // ============ Events ============ /** * @notice Emitted when a new Replica is enrolled / added * @param domain the remote domain of the Home contract for the Replica * @param replica the address of the Replica */ event ReplicaEnrolled(uint32 indexed domain, address replica); /** * @notice Emitted when a new Replica is un-enrolled / removed * @param domain the remote domain of the Home contract for the Replica * @param replica the address of the Replica */ event ReplicaUnenrolled(uint32 indexed domain, address replica); /** * @notice Emitted when Watcher permissions are changed * @param domain the remote domain of the Home contract for the Replica * @param watcher the address of the Watcher * @param access TRUE if the Watcher was given permissions, FALSE if permissions were removed */ event WatcherPermissionSet( uint32 indexed domain, address watcher, bool access ); // ============ Modifiers ============ modifier onlyReplica() { require(isReplica(msg.sender), "!replica"); _; } // ============ Constructor ============ // solhint-disable-next-line no-empty-blocks constructor() Ownable() {} // ============ External Functions ============ /** * @notice Un-Enroll a replica contract * in the case that fraud was detected on the Home * @dev in the future, if fraud occurs on the Home contract, * the Watcher will submit their signature directly to the Home * and it can be relayed to all remote chains to un-enroll the Replicas * @param _domain the remote domain of the Home contract for the Replica * @param _updater the address of the Updater for the Home contract (also stored on Replica) * @param _signature signature of watcher on (domain, replica address, updater address) */ function unenrollReplica( uint32 _domain, bytes32 _updater, bytes memory _signature ) external { // ensure that the replica is currently set address _replica = domainToReplica[_domain]; require(_replica != address(0), "!replica exists"); // ensure that the signature is on the proper updater require( Replica(_replica).updater() == TypeCasts.bytes32ToAddress(_updater), "!current updater" ); // get the watcher address from the signature // and ensure that the watcher has permission to un-enroll this replica address _watcher = _recoverWatcherFromSig( _domain, TypeCasts.addressToBytes32(_replica), _updater, _signature ); require(watcherPermissions[_watcher][_domain], "!valid watcher"); // remove the replica from mappings _unenrollReplica(_replica); } /** * @notice Set the address of the local Home contract * @param _home the address of the local Home contract */ function setHome(address _home) external onlyOwner { home = Home(_home); } /** * @notice Allow Owner to enroll Replica contract * @param _replica the address of the Replica * @param _domain the remote domain of the Home contract for the Replica */ function ownerEnrollReplica(address _replica, uint32 _domain) external onlyOwner { // un-enroll any existing replica _unenrollReplica(_replica); // add replica and domain to two-way mapping replicaToDomain[_replica] = _domain; domainToReplica[_domain] = _replica; emit ReplicaEnrolled(_domain, _replica); } /** * @notice Allow Owner to un-enroll Replica contract * @param _replica the address of the Replica */ function ownerUnenrollReplica(address _replica) external onlyOwner { _unenrollReplica(_replica); } /** * @notice Allow Owner to set Watcher permissions for a Replica * @param _watcher the address of the Watcher * @param _domain the remote domain of the Home contract for the Replica * @param _access TRUE to give the Watcher permissions, FALSE to remove permissions */ function setWatcherPermission( address _watcher, uint32 _domain, bool _access ) external onlyOwner { watcherPermissions[_watcher][_domain] = _access; emit WatcherPermissionSet(_domain, _watcher, _access); } /** * @notice Query local domain from Home * @return local domain */ function localDomain() external view returns (uint32) { return home.localDomain(); } /** * @notice Get access permissions for the watcher on the domain * @param _watcher the address of the watcher * @param _domain the domain to check for watcher permissions * @return TRUE iff _watcher has permission to un-enroll replicas on _domain */ function watcherPermission(address _watcher, uint32 _domain) external view returns (bool) { return watcherPermissions[_watcher][_domain]; } // ============ Public Functions ============ /** * @notice Check whether _replica is enrolled * @param _replica the replica to check for enrollment * @return TRUE iff _replica is enrolled */ function isReplica(address _replica) public view returns (bool) { return replicaToDomain[_replica] != 0; } // ============ Internal Functions ============ /** * @notice Remove the replica from the two-way mappings * @param _replica replica to un-enroll */ function _unenrollReplica(address _replica) internal { uint32 _currentDomain = replicaToDomain[_replica]; domainToReplica[_currentDomain] = address(0); replicaToDomain[_replica] = 0; emit ReplicaUnenrolled(_currentDomain, _replica); } /** * @notice Get the Watcher address from the provided signature * @return address of watcher that signed */ function _recoverWatcherFromSig( uint32 _domain, bytes32 _replica, bytes32 _updater, bytes memory _signature ) internal view returns (address) { bytes32 _homeDomainHash = Replica(TypeCasts.bytes32ToAddress(_replica)) .homeDomainHash(); bytes32 _digest = keccak256( abi.encodePacked(_homeDomainHash, _domain, _updater) ); _digest = ECDSA.toEthSignedMessageHash(_digest); return ECDSA.recover(_digest, _signature); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {BridgeMessage} from "./BridgeMessage.sol"; import {Encoding} from "./Encoding.sol"; import {IBridgeToken} from "../../interfaces/bridge/IBridgeToken.sol"; import {XAppConnectionClient} from "../XAppConnectionClient.sol"; // ============ External Imports ============ import {TypeCasts} from "@celo-org/optics-sol/contracts/XAppConnectionManager.sol"; import {UpgradeBeaconProxy} from "@celo-org/optics-sol/contracts/upgrade/UpgradeBeaconProxy.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol"; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title TokenRegistry * @notice manages a registry of token contracts on this chain * - * We sort token types as "representation token" or "locally originating token". * Locally originating - a token contract that was originally deployed on the local chain * Representation (repr) - a token that was originally deployed on some other chain * - * When the router handles an incoming message, it determines whether the * transfer is for an asset of local origin. If not, it checks for an existing * representation contract. If no such representation exists, it deploys a new * representation contract. It then stores the relationship in the * "reprToCanonical" and "canonicalToRepr" mappings to ensure we can always * perform a lookup in either direction * Note that locally originating tokens should NEVER be represented in these lookup tables. */ abstract contract TokenRegistry is Initializable { // ============ Libraries ============ using TypedMemView for bytes; using TypedMemView for bytes29; using BridgeMessage for bytes29; // ============ Structs ============ // Tokens are identified by a TokenId: // domain - 4 byte chain ID of the chain from which the token originates // id - 32 byte identifier of the token address on the origin chain, in that chain's address format struct TokenId { uint32 domain; bytes32 id; } // ============ Public Storage ============ // UpgradeBeacon from which new token proxies will get their implementation address public tokenBeacon; // local representation token address => token ID mapping(address => TokenId) public representationToCanonical; // hash of the tightly-packed TokenId => local representation token address // If the token is of local origin, this MUST map to address(0). mapping(bytes32 => address) public canonicalToRepresentation; // ============ Events ============ event TokenDeployed( uint32 indexed domain, bytes32 indexed id, address indexed representation ); // ======== Initializer ========= /** * @notice Initialize the TokenRegistry with UpgradeBeaconController and * XappConnectionManager. * @dev This method deploys two new contracts, and may be expensive to call. * @param _tokenBeacon The address of the upgrade beacon for bridge token * proxies */ function __TokenRegistry_initialize(address _tokenBeacon) internal initializer { tokenBeacon = _tokenBeacon; } // ======== External: Token Lookup Convenience ========= /** * @notice Looks up the canonical identifier for a local representation. * @dev If no such canonical ID is known, this instead returns (0, bytes32(0)) * @param _local The local address of the representation */ function getCanonicalAddress(address _local) external view returns (uint32 _domain, bytes32 _id) { TokenId memory _canonical = representationToCanonical[_local]; _domain = _canonical.domain; _id = _canonical.id; } /** * @notice Looks up the local address corresponding to a domain/id pair. * @dev If the token is local, it will return the local address. * If the token is non-local and no local representation exists, this * will return `address(0)`. * @param _domain the domain of the canonical version. * @param _id the identifier of the canonical version in its domain. * @return _token the local address of the token contract */ function getLocalAddress(uint32 _domain, address _id) external view returns (address _token) { _token = getLocalAddress(_domain, TypeCasts.addressToBytes32(_id)); } // ======== Public: Token Lookup Convenience ========= /** * @notice Looks up the local address corresponding to a domain/id pair. * @dev If the token is local, it will return the local address. * If the token is non-local and no local representation exists, this * will return `address(0)`. * @param _domain the domain of the canonical version. * @param _id the identifier of the canonical version in its domain. * @return _token the local address of the token contract */ function getLocalAddress(uint32 _domain, bytes32 _id) public view returns (address _token) { _token = _getTokenAddress(BridgeMessage.formatTokenId(_domain, _id)); } // ======== Internal Functions ========= function _localDomain() internal view virtual returns (uint32); /** * @notice Get default name and details for a token * Sets name to "optics.[domain].[id]" * and symbol to * @param _tokenId the tokenId for the token */ function _defaultDetails(bytes29 _tokenId) internal pure returns (string memory _name, string memory _symbol) { // get the first and second half of the token ID (, uint256 _secondHalfId) = Encoding.encodeHex(uint256(_tokenId.id())); // encode the default token name: "[decimal domain].[hex 4 bytes of ID]" _name = string( abi.encodePacked( Encoding.decimalUint32(_tokenId.domain()), // 10 ".", // 1 uint32(_secondHalfId) // 4 ) ); // allocate the memory for a new 32-byte string _symbol = new string(10 + 1 + 4); assembly { mstore(add(_symbol, 0x20), mload(add(_name, 0x20))) } } /** * @notice Deploy and initialize a new token contract * @dev Each token contract is a proxy which * points to the token upgrade beacon * @return _token the address of the token contract */ function _deployToken(bytes29 _tokenId) internal returns (address _token) { // deploy and initialize the token contract _token = address(new UpgradeBeaconProxy(tokenBeacon, "")); // initialize the token separately from the IBridgeToken(_token).initialize(); // set the default token name & symbol string memory _name; string memory _symbol; (_name, _symbol) = _defaultDetails(_tokenId); IBridgeToken(_token).setDetails(_name, _symbol, 18); // store token in mappings representationToCanonical[_token].domain = _tokenId.domain(); representationToCanonical[_token].id = _tokenId.id(); canonicalToRepresentation[_tokenId.keccak()] = _token; // emit event upon deploying new token emit TokenDeployed(_tokenId.domain(), _tokenId.id(), _token); } /** * @notice Get the local token address * for the canonical token represented by tokenID * Returns address(0) if canonical token is of remote origin * and no representation token has been deployed locally * @param _tokenId the token id of the canonical token * @return _local the local token address */ function _getTokenAddress(bytes29 _tokenId) internal view returns (address _local) { if (_tokenId.domain() == _localDomain()) { // Token is of local origin _local = _tokenId.evmId(); } else { // Token is a representation of a token of remote origin _local = canonicalToRepresentation[_tokenId.keccak()]; } } /** * @notice Return the local token contract for the * canonical tokenId; revert if there is no local token * @param _tokenId the token id of the canonical token * @return the IERC20 token contract */ function _mustHaveToken(bytes29 _tokenId) internal view returns (IERC20) { address _local = _getTokenAddress(_tokenId); require(_local != address(0), "!token"); return IERC20(_local); } /** * @notice Return tokenId for a local token address * @param _token local token address (representation or canonical) * @return _id local token address (representation or canonical) */ function _tokenIdFor(address _token) internal view returns (TokenId memory _id) { _id = representationToCanonical[_token]; if (_id.domain == 0) { _id.domain = _localDomain(); _id.id = TypeCasts.addressToBytes32(_token); } } /** * @notice Determine if token is of local origin * @return TRUE if token is locally originating */ function _isLocalOrigin(IERC20 _token) internal view returns (bool) { return _isLocalOrigin(address(_token)); } /** * @notice Determine if token is of local origin * @return TRUE if token is locally originating */ function _isLocalOrigin(address _token) internal view returns (bool) { // If the contract WAS deployed by the TokenRegistry, // it will be stored in this mapping. // If so, it IS NOT of local origin if (representationToCanonical[_token].domain != 0) { return false; } // If the contract WAS NOT deployed by the TokenRegistry, // and the contract exists, then it IS of local origin // Return true if code exists at _addr uint256 _codeSize; // solhint-disable-next-line no-inline-assembly assembly { _codeSize := extcodesize(_token) } return _codeSize != 0; } /** * @notice Get the local representation contract for a canonical token * @dev Returns contract with null address if tokenId has no representation * @param _tokenId the tokenId of the canonical token * @return representation token contract */ function _representationForCanonical(bytes29 _tokenId) internal view returns (IBridgeToken) { return IBridgeToken(canonicalToRepresentation[_tokenId.keccak()]); } /** * @notice Get the local representation contract for a canonical token * @dev Returns contract with null address if tokenId has no representation * @param _tokenId the tokenId of the canonical token * @return representation token contract */ function _representationForCanonical(TokenId memory _tokenId) internal view returns (IBridgeToken) { return _representationForCanonical(_serializeId(_tokenId)); } /** * @notice downcast an IERC20 to an IBridgeToken * @dev Unsafe. Please know what you're doing * @param _token the IERC20 contract * @return the IBridgeToken contract */ function _downcast(IERC20 _token) internal pure returns (IBridgeToken) { return IBridgeToken(address(_token)); } /** * @notice serialize a TokenId struct into a bytes view * @param _id the tokenId * @return serialized bytes of tokenId */ function _serializeId(TokenId memory _id) internal pure returns (bytes29) { return BridgeMessage.formatTokenId(_id.domain, _id.id); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {XAppConnectionClient} from "./XAppConnectionClient.sol"; // ============ External Imports ============ import {IMessageRecipient} from "@celo-org/optics-sol/interfaces/IMessageRecipient.sol"; abstract contract Router is XAppConnectionClient, IMessageRecipient { // ============ Mutable Storage ============ mapping(uint32 => bytes32) public remotes; uint256[49] private __GAP; // gap for upgrade safety // ============ Modifiers ============ /** * @notice Only accept messages from a remote Router contract * @param _origin The domain the message is coming from * @param _router The address the message is coming from */ modifier onlyRemoteRouter(uint32 _origin, bytes32 _router) { require(_isRemoteRouter(_origin, _router), "!remote router"); _; } // ============ External functions ============ /** * @notice Register the address of a Router contract for the same xApp on a remote chain * @param _domain The domain of the remote xApp Router * @param _router The address of the remote xApp Router */ function enrollRemoteRouter(uint32 _domain, bytes32 _router) external onlyOwner { remotes[_domain] = _router; } // ============ Virtual functions ============ function handle( uint32 _origin, bytes32 _sender, bytes memory _message ) external virtual override; // ============ Internal functions ============ /** * @notice Return true if the given domain / router is the address of a remote xApp Router * @param _domain The domain of the potential remote xApp Router * @param _router The address of the potential remote xApp Router */ function _isRemoteRouter(uint32 _domain, bytes32 _router) internal view returns (bool) { return remotes[_domain] == _router; } /** * @notice Assert that the given domain has a xApp Router registered and return its address * @param _domain The domain of the chain for which to get the xApp Router * @return _remote The address of the remote xApp Router on _domain */ function _mustHaveRemote(uint32 _domain) internal view returns (bytes32 _remote) { _remote = remotes[_domain]; require(_remote != bytes32(0), "!remote"); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ External Imports ============ import {Home} from "@celo-org/optics-sol/contracts/Home.sol"; import {XAppConnectionManager} from "@celo-org/optics-sol/contracts/XAppConnectionManager.sol"; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; abstract contract XAppConnectionClient is OwnableUpgradeable { // ============ Mutable Storage ============ XAppConnectionManager public xAppConnectionManager; uint256[49] private __GAP; // gap for upgrade safety // ============ Modifiers ============ /** * @notice Only accept messages from an Optics Replica contract */ modifier onlyReplica() { require(_isReplica(msg.sender), "!replica"); _; } // ======== Initializer ========= function __XAppConnectionClient_initialize(address _xAppConnectionManager) internal initializer { xAppConnectionManager = XAppConnectionManager(_xAppConnectionManager); __Ownable_init(); } // ============ External functions ============ /** * @notice Modify the contract the xApp uses to validate Replica contracts * @param _xAppConnectionManager The address of the xAppConnectionManager contract */ function setXAppConnectionManager(address _xAppConnectionManager) external onlyOwner { xAppConnectionManager = XAppConnectionManager(_xAppConnectionManager); } // ============ Internal functions ============ /** * @notice Get the local Home contract from the xAppConnectionManager * @return The local Home contract */ function _home() internal view returns (Home) { return xAppConnectionManager.home(); } /** * @notice Determine whether _potentialReplcia is an enrolled Replica from the xAppConnectionManager * @return True if _potentialReplica is an enrolled Replica */ function _isReplica(address _potentialReplica) internal view returns (bool) { return xAppConnectionManager.isReplica(_potentialReplica); } /** * @notice Get the local domain from the xAppConnectionManager * @return The local domain */ function _localDomain() internal view virtual returns (uint32) { return xAppConnectionManager.localDomain(); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; interface IBridgeToken { function initialize() external; function name() external returns (string memory); function balanceOf(address _account) external view returns (uint256); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function burn(address _from, uint256 _amnt) external; function mint(address _to, uint256 _amnt) external; function setDetails( string calldata _name, string calldata _symbol, uint8 _decimals ) external; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ External Imports ============ import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol"; library BridgeMessage { // ============ Libraries ============ using TypedMemView for bytes; using TypedMemView for bytes29; // ============ Enums ============ // WARNING: do NOT re-write the numbers / order // of message types in an upgrade; // will cause in-flight messages to be mis-interpreted enum Types { Invalid, // 0 TokenId, // 1 Message, // 2 Transfer, // 3 Details, // 4 RequestDetails // 5 } // ============ Constants ============ uint256 private constant TOKEN_ID_LEN = 36; // 4 bytes domain + 32 bytes id uint256 private constant IDENTIFIER_LEN = 1; uint256 private constant TRANSFER_LEN = 65; // 1 byte identifier + 32 bytes recipient + 32 bytes amount uint256 private constant DETAILS_LEN = 66; // 1 byte identifier + 32 bytes name + 32 bytes symbol + 1 byte decimals uint256 private constant REQUEST_DETAILS_LEN = 1; // 1 byte identifier // ============ Modifiers ============ /** * @notice Asserts a message is of type `_t` * @param _view The message * @param _t The expected type */ modifier typeAssert(bytes29 _view, Types _t) { _view.assertType(uint40(_t)); _; } // ============ Internal Functions ============ /** * @notice Checks that Action is valid type * @param _action The action * @return TRUE if action is valid */ function isValidAction(bytes29 _action) internal pure returns (bool) { return isDetails(_action) || isRequestDetails(_action) || isTransfer(_action); } /** * @notice Checks that view is a valid message length * @param _view The bytes string * @return TRUE if message is valid */ function isValidMessageLength(bytes29 _view) internal pure returns (bool) { uint256 _len = _view.len(); return _len == TOKEN_ID_LEN + TRANSFER_LEN || _len == TOKEN_ID_LEN + DETAILS_LEN || _len == TOKEN_ID_LEN + REQUEST_DETAILS_LEN; } /** * @notice Formats an action message * @param _tokenId The token ID * @param _action The action * @return The formatted message */ function formatMessage(bytes29 _tokenId, bytes29 _action) internal view typeAssert(_tokenId, Types.TokenId) returns (bytes memory) { require(isValidAction(_action), "!action"); bytes29[] memory _views = new bytes29[](2); _views[0] = _tokenId; _views[1] = _action; return TypedMemView.join(_views); } /** * @notice Returns the type of the message * @param _view The message * @return The type of the message */ function messageType(bytes29 _view) internal pure returns (Types) { return Types(uint8(_view.typeOf())); } /** * @notice Checks that the message is of type Transfer * @param _action The message * @return True if the message is of type Transfer */ function isTransfer(bytes29 _action) internal pure returns (bool) { return actionType(_action) == uint8(Types.Transfer) && messageType(_action) == Types.Transfer; } /** * @notice Checks that the message is of type Details * @param _action The message * @return True if the message is of type Details */ function isDetails(bytes29 _action) internal pure returns (bool) { return actionType(_action) == uint8(Types.Details) && messageType(_action) == Types.Details; } /** * @notice Checks that the message is of type Details * @param _action The message * @return True if the message is of type Details */ function isRequestDetails(bytes29 _action) internal pure returns (bool) { return actionType(_action) == uint8(Types.RequestDetails) && messageType(_action) == Types.RequestDetails; } /** * @notice Formats Transfer * @param _to The recipient address as bytes32 * @param _amnt The transfer amount * @return */ function formatTransfer(bytes32 _to, uint256 _amnt) internal pure returns (bytes29) { return mustBeTransfer(abi.encodePacked(Types.Transfer, _to, _amnt).ref(0)); } /** * @notice Formats Details * @param _name The name * @param _symbol The symbol * @param _decimals The decimals * @return The Details message */ function formatDetails( bytes32 _name, bytes32 _symbol, uint8 _decimals ) internal pure returns (bytes29) { return mustBeDetails( abi.encodePacked(Types.Details, _name, _symbol, _decimals).ref( 0 ) ); } /** * @notice Formats Request Details * @return The Request Details message */ function formatRequestDetails() internal pure returns (bytes29) { return mustBeRequestDetails(abi.encodePacked(Types.RequestDetails).ref(0)); } /** * @notice Formats the Token ID * @param _domain The domain * @param _id The ID * @return The formatted Token ID */ function formatTokenId(uint32 _domain, bytes32 _id) internal pure returns (bytes29) { return mustBeTokenId(abi.encodePacked(_domain, _id).ref(0)); } /** * @notice Retrieves the domain from a TokenID * @param _tokenId The message * @return The domain */ function domain(bytes29 _tokenId) internal pure typeAssert(_tokenId, Types.TokenId) returns (uint32) { return uint32(_tokenId.indexUint(0, 4)); } /** * @notice Retrieves the ID from a TokenID * @param _tokenId The message * @return The ID */ function id(bytes29 _tokenId) internal pure typeAssert(_tokenId, Types.TokenId) returns (bytes32) { // before = 4 bytes domain return _tokenId.index(4, 32); } /** * @notice Retrieves the EVM ID * @param _tokenId The message * @return The EVM ID */ function evmId(bytes29 _tokenId) internal pure typeAssert(_tokenId, Types.TokenId) returns (address) { // before = 4 bytes domain + 12 bytes empty to trim for address return _tokenId.indexAddress(16); } /** * @notice Retrieves the action identifier from message * @param _message The action * @return The message type */ function msgType(bytes29 _message) internal pure returns (uint8) { return uint8(_message.indexUint(TOKEN_ID_LEN, 1)); } /** * @notice Retrieves the identifier from action * @param _action The action * @return The action type */ function actionType(bytes29 _action) internal pure returns (uint8) { return uint8(_action.indexUint(0, 1)); } /** * @notice Retrieves the recipient from a Transfer * @param _transferAction The message * @return The recipient address as bytes32 */ function recipient(bytes29 _transferAction) internal pure typeAssert(_transferAction, Types.Transfer) returns (bytes32) { // before = 1 byte identifier return _transferAction.index(1, 32); } /** * @notice Retrieves the EVM Recipient from a Transfer * @param _transferAction The message * @return The EVM Recipient */ function evmRecipient(bytes29 _transferAction) internal pure typeAssert(_transferAction, Types.Transfer) returns (address) { // before = 1 byte identifier + 12 bytes empty to trim for address return _transferAction.indexAddress(13); } /** * @notice Retrieves the amount from a Transfer * @param _transferAction The message * @return The amount */ function amnt(bytes29 _transferAction) internal pure typeAssert(_transferAction, Types.Transfer) returns (uint256) { // before = 1 byte identifier + 32 bytes ID return _transferAction.indexUint(33, 32); } /** * @notice Retrieves the name from Details * @param _detailsAction The message * @return The name */ function name(bytes29 _detailsAction) internal pure typeAssert(_detailsAction, Types.Details) returns (bytes32) { // before = 1 byte identifier return _detailsAction.index(1, 32); } /** * @notice Retrieves the symbol from Details * @param _detailsAction The message * @return The symbol */ function symbol(bytes29 _detailsAction) internal pure typeAssert(_detailsAction, Types.Details) returns (bytes32) { // before = 1 byte identifier + 32 bytes name return _detailsAction.index(33, 32); } /** * @notice Retrieves the decimals from Details * @param _detailsAction The message * @return The decimals */ function decimals(bytes29 _detailsAction) internal pure typeAssert(_detailsAction, Types.Details) returns (uint8) { // before = 1 byte identifier + 32 bytes name + 32 bytes symbol return uint8(_detailsAction.indexUint(65, 1)); } /** * @notice Retrieves the token ID from a Message * @param _message The message * @return The ID */ function tokenId(bytes29 _message) internal pure typeAssert(_message, Types.Message) returns (bytes29) { return _message.slice(0, TOKEN_ID_LEN, uint40(Types.TokenId)); } /** * @notice Retrieves the action data from a Message * @param _message The message * @return The action */ function action(bytes29 _message) internal pure typeAssert(_message, Types.Message) returns (bytes29) { uint256 _actionLen = _message.len() - TOKEN_ID_LEN; uint40 _type = uint40(msgType(_message)); return _message.slice(TOKEN_ID_LEN, _actionLen, _type); } /** * @notice Converts to a Transfer * @param _action The message * @return The newly typed message */ function tryAsTransfer(bytes29 _action) internal pure returns (bytes29) { if (_action.len() == TRANSFER_LEN) { return _action.castTo(uint40(Types.Transfer)); } return TypedMemView.nullView(); } /** * @notice Converts to a Details * @param _action The message * @return The newly typed message */ function tryAsDetails(bytes29 _action) internal pure returns (bytes29) { if (_action.len() == DETAILS_LEN) { return _action.castTo(uint40(Types.Details)); } return TypedMemView.nullView(); } /** * @notice Converts to a Details * @param _action The message * @return The newly typed message */ function tryAsRequestDetails(bytes29 _action) internal pure returns (bytes29) { if (_action.len() == REQUEST_DETAILS_LEN) { return _action.castTo(uint40(Types.RequestDetails)); } return TypedMemView.nullView(); } /** * @notice Converts to a TokenID * @param _tokenId The message * @return The newly typed message */ function tryAsTokenId(bytes29 _tokenId) internal pure returns (bytes29) { if (_tokenId.len() == TOKEN_ID_LEN) { return _tokenId.castTo(uint40(Types.TokenId)); } return TypedMemView.nullView(); } /** * @notice Converts to a Message * @param _message The message * @return The newly typed message */ function tryAsMessage(bytes29 _message) internal pure returns (bytes29) { if (isValidMessageLength(_message)) { return _message.castTo(uint40(Types.Message)); } return TypedMemView.nullView(); } /** * @notice Asserts that the message is of type Transfer * @param _view The message * @return The message */ function mustBeTransfer(bytes29 _view) internal pure returns (bytes29) { return tryAsTransfer(_view).assertValid(); } /** * @notice Asserts that the message is of type Details * @param _view The message * @return The message */ function mustBeDetails(bytes29 _view) internal pure returns (bytes29) { return tryAsDetails(_view).assertValid(); } /** * @notice Asserts that the message is of type Details * @param _view The message * @return The message */ function mustBeRequestDetails(bytes29 _view) internal pure returns (bytes29) { return tryAsRequestDetails(_view).assertValid(); } /** * @notice Asserts that the message is of type TokenID * @param _view The message * @return The message */ function mustBeTokenId(bytes29 _view) internal pure returns (bytes29) { return tryAsTokenId(_view).assertValid(); } /** * @notice Asserts that the message is of type Message * @param _view The message * @return The message */ function mustBeMessage(bytes29 _view) internal pure returns (bytes29) { return tryAsMessage(_view).assertValid(); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Version0} from "./Version0.sol"; import {Common} from "./Common.sol"; import {QueueLib} from "../libs/Queue.sol"; import {MerkleLib} from "../libs/Merkle.sol"; import {Message} from "../libs/Message.sol"; import {MerkleTreeManager} from "./Merkle.sol"; import {QueueManager} from "./Queue.sol"; import {IUpdaterManager} from "../interfaces/IUpdaterManager.sol"; // ============ External Imports ============ import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; /** * @title Home * @author Celo Labs Inc. * @notice Accepts messages to be dispatched to remote chains, * constructs a Merkle tree of the messages, * and accepts signatures from a bonded Updater * which notarize the Merkle tree roots. * Accepts submissions of fraudulent signatures * by the Updater and slashes the Updater in this case. */ contract Home is Version0, QueueManager, MerkleTreeManager, Common, OwnableUpgradeable { // ============ Libraries ============ using QueueLib for QueueLib.Queue; using MerkleLib for MerkleLib.Tree; // ============ Constants ============ // Maximum bytes per message = 2 KiB // (somewhat arbitrarily set to begin) uint256 public constant MAX_MESSAGE_BODY_BYTES = 2 * 2**10; // ============ Public Storage Variables ============ // domain => next available nonce for the domain mapping(uint32 => uint32) public nonces; // contract responsible for Updater bonding, slashing and rotation IUpdaterManager public updaterManager; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[48] private __GAP; // ============ Events ============ /** * @notice Emitted when a new message is dispatched via Optics * @param leafIndex Index of message's leaf in merkle tree * @param destinationAndNonce Destination and destination-specific * nonce combined in single field ((destination << 32) & nonce) * @param messageHash Hash of message; the leaf inserted to the Merkle tree for the message * @param committedRoot the latest notarized root submitted in the last signed Update * @param message Raw bytes of message */ event Dispatch( bytes32 indexed messageHash, uint256 indexed leafIndex, uint64 indexed destinationAndNonce, bytes32 committedRoot, bytes message ); /** * @notice Emitted when proof of an improper update is submitted, * which sets the contract to FAILED state * @param oldRoot Old root of the improper update * @param newRoot New root of the improper update * @param signature Signature on `oldRoot` and `newRoot */ event ImproperUpdate(bytes32 oldRoot, bytes32 newRoot, bytes signature); /** * @notice Emitted when the Updater is slashed * (should be paired with ImproperUpdater or DoubleUpdate event) * @param updater The address of the updater * @param reporter The address of the entity that reported the updater misbehavior */ event UpdaterSlashed(address indexed updater, address indexed reporter); /** * @notice Emitted when Updater is rotated by the UpdaterManager * @param updater The address of the new updater */ event NewUpdater(address updater); /** * @notice Emitted when the UpdaterManager contract is changed * @param updaterManager The address of the new updaterManager */ event NewUpdaterManager(address updaterManager); // ============ Constructor ============ constructor(uint32 _localDomain) Common(_localDomain) {} // solhint-disable-line no-empty-blocks // ============ Initializer ============ function initialize(IUpdaterManager _updaterManager) public initializer { // initialize owner & queue __Ownable_init(); __QueueManager_initialize(); // set Updater Manager contract and initialize Updater _setUpdaterManager(_updaterManager); address _updater = updaterManager.updater(); __Common_initialize(_updater); emit NewUpdater(_updater); } // ============ Modifiers ============ /** * @notice Ensures that function is called by the UpdaterManager contract */ modifier onlyUpdaterManager() { require(msg.sender == address(updaterManager), "!updaterManager"); _; } // ============ External: Updater & UpdaterManager Configuration ============ /** * @notice Set a new Updater * @param _updater the new Updater */ function setUpdater(address _updater) external onlyUpdaterManager { _setUpdater(_updater); } /** * @notice Set a new UpdaterManager contract * @dev Home(s) will initially be initialized using a trusted UpdaterManager contract; * we will progressively decentralize by swapping the trusted contract with a new implementation * that implements Updater bonding & slashing, and rules for Updater selection & rotation * @param _updaterManager the new UpdaterManager contract */ function setUpdaterManager(address _updaterManager) external onlyOwner { _setUpdaterManager(IUpdaterManager(_updaterManager)); } // ============ External Functions ============ /** * @notice Dispatch the message it to the destination domain & recipient * @dev Format the message, insert its hash into Merkle tree, * enqueue the new Merkle root, and emit `Dispatch` event with message information. * @param _destinationDomain Domain of destination chain * @param _recipientAddress Address of recipient on destination chain as bytes32 * @param _messageBody Raw bytes content of message */ function dispatch( uint32 _destinationDomain, bytes32 _recipientAddress, bytes memory _messageBody ) external notFailed { require(_messageBody.length <= MAX_MESSAGE_BODY_BYTES, "msg too long"); // get the next nonce for the destination domain, then increment it uint32 _nonce = nonces[_destinationDomain]; nonces[_destinationDomain] = _nonce + 1; // format the message into packed bytes bytes memory _message = Message.formatMessage( localDomain, bytes32(uint256(uint160(msg.sender))), _nonce, _destinationDomain, _recipientAddress, _messageBody ); // insert the hashed message into the Merkle tree bytes32 _messageHash = keccak256(_message); tree.insert(_messageHash); // enqueue the new Merkle root after inserting the message queue.enqueue(root()); // Emit Dispatch event with message information // note: leafIndex is count() - 1 since new leaf has already been inserted emit Dispatch( _messageHash, count() - 1, _destinationAndNonce(_destinationDomain, _nonce), committedRoot, _message ); } /** * @notice Submit a signature from the Updater "notarizing" a root, * which updates the Home contract's `committedRoot`, * and publishes the signature which will be relayed to Replica contracts * @dev emits Update event * @dev If _newRoot is not contained in the queue, * the Update is a fraudulent Improper Update, so * the Updater is slashed & Home is set to FAILED state * @param _committedRoot Current updated merkle root which the update is building off of * @param _newRoot New merkle root to update the contract state to * @param _signature Updater signature on `_committedRoot` and `_newRoot` */ function update( bytes32 _committedRoot, bytes32 _newRoot, bytes memory _signature ) external notFailed { // check that the update is not fraudulent; // if fraud is detected, Updater is slashed & Home is set to FAILED state if (improperUpdate(_committedRoot, _newRoot, _signature)) return; // clear all of the intermediate roots contained in this update from the queue while (true) { bytes32 _next = queue.dequeue(); if (_next == _newRoot) break; } // update the Home state with the latest signed root & emit event committedRoot = _newRoot; emit Update(localDomain, _committedRoot, _newRoot, _signature); } /** * @notice Suggest an update for the Updater to sign and submit. * @dev If queue is empty, null bytes returned for both * (No update is necessary because no messages have been dispatched since the last update) * @return _committedRoot Latest root signed by the Updater * @return _new Latest enqueued Merkle root */ function suggestUpdate() external view returns (bytes32 _committedRoot, bytes32 _new) { if (queue.length() != 0) { _committedRoot = committedRoot; _new = queue.lastItem(); } } // ============ Public Functions ============ /** * @notice Hash of Home domain concatenated with "OPTICS" */ function homeDomainHash() public view override returns (bytes32) { return _homeDomainHash(localDomain); } /** * @notice Check if an Update is an Improper Update; * if so, slash the Updater and set the contract to FAILED state. * * An Improper Update is an update building off of the Home's `committedRoot` * for which the `_newRoot` does not currently exist in the Home's queue. * This would mean that message(s) that were not truly * dispatched on Home were falsely included in the signed root. * * An Improper Update will only be accepted as valid by the Replica * If an Improper Update is attempted on Home, * the Updater will be slashed immediately. * If an Improper Update is submitted to the Replica, * it should be relayed to the Home contract using this function * in order to slash the Updater with an Improper Update. * * An Improper Update submitted to the Replica is only valid * while the `_oldRoot` is still equal to the `committedRoot` on Home; * if the `committedRoot` on Home has already been updated with a valid Update, * then the Updater should be slashed with a Double Update. * @dev Reverts (and doesn't slash updater) if signature is invalid or * update not current * @param _oldRoot Old merkle tree root (should equal home's committedRoot) * @param _newRoot New merkle tree root * @param _signature Updater signature on `_oldRoot` and `_newRoot` * @return TRUE if update was an Improper Update (implying Updater was slashed) */ function improperUpdate( bytes32 _oldRoot, bytes32 _newRoot, bytes memory _signature ) public notFailed returns (bool) { require( _isUpdaterSignature(_oldRoot, _newRoot, _signature), "!updater sig" ); require(_oldRoot == committedRoot, "not a current update"); // if the _newRoot is not currently contained in the queue, // slash the Updater and set the contract to FAILED state if (!queue.contains(_newRoot)) { _fail(); emit ImproperUpdate(_oldRoot, _newRoot, _signature); return true; } // if the _newRoot is contained in the queue, // this is not an improper update return false; } // ============ Internal Functions ============ /** * @notice Set the UpdaterManager * @param _updaterManager Address of the UpdaterManager */ function _setUpdaterManager(IUpdaterManager _updaterManager) internal { require( Address.isContract(address(_updaterManager)), "!contract updaterManager" ); updaterManager = IUpdaterManager(_updaterManager); emit NewUpdaterManager(address(_updaterManager)); } /** * @notice Set the Updater * @param _updater Address of the Updater */ function _setUpdater(address _updater) internal { updater = _updater; emit NewUpdater(_updater); } /** * @notice Slash the Updater and set contract state to FAILED * @dev Called when fraud is proven (Improper Update or Double Update) */ function _fail() internal override { // set contract to FAILED _setFailed(); // slash Updater updaterManager.slashUpdater(msg.sender); emit UpdaterSlashed(updater, msg.sender); } /** * @notice Internal utility function that combines * `_destination` and `_nonce`. * @dev Both destination and nonce should be less than 2^32 - 1 * @param _destination Domain of destination chain * @param _nonce Current nonce for given destination chain * @return Returns (`_destination` << 32) & `_nonce` */ function _destinationAndNonce(uint32 _destination, uint32 _nonce) internal pure returns (uint64) { return (uint64(_destination) << 32) | _nonce; } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; /** * @title Version0 * @notice Version getter for contracts **/ contract Version0 { uint8 public constant VERSION = 0; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.5.10; import {SafeMath} from "./SafeMath.sol"; library TypedMemView { using SafeMath for uint256; // Why does this exist? // the solidity `bytes memory` type has a few weaknesses. // 1. You can't index ranges effectively // 2. You can't slice without copying // 3. The underlying data may represent any type // 4. Solidity never deallocates memory, and memory costs grow // superlinearly // By using a memory view instead of a `bytes memory` we get the following // advantages: // 1. Slices are done on the stack, by manipulating the pointer // 2. We can index arbitrary ranges and quickly convert them to stack types // 3. We can insert type info into the pointer, and typecheck at runtime // This makes `TypedMemView` a useful tool for efficient zero-copy // algorithms. // Why bytes29? // We want to avoid confusion between views, digests, and other common // types so we chose a large and uncommonly used odd number of bytes // // Note that while bytes are left-aligned in a word, integers and addresses // are right-aligned. This means when working in assembly we have to // account for the 3 unused bytes on the righthand side // // First 5 bytes are a type flag. // - ff_ffff_fffe is reserved for unknown type. // - ff_ffff_ffff is reserved for invalid types/errors. // next 12 are memory address // next 12 are len // bottom 3 bytes are empty // Assumptions: // - non-modification of memory. // - No Solidity updates // - - wrt free mem point // - - wrt bytes representation in memory // - - wrt memory addressing in general // Usage: // - create type constants // - use `assertType` for runtime type assertions // - - unfortunately we can't do this at compile time yet :( // - recommended: implement modifiers that perform type checking // - - e.g. // - - `uint40 constant MY_TYPE = 3;` // - - ` modifer onlyMyType(bytes29 myView) { myView.assertType(MY_TYPE); }` // - instantiate a typed view from a bytearray using `ref` // - use `index` to inspect the contents of the view // - use `slice` to create smaller views into the same memory // - - `slice` can increase the offset // - - `slice can decrease the length` // - - must specify the output type of `slice` // - - `slice` will return a null view if you try to overrun // - - make sure to explicitly check for this with `notNull` or `assertType` // - use `equal` for typed comparisons. // The null view bytes29 public constant NULL = hex"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"; uint256 constant LOW_12_MASK = 0xffffffffffffffffffffffff; uint8 constant TWELVE_BYTES = 96; /** * @notice Returns the encoded hex character that represents the lower 4 bits of the argument. * @param _b The byte * @return char - The encoded hex character */ function nibbleHex(uint8 _b) internal pure returns (uint8 char) { // This can probably be done more efficiently, but it's only in error // paths, so we don't really care :) uint8 _nibble = _b | 0xf0; // set top 4, keep bottom 4 if (_nibble == 0xf0) {return 0x30;} // 0 if (_nibble == 0xf1) {return 0x31;} // 1 if (_nibble == 0xf2) {return 0x32;} // 2 if (_nibble == 0xf3) {return 0x33;} // 3 if (_nibble == 0xf4) {return 0x34;} // 4 if (_nibble == 0xf5) {return 0x35;} // 5 if (_nibble == 0xf6) {return 0x36;} // 6 if (_nibble == 0xf7) {return 0x37;} // 7 if (_nibble == 0xf8) {return 0x38;} // 8 if (_nibble == 0xf9) {return 0x39;} // 9 if (_nibble == 0xfa) {return 0x61;} // a if (_nibble == 0xfb) {return 0x62;} // b if (_nibble == 0xfc) {return 0x63;} // c if (_nibble == 0xfd) {return 0x64;} // d if (_nibble == 0xfe) {return 0x65;} // e if (_nibble == 0xff) {return 0x66;} // f } /** * @notice Returns a uint16 containing the hex-encoded byte. * @param _b The byte * @return encoded - The hex-encoded byte */ function byteHex(uint8 _b) internal pure returns (uint16 encoded) { encoded |= nibbleHex(_b >> 4); // top 4 bits encoded <<= 8; encoded |= nibbleHex(_b); // lower 4 bits } /** * @notice Encodes the uint256 to hex. `first` contains the encoded top 16 bytes. * `second` contains the encoded lower 16 bytes. * * @param _b The 32 bytes as uint256 * @return first - The top 16 bytes * @return second - The bottom 16 bytes */ function encodeHex(uint256 _b) internal pure returns (uint256 first, uint256 second) { for (uint8 i = 31; i > 15; i -= 1) { uint8 _byte = uint8(_b >> (i * 8)); first |= byteHex(_byte); if (i != 16) { first <<= 16; } } // abusing underflow here =_= for (uint8 i = 15; i < 255 ; i -= 1) { uint8 _byte = uint8(_b >> (i * 8)); second |= byteHex(_byte); if (i != 0) { second <<= 16; } } } /** * @notice Changes the endianness of a uint256. * @dev https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel * @param _b The unsigned integer to reverse * @return v - The reversed value */ function reverseUint256(uint256 _b) internal pure returns (uint256 v) { v = _b; // swap bytes v = ((v >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) | ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8); // swap 2-byte long pairs v = ((v >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) | ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16); // swap 4-byte long pairs v = ((v >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) | ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32); // swap 8-byte long pairs v = ((v >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) | ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64); // swap 16-byte long pairs v = (v >> 128) | (v << 128); } /** * @notice Create a mask with the highest `_len` bits set. * @param _len The length * @return mask - The mask */ function leftMask(uint8 _len) private pure returns (uint256 mask) { // ugly. redo without assembly? assembly { // solium-disable-previous-line security/no-inline-assembly mask := sar( sub(_len, 1), 0x8000000000000000000000000000000000000000000000000000000000000000 ) } } /** * @notice Return the null view. * @return bytes29 - The null view */ function nullView() internal pure returns (bytes29) { return NULL; } /** * @notice Check if the view is null. * @return bool - True if the view is null */ function isNull(bytes29 memView) internal pure returns (bool) { return memView == NULL; } /** * @notice Check if the view is not null. * @return bool - True if the view is not null */ function notNull(bytes29 memView) internal pure returns (bool) { return !isNull(memView); } /** * @notice Check if the view is of a valid type and points to a valid location * in memory. * @dev We perform this check by examining solidity's unallocated memory * pointer and ensuring that the view's upper bound is less than that. * @param memView The view * @return ret - True if the view is valid */ function isValid(bytes29 memView) internal pure returns (bool ret) { if (typeOf(memView) == 0xffffffffff) {return false;} uint256 _end = end(memView); assembly { // solium-disable-previous-line security/no-inline-assembly ret := not(gt(_end, mload(0x40))) } } /** * @notice Require that a typed memory view be valid. * @dev Returns the view for easy chaining. * @param memView The view * @return bytes29 - The validated view */ function assertValid(bytes29 memView) internal pure returns (bytes29) { require(isValid(memView), "Validity assertion failed"); return memView; } /** * @notice Return true if the memview is of the expected type. Otherwise false. * @param memView The view * @param _expected The expected type * @return bool - True if the memview is of the expected type */ function isType(bytes29 memView, uint40 _expected) internal pure returns (bool) { return typeOf(memView) == _expected; } /** * @notice Require that a typed memory view has a specific type. * @dev Returns the view for easy chaining. * @param memView The view * @param _expected The expected type * @return bytes29 - The view with validated type */ function assertType(bytes29 memView, uint40 _expected) internal pure returns (bytes29) { if (!isType(memView, _expected)) { (, uint256 g) = encodeHex(uint256(typeOf(memView))); (, uint256 e) = encodeHex(uint256(_expected)); string memory err = string( abi.encodePacked( "Type assertion failed. Got 0x", uint80(g), ". Expected 0x", uint80(e) ) ); revert(err); } return memView; } /** * @notice Return an identical view with a different type. * @param memView The view * @param _newType The new type * @return newView - The new view with the specified type */ function castTo(bytes29 memView, uint40 _newType) internal pure returns (bytes29 newView) { // then | in the new type assembly { // solium-disable-previous-line security/no-inline-assembly // shift off the top 5 bytes newView := or(newView, shr(40, shl(40, memView))) newView := or(newView, shl(216, _newType)) } } /** * @notice Unsafe raw pointer construction. This should generally not be called * directly. Prefer `ref` wherever possible. * @dev Unsafe raw pointer construction. This should generally not be called * directly. Prefer `ref` wherever possible. * @param _type The type * @param _loc The memory address * @param _len The length * @return newView - The new view with the specified type, location and length */ function unsafeBuildUnchecked(uint256 _type, uint256 _loc, uint256 _len) private pure returns (bytes29 newView) { assembly { // solium-disable-previous-line security/no-inline-assembly newView := shl(96, or(newView, _type)) // insert type newView := shl(96, or(newView, _loc)) // insert loc newView := shl(24, or(newView, _len)) // empty bottom 3 bytes } } /** * @notice Instantiate a new memory view. This should generally not be called * directly. Prefer `ref` wherever possible. * @dev Instantiate a new memory view. This should generally not be called * directly. Prefer `ref` wherever possible. * @param _type The type * @param _loc The memory address * @param _len The length * @return newView - The new view with the specified type, location and length */ function build(uint256 _type, uint256 _loc, uint256 _len) internal pure returns (bytes29 newView) { uint256 _end = _loc.add(_len); assembly { // solium-disable-previous-line security/no-inline-assembly if gt(_end, mload(0x40)) { _end := 0 } } if (_end == 0) { return NULL; } newView = unsafeBuildUnchecked(_type, _loc, _len); } /** * @notice Instantiate a memory view from a byte array. * @dev Note that due to Solidity memory representation, it is not possible to * implement a deref, as the `bytes` type stores its len in memory. * @param arr The byte array * @param newType The type * @return bytes29 - The memory view */ function ref(bytes memory arr, uint40 newType) internal pure returns (bytes29) { uint256 _len = arr.length; uint256 _loc; assembly { // solium-disable-previous-line security/no-inline-assembly _loc := add(arr, 0x20) // our view is of the data, not the struct } return build(newType, _loc, _len); } /** * @notice Return the associated type information. * @param memView The memory view * @return _type - The type associated with the view */ function typeOf(bytes29 memView) internal pure returns (uint40 _type) { assembly { // solium-disable-previous-line security/no-inline-assembly // 216 == 256 - 40 _type := shr(216, memView) // shift out lower 24 bytes } } /** * @notice Optimized type comparison. Checks that the 5-byte type flag is equal. * @param left The first view * @param right The second view * @return bool - True if the 5-byte type flag is equal */ function sameType(bytes29 left, bytes29 right) internal pure returns (bool) { return (left ^ right) >> (2 * TWELVE_BYTES) == 0; } /** * @notice Return the memory address of the underlying bytes. * @param memView The view * @return _loc - The memory address */ function loc(bytes29 memView) internal pure returns (uint96 _loc) { uint256 _mask = LOW_12_MASK; // assembly can't use globals assembly { // solium-disable-previous-line security/no-inline-assembly // 120 bits = 12 bytes (the encoded loc) + 3 bytes (empty low space) _loc := and(shr(120, memView), _mask) } } /** * @notice The number of memory words this memory view occupies, rounded up. * @param memView The view * @return uint256 - The number of memory words */ function words(bytes29 memView) internal pure returns (uint256) { return uint256(len(memView)).add(32) / 32; } /** * @notice The in-memory footprint of a fresh copy of the view. * @param memView The view * @return uint256 - The in-memory footprint of a fresh copy of the view. */ function footprint(bytes29 memView) internal pure returns (uint256) { return words(memView) * 32; } /** * @notice The number of bytes of the view. * @param memView The view * @return _len - The length of the view */ function len(bytes29 memView) internal pure returns (uint96 _len) { uint256 _mask = LOW_12_MASK; // assembly can't use globals assembly { // solium-disable-previous-line security/no-inline-assembly _len := and(shr(24, memView), _mask) } } /** * @notice Returns the endpoint of `memView`. * @param memView The view * @return uint256 - The endpoint of `memView` */ function end(bytes29 memView) internal pure returns (uint256) { return loc(memView) + len(memView); } /** * @notice Safe slicing without memory modification. * @param memView The view * @param _index The start index * @param _len The length * @param newType The new type * @return bytes29 - The new view */ function slice(bytes29 memView, uint256 _index, uint256 _len, uint40 newType) internal pure returns (bytes29) { uint256 _loc = loc(memView); // Ensure it doesn't overrun the view if (_loc.add(_index).add(_len) > end(memView)) { return NULL; } _loc = _loc.add(_index); return build(newType, _loc, _len); } /** * @notice Shortcut to `slice`. Gets a view representing the first `_len` bytes. * @param memView The view * @param _len The length * @param newType The new type * @return bytes29 - The new view */ function prefix(bytes29 memView, uint256 _len, uint40 newType) internal pure returns (bytes29) { return slice(memView, 0, _len, newType); } /** * @notice Shortcut to `slice`. Gets a view representing the last `_len` byte. * @param memView The view * @param _len The length * @param newType The new type * @return bytes29 - The new view */ function postfix(bytes29 memView, uint256 _len, uint40 newType) internal pure returns (bytes29) { return slice(memView, uint256(len(memView)).sub(_len), _len, newType); } /** * @notice Construct an error message for an indexing overrun. * @param _loc The memory address * @param _len The length * @param _index The index * @param _slice The slice where the overrun occurred * @return err - The err */ function indexErrOverrun( uint256 _loc, uint256 _len, uint256 _index, uint256 _slice ) internal pure returns (string memory err) { (, uint256 a) = encodeHex(_loc); (, uint256 b) = encodeHex(_len); (, uint256 c) = encodeHex(_index); (, uint256 d) = encodeHex(_slice); err = string( abi.encodePacked( "TypedMemView/index - Overran the view. Slice is at 0x", uint48(a), " with length 0x", uint48(b), ". Attempted to index at offset 0x", uint48(c), " with length 0x", uint48(d), "." ) ); } /** * @notice Load up to 32 bytes from the view onto the stack. * @dev Returns a bytes32 with only the `_bytes` highest bytes set. * This can be immediately cast to a smaller fixed-length byte array. * To automatically cast to an integer, use `indexUint`. * @param memView The view * @param _index The index * @param _bytes The bytes * @return result - The 32 byte result */ function index(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (bytes32 result) { if (_bytes == 0) {return bytes32(0);} if (_index.add(_bytes) > len(memView)) { revert(indexErrOverrun(loc(memView), len(memView), _index, uint256(_bytes))); } require(_bytes <= 32, "TypedMemView/index - Attempted to index more than 32 bytes"); uint8 bitLength = _bytes * 8; uint256 _loc = loc(memView); uint256 _mask = leftMask(bitLength); assembly { // solium-disable-previous-line security/no-inline-assembly result := and(mload(add(_loc, _index)), _mask) } } /** * @notice Parse an unsigned integer from the view at `_index`. * @dev Requires that the view have >= `_bytes` bytes following that index. * @param memView The view * @param _index The index * @param _bytes The bytes * @return result - The unsigned integer */ function indexUint(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (uint256 result) { return uint256(index(memView, _index, _bytes)) >> ((32 - _bytes) * 8); } /** * @notice Parse an unsigned integer from LE bytes. * @param memView The view * @param _index The index * @param _bytes The bytes * @return result - The unsigned integer */ function indexLEUint(bytes29 memView, uint256 _index, uint8 _bytes) internal pure returns (uint256 result) { return reverseUint256(uint256(index(memView, _index, _bytes))); } /** * @notice Parse an address from the view at `_index`. Requires that the view have >= 20 bytes * following that index. * @param memView The view * @param _index The index * @return address - The address */ function indexAddress(bytes29 memView, uint256 _index) internal pure returns (address) { return address(uint160(indexUint(memView, _index, 20))); } /** * @notice Return the keccak256 hash of the underlying memory * @param memView The view * @return digest - The keccak256 hash of the underlying memory */ function keccak(bytes29 memView) internal pure returns (bytes32 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly digest := keccak256(_loc, _len) } } /** * @notice Return the sha2 digest of the underlying memory. * @dev We explicitly deallocate memory afterwards. * @param memView The view * @return digest - The sha2 hash of the underlying memory */ function sha2(bytes29 memView) internal view returns (bytes32 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 #1 digest := mload(ptr) } } /** * @notice Implements bitcoin's hash160 (rmd160(sha2())) * @param memView The pre-image * @return digest - the Digest */ function hash160(bytes29 memView) internal view returns (bytes20 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 pop(staticcall(gas(), 3, ptr, 0x20, ptr, 0x20)) // rmd160 digest := mload(add(ptr, 0xc)) // return value is 0-prefixed. } } /** * @notice Implements bitcoin's hash256 (double sha2) * @param memView A view of the preimage * @return digest - the Digest */ function hash256(bytes29 memView) internal view returns (bytes32 digest) { uint256 _loc = loc(memView); uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) pop(staticcall(gas(), 2, _loc, _len, ptr, 0x20)) // sha2 #1 pop(staticcall(gas(), 2, ptr, 0x20, ptr, 0x20)) // sha2 #2 digest := mload(ptr) } } /** * @notice Return true if the underlying memory is equal. Else false. * @param left The first view * @param right The second view * @return bool - True if the underlying memory is equal */ function untypedEqual(bytes29 left, bytes29 right) internal pure returns (bool) { return (loc(left) == loc(right) && len(left) == len(right)) || keccak(left) == keccak(right); } /** * @notice Return false if the underlying memory is equal. Else true. * @param left The first view * @param right The second view * @return bool - False if the underlying memory is equal */ function untypedNotEqual(bytes29 left, bytes29 right) internal pure returns (bool) { return !untypedEqual(left, right); } /** * @notice Compares type equality. * @dev Shortcuts if the pointers are identical, otherwise compares type and digest. * @param left The first view * @param right The second view * @return bool - True if the types are the same */ function equal(bytes29 left, bytes29 right) internal pure returns (bool) { return left == right || (typeOf(left) == typeOf(right) && keccak(left) == keccak(right)); } /** * @notice Compares type inequality. * @dev Shortcuts if the pointers are identical, otherwise compares type and digest. * @param left The first view * @param right The second view * @return bool - True if the types are not the same */ function notEqual(bytes29 left, bytes29 right) internal pure returns (bool) { return !equal(left, right); } /** * @notice Copy the view to a location, return an unsafe memory reference * @dev Super Dangerous direct memory access. * * This reference can be overwritten if anything else modifies memory (!!!). * As such it MUST be consumed IMMEDIATELY. * This function is private to prevent unsafe usage by callers. * @param memView The view * @param _newLoc The new location * @return written - the unsafe memory reference */ function unsafeCopyTo(bytes29 memView, uint256 _newLoc) private view returns (bytes29 written) { require(notNull(memView), "TypedMemView/copyTo - Null pointer deref"); require(isValid(memView), "TypedMemView/copyTo - Invalid pointer deref"); uint256 _len = len(memView); uint256 _oldLoc = loc(memView); uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // revert if we're writing in occupied memory if gt(ptr, _newLoc) { revert(0x60, 0x20) // empty revert message } // use the identity precompile to copy // guaranteed not to fail, so pop the success pop(staticcall(gas(), 4, _oldLoc, _len, _newLoc, _len)) } written = unsafeBuildUnchecked(typeOf(memView), _newLoc, _len); } /** * @notice Copies the referenced memory to a new loc in memory, returning a `bytes` pointing to * the new memory * @dev Shortcuts if the pointers are identical, otherwise compares type and digest. * @param memView The view * @return ret - The view pointing to the new memory */ function clone(bytes29 memView) internal view returns (bytes memory ret) { uint256 ptr; uint256 _len = len(memView); assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer ret := ptr } unsafeCopyTo(memView, ptr + 0x20); assembly { // solium-disable-previous-line security/no-inline-assembly mstore(0x40, add(add(ptr, _len), 0x20)) // write new unused pointer mstore(ptr, _len) // write len of new array (in bytes) } } /** * @notice Join the views in memory, return an unsafe reference to the memory. * @dev Super Dangerous direct memory access. * * This reference can be overwritten if anything else modifies memory (!!!). * As such it MUST be consumed IMMEDIATELY. * This function is private to prevent unsafe usage by callers. * @param memViews The views * @return unsafeView - The conjoined view pointing to the new memory */ function unsafeJoin(bytes29[] memory memViews, uint256 _location) private view returns (bytes29 unsafeView) { assembly { // solium-disable-previous-line security/no-inline-assembly let ptr := mload(0x40) // revert if we're writing in occupied memory if gt(ptr, _location) { revert(0x60, 0x20) // empty revert message } } uint256 _offset = 0; for (uint256 i = 0; i < memViews.length; i ++) { bytes29 memView = memViews[i]; unsafeCopyTo(memView, _location + _offset); _offset += len(memView); } unsafeView = unsafeBuildUnchecked(0, _location, _offset); } /** * @notice Produce the keccak256 digest of the concatenated contents of multiple views. * @param memViews The views * @return bytes32 - The keccak256 digest */ function joinKeccak(bytes29[] memory memViews) internal view returns (bytes32) { uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer } return keccak(unsafeJoin(memViews, ptr)); } /** * @notice Produce the sha256 digest of the concatenated contents of multiple views. * @param memViews The views * @return bytes32 - The sha256 digest */ function joinSha2(bytes29[] memory memViews) internal view returns (bytes32) { uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer } return sha2(unsafeJoin(memViews, ptr)); } /** * @notice copies all views, joins them into a new bytearray. * @param memViews The views * @return ret - The new byte array */ function join(bytes29[] memory memViews) internal view returns (bytes memory ret) { uint256 ptr; assembly { // solium-disable-previous-line security/no-inline-assembly ptr := mload(0x40) // load unused memory pointer } bytes29 _newView = unsafeJoin(memViews, ptr + 0x20); uint256 _written = len(_newView); uint256 _footprint = footprint(_newView); assembly { // solium-disable-previous-line security/no-inline-assembly // store the legnth mstore(ptr, _written) // new pointer is old + 0x20 + the footprint of the body mstore(0x40, add(add(ptr, _footprint), 0x20)) ret := ptr } } } // 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; 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 OR Apache-2.0 pragma solidity >=0.6.11; library Encoding { // ============ Constants ============ bytes private constant NIBBLE_LOOKUP = "0123456789abcdef"; // ============ Internal Functions ============ /** * @notice Encode a uint32 in its DECIMAL representation, with leading * zeroes. * @param _num The number to encode * @return _encoded The encoded number, suitable for use in abi. * encodePacked */ function decimalUint32(uint32 _num) internal pure returns (uint80 _encoded) { uint80 ASCII_0 = 0x30; // all over/underflows are impossible // this will ALWAYS produce 10 decimal characters for (uint8 i = 0; i < 10; i += 1) { _encoded |= ((_num % 10) + ASCII_0) << (i * 8); _num = _num / 10; } } /** * @notice Encodes the uint256 to hex. `first` contains the encoded top 16 bytes. * `second` contains the encoded lower 16 bytes. * @param _bytes The 32 bytes as uint256 * @return _firstHalf The top 16 bytes * @return _secondHalf The bottom 16 bytes */ function encodeHex(uint256 _bytes) internal pure returns (uint256 _firstHalf, uint256 _secondHalf) { for (uint8 i = 31; i > 15; i -= 1) { uint8 _b = uint8(_bytes >> (i * 8)); _firstHalf |= _byteHex(_b); if (i != 16) { _firstHalf <<= 16; } } // abusing underflow here =_= for (uint8 i = 15; i < 255; i -= 1) { uint8 _b = uint8(_bytes >> (i * 8)); _secondHalf |= _byteHex(_b); if (i != 0) { _secondHalf <<= 16; } } } /** * @notice Returns the encoded hex character that represents the lower 4 bits of the argument. * @param _byte The byte * @return _char The encoded hex character */ function _nibbleHex(uint8 _byte) private pure returns (uint8 _char) { uint8 _nibble = _byte & 0x0f; // keep bottom 4, 0 top 4 _char = uint8(NIBBLE_LOOKUP[_nibble]); } /** * @notice Returns a uint16 containing the hex-encoded byte. * @param _byte The byte * @return _encoded The hex-encoded byte */ function _byteHex(uint8 _byte) private pure returns (uint16 _encoded) { _encoded |= _nibbleHex(_byte >> 4); // top 4 bits _encoded <<= 8; _encoded |= _nibbleHex(_byte); // lower 4 bits } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.11; // ============ External Imports ============ import {Address} from "@openzeppelin/contracts/utils/Address.sol"; /** * @title UpgradeBeaconProxy * @notice * Proxy contract which delegates all logic, including initialization, * to an implementation contract. * The implementation contract is stored within an Upgrade Beacon contract; * the implementation contract can be changed by performing an upgrade on the Upgrade Beacon contract. * The Upgrade Beacon contract for this Proxy is immutably specified at deployment. * @dev This implementation combines the gas savings of keeping the UpgradeBeacon address outside of contract storage * found in 0age's implementation: * https://github.com/dharma-eng/dharma-smart-wallet/blob/master/contracts/proxies/smart-wallet/UpgradeBeaconProxyV1.sol * With the added safety checks that the UpgradeBeacon and implementation are contracts at time of deployment * found in OpenZeppelin's implementation: * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/proxy/beacon/BeaconProxy.sol */ contract UpgradeBeaconProxy { // ============ Immutables ============ // Upgrade Beacon address is immutable (therefore not kept in contract storage) address private immutable upgradeBeacon; // ============ Constructor ============ /** * @notice Validate that the Upgrade Beacon is a contract, then set its * address immutably within this contract. * Validate that the implementation is also a contract, * Then call the initialization function defined at the implementation. * The deployment will revert and pass along the * revert reason if the initialization function reverts. * @param _upgradeBeacon Address of the Upgrade Beacon to be stored immutably in the contract * @param _initializationCalldata Calldata supplied when calling the initialization function */ constructor(address _upgradeBeacon, bytes memory _initializationCalldata) payable { // Validate the Upgrade Beacon is a contract require(Address.isContract(_upgradeBeacon), "beacon !contract"); // set the Upgrade Beacon upgradeBeacon = _upgradeBeacon; // Validate the implementation is a contract address _implementation = _getImplementation(_upgradeBeacon); require( Address.isContract(_implementation), "beacon implementation !contract" ); // Call the initialization function on the implementation if (_initializationCalldata.length > 0) { _initialize(_implementation, _initializationCalldata); } } // ============ External Functions ============ /** * @notice Forwards all calls with data to _fallback() * No public functions are declared on the contract, so all calls hit fallback */ fallback() external payable { _fallback(); } /** * @notice Forwards all calls with no data to _fallback() */ receive() external payable { _fallback(); } // ============ Private Functions ============ /** * @notice Call the initialization function on the implementation * Used at deployment to initialize the proxy * based on the logic for initialization defined at the implementation * @param _implementation - Contract to which the initalization is delegated * @param _initializationCalldata - Calldata supplied when calling the initialization function */ function _initialize( address _implementation, bytes memory _initializationCalldata ) private { // Delegatecall into the implementation, supplying initialization calldata. (bool _ok, ) = _implementation.delegatecall(_initializationCalldata); // Revert and include revert data if delegatecall to implementation reverts. if (!_ok) { assembly { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } } /** * @notice Delegates function calls to the implementation contract returned by the Upgrade Beacon */ function _fallback() private { _delegate(_getImplementation()); } /** * @notice Delegate function execution to the implementation contract * @dev This is a low level function that doesn't return to its internal * call site. It will return whatever is returned by the implementation to the * external caller, reverting and returning the revert data if implementation * reverts. * @param _implementation - Address to which the function execution is delegated */ function _delegate(address _implementation) private { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Delegatecall to the implementation, supplying calldata and gas. // Out and outsize are set to zero - instead, use the return buffer. let result := delegatecall( gas(), _implementation, 0, calldatasize(), 0, 0 ) // Copy the returned data from the return buffer. returndatacopy(0, 0, returndatasize()) switch result // Delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @notice Call the Upgrade Beacon to get the current implementation contract address * @return _implementation Address of the current implementation. */ function _getImplementation() private view returns (address _implementation) { _implementation = _getImplementation(upgradeBeacon); } /** * @notice Call the Upgrade Beacon to get the current implementation contract address * @dev _upgradeBeacon is passed as a parameter so that * we can also use this function in the constructor, * where we can't access immutable variables. * @param _upgradeBeacon Address of the UpgradeBeacon storing the current implementation * @return _implementation Address of the current implementation. */ function _getImplementation(address _upgradeBeacon) private view returns (address _implementation) { // Get the current implementation address from the upgrade beacon. (bool _ok, bytes memory _returnData) = _upgradeBeacon.staticcall(""); // Revert and pass along revert message if call to upgrade beacon reverts. require(_ok, string(_returnData)); // Set the implementation to the address returned from the upgrade beacon. _implementation = abi.decode(_returnData, (address)); } } // 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.5.10; /* The MIT License (MIT) Copyright (c) 2016 Smart Contract Solutions, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; require(c / _a == _b, "Overflow during multiplication."); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a, "Underflow during subtraction."); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; require(c >= _a, "Overflow during addition."); return c; } } // 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 OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Message} from "../libs/Message.sol"; // ============ External Imports ============ import {ECDSA} from "@openzeppelin/contracts/cryptography/ECDSA.sol"; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title Common * @author Celo Labs Inc. * @notice Shared utilities between Home and Replica. */ abstract contract Common is Initializable { // ============ Enums ============ // States: // 0 - UnInitialized - before initialize function is called // note: the contract is initialized at deploy time, so it should never be in this state // 1 - Active - as long as the contract has not become fraudulent // 2 - Failed - after a valid fraud proof has been submitted; // contract will no longer accept updates or new messages enum States { UnInitialized, Active, Failed } // ============ Immutable Variables ============ // Domain of chain on which the contract is deployed uint32 public immutable localDomain; // ============ Public Variables ============ // Address of bonded Updater address public updater; // Current state of contract States public state; // The latest root that has been signed by the Updater bytes32 public committedRoot; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[47] private __GAP; // ============ Events ============ /** * @notice Emitted when update is made on Home * or unconfirmed update root is submitted on Replica * @param homeDomain Domain of home contract * @param oldRoot Old merkle root * @param newRoot New merkle root * @param signature Updater's signature on `oldRoot` and `newRoot` */ event Update( uint32 indexed homeDomain, bytes32 indexed oldRoot, bytes32 indexed newRoot, bytes signature ); /** * @notice Emitted when proof of a double update is submitted, * which sets the contract to FAILED state * @param oldRoot Old root shared between two conflicting updates * @param newRoot Array containing two conflicting new roots * @param signature Signature on `oldRoot` and `newRoot`[0] * @param signature2 Signature on `oldRoot` and `newRoot`[1] */ event DoubleUpdate( bytes32 oldRoot, bytes32[2] newRoot, bytes signature, bytes signature2 ); // ============ Modifiers ============ /** * @notice Ensures that contract state != FAILED when the function is called */ modifier notFailed() { require(state != States.Failed, "failed state"); _; } // ============ Constructor ============ constructor(uint32 _localDomain) { localDomain = _localDomain; } // ============ Initializer ============ function __Common_initialize(address _updater) internal initializer { updater = _updater; state = States.Active; } // ============ External Functions ============ /** * @notice Called by external agent. Checks that signatures on two sets of * roots are valid and that the new roots conflict with each other. If both * cases hold true, the contract is failed and a `DoubleUpdate` event is * emitted. * @dev When `fail()` is called on Home, updater is slashed. * @param _oldRoot Old root shared between two conflicting updates * @param _newRoot Array containing two conflicting new roots * @param _signature Signature on `_oldRoot` and `_newRoot`[0] * @param _signature2 Signature on `_oldRoot` and `_newRoot`[1] */ function doubleUpdate( bytes32 _oldRoot, bytes32[2] calldata _newRoot, bytes calldata _signature, bytes calldata _signature2 ) external notFailed { if ( Common._isUpdaterSignature(_oldRoot, _newRoot[0], _signature) && Common._isUpdaterSignature(_oldRoot, _newRoot[1], _signature2) && _newRoot[0] != _newRoot[1] ) { _fail(); emit DoubleUpdate(_oldRoot, _newRoot, _signature, _signature2); } } // ============ Public Functions ============ /** * @notice Hash of Home domain concatenated with "OPTICS" */ function homeDomainHash() public view virtual returns (bytes32); // ============ Internal Functions ============ /** * @notice Hash of Home domain concatenated with "OPTICS" * @param _homeDomain the Home domain to hash */ function _homeDomainHash(uint32 _homeDomain) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_homeDomain, "OPTICS")); } /** * @notice Set contract state to FAILED * @dev Called when a valid fraud proof is submitted */ function _setFailed() internal { state = States.Failed; } /** * @notice Moves the contract into failed state * @dev Called when fraud is proven * (Double Update is submitted on Home or Replica, * or Improper Update is submitted on Home) */ function _fail() internal virtual; /** * @notice Checks that signature was signed by Updater * @param _oldRoot Old merkle root * @param _newRoot New merkle root * @param _signature Signature on `_oldRoot` and `_newRoot` * @return TRUE iff signature is valid signed by updater **/ function _isUpdaterSignature( bytes32 _oldRoot, bytes32 _newRoot, bytes memory _signature ) internal view returns (bool) { bytes32 _digest = keccak256( abi.encodePacked(homeDomainHash(), _oldRoot, _newRoot) ); _digest = ECDSA.toEthSignedMessageHash(_digest); return (ECDSA.recover(_digest, _signature) == updater); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; /** * @title QueueLib * @author Celo Labs Inc. * @notice Library containing queue struct and operations for queue used by * Home and Replica. **/ library QueueLib { /** * @notice Queue struct * @dev Internally keeps track of the `first` and `last` elements through * indices and a mapping of indices to enqueued elements. **/ struct Queue { uint128 first; uint128 last; mapping(uint256 => bytes32) queue; } /** * @notice Initializes the queue * @dev Empty state denoted by _q.first > q._last. Queue initialized * with _q.first = 1 and _q.last = 0. **/ function initialize(Queue storage _q) internal { if (_q.first == 0) { _q.first = 1; } } /** * @notice Enqueues a single new element * @param _item New element to be enqueued * @return _last Index of newly enqueued element **/ function enqueue(Queue storage _q, bytes32 _item) internal returns (uint128 _last) { _last = _q.last + 1; _q.last = _last; if (_item != bytes32(0)) { // saves gas if we're queueing 0 _q.queue[_last] = _item; } } /** * @notice Dequeues element at front of queue * @dev Removes dequeued element from storage * @return _item Dequeued element **/ function dequeue(Queue storage _q) internal returns (bytes32 _item) { uint128 _last = _q.last; uint128 _first = _q.first; require(_length(_last, _first) != 0, "Empty"); _item = _q.queue[_first]; if (_item != bytes32(0)) { // saves gas if we're dequeuing 0 delete _q.queue[_first]; } _q.first = _first + 1; } /** * @notice Batch enqueues several elements * @param _items Array of elements to be enqueued * @return _last Index of last enqueued element **/ function enqueue(Queue storage _q, bytes32[] memory _items) internal returns (uint128 _last) { _last = _q.last; for (uint256 i = 0; i < _items.length; i += 1) { _last += 1; bytes32 _item = _items[i]; if (_item != bytes32(0)) { _q.queue[_last] = _item; } } _q.last = _last; } /** * @notice Batch dequeues `_number` elements * @dev Reverts if `_number` > queue length * @param _number Number of elements to dequeue * @return Array of dequeued elements **/ function dequeue(Queue storage _q, uint256 _number) internal returns (bytes32[] memory) { uint128 _last = _q.last; uint128 _first = _q.first; // Cannot underflow unless state is corrupted require(_length(_last, _first) >= _number, "Insufficient"); bytes32[] memory _items = new bytes32[](_number); for (uint256 i = 0; i < _number; i++) { _items[i] = _q.queue[_first]; delete _q.queue[_first]; _first++; } _q.first = _first; return _items; } /** * @notice Returns true if `_item` is in the queue and false if otherwise * @dev Linearly scans from _q.first to _q.last looking for `_item` * @param _item Item being searched for in queue * @return True if `_item` currently exists in queue, false if otherwise **/ function contains(Queue storage _q, bytes32 _item) internal view returns (bool) { for (uint256 i = _q.first; i <= _q.last; i++) { if (_q.queue[i] == _item) { return true; } } return false; } /// @notice Returns last item in queue /// @dev Returns bytes32(0) if queue empty function lastItem(Queue storage _q) internal view returns (bytes32) { return _q.queue[_q.last]; } /// @notice Returns element at front of queue without removing element /// @dev Reverts if queue is empty function peek(Queue storage _q) internal view returns (bytes32 _item) { require(!isEmpty(_q), "Empty"); _item = _q.queue[_q.first]; } /// @notice Returns true if queue is empty and false if otherwise function isEmpty(Queue storage _q) internal view returns (bool) { return _q.last < _q.first; } /// @notice Returns number of elements in queue function length(Queue storage _q) internal view returns (uint256) { uint128 _last = _q.last; uint128 _first = _q.first; // Cannot underflow unless state is corrupted return _length(_last, _first); } /// @notice Returns number of elements between `_last` and `_first` (used internally) function _length(uint128 _last, uint128 _first) internal pure returns (uint256) { return uint256(_last + 1 - _first); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // work based on eth2 deposit contract, which is used under CC0-1.0 /** * @title MerkleLib * @author Celo Labs Inc. * @notice An incremental merkle tree modeled on the eth2 deposit contract. **/ library MerkleLib { uint256 internal constant TREE_DEPTH = 32; uint256 internal constant MAX_LEAVES = 2**TREE_DEPTH - 1; /** * @notice Struct representing incremental merkle tree. Contains current * branch and the number of inserted leaves in the tree. **/ struct Tree { bytes32[TREE_DEPTH] branch; uint256 count; } /** * @notice Inserts `_node` into merkle tree * @dev Reverts if tree is full * @param _node Element to insert into tree **/ function insert(Tree storage _tree, bytes32 _node) internal { require(_tree.count < MAX_LEAVES, "merkle tree full"); _tree.count += 1; uint256 size = _tree.count; for (uint256 i = 0; i < TREE_DEPTH; i++) { if ((size & 1) == 1) { _tree.branch[i] = _node; return; } _node = keccak256(abi.encodePacked(_tree.branch[i], _node)); size /= 2; } // As the loop should always end prematurely with the `return` statement, // this code should be unreachable. We assert `false` just to be safe. assert(false); } /** * @notice Calculates and returns`_tree`'s current root given array of zero * hashes * @param _zeroes Array of zero hashes * @return _current Calculated root of `_tree` **/ function rootWithCtx(Tree storage _tree, bytes32[TREE_DEPTH] memory _zeroes) internal view returns (bytes32 _current) { uint256 _index = _tree.count; for (uint256 i = 0; i < TREE_DEPTH; i++) { uint256 _ithBit = (_index >> i) & 0x01; bytes32 _next = _tree.branch[i]; if (_ithBit == 1) { _current = keccak256(abi.encodePacked(_next, _current)); } else { _current = keccak256(abi.encodePacked(_current, _zeroes[i])); } } } /// @notice Calculates and returns`_tree`'s current root function root(Tree storage _tree) internal view returns (bytes32) { return rootWithCtx(_tree, zeroHashes()); } /// @notice Returns array of TREE_DEPTH zero hashes /// @return _zeroes Array of TREE_DEPTH zero hashes function zeroHashes() internal pure returns (bytes32[TREE_DEPTH] memory _zeroes) { _zeroes[0] = Z_0; _zeroes[1] = Z_1; _zeroes[2] = Z_2; _zeroes[3] = Z_3; _zeroes[4] = Z_4; _zeroes[5] = Z_5; _zeroes[6] = Z_6; _zeroes[7] = Z_7; _zeroes[8] = Z_8; _zeroes[9] = Z_9; _zeroes[10] = Z_10; _zeroes[11] = Z_11; _zeroes[12] = Z_12; _zeroes[13] = Z_13; _zeroes[14] = Z_14; _zeroes[15] = Z_15; _zeroes[16] = Z_16; _zeroes[17] = Z_17; _zeroes[18] = Z_18; _zeroes[19] = Z_19; _zeroes[20] = Z_20; _zeroes[21] = Z_21; _zeroes[22] = Z_22; _zeroes[23] = Z_23; _zeroes[24] = Z_24; _zeroes[25] = Z_25; _zeroes[26] = Z_26; _zeroes[27] = Z_27; _zeroes[28] = Z_28; _zeroes[29] = Z_29; _zeroes[30] = Z_30; _zeroes[31] = Z_31; } /** * @notice Calculates and returns the merkle root for the given leaf * `_item`, a merkle branch, and the index of `_item` in the tree. * @param _item Merkle leaf * @param _branch Merkle proof * @param _index Index of `_item` in tree * @return _current Calculated merkle root **/ function branchRoot( bytes32 _item, bytes32[TREE_DEPTH] memory _branch, uint256 _index ) internal pure returns (bytes32 _current) { _current = _item; for (uint256 i = 0; i < TREE_DEPTH; i++) { uint256 _ithBit = (_index >> i) & 0x01; bytes32 _next = _branch[i]; if (_ithBit == 1) { _current = keccak256(abi.encodePacked(_next, _current)); } else { _current = keccak256(abi.encodePacked(_current, _next)); } } } // keccak256 zero hashes bytes32 internal constant Z_0 = hex"0000000000000000000000000000000000000000000000000000000000000000"; bytes32 internal constant Z_1 = hex"ad3228b676f7d3cd4284a5443f17f1962b36e491b30a40b2405849e597ba5fb5"; bytes32 internal constant Z_2 = hex"b4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30"; bytes32 internal constant Z_3 = hex"21ddb9a356815c3fac1026b6dec5df3124afbadb485c9ba5a3e3398a04b7ba85"; bytes32 internal constant Z_4 = hex"e58769b32a1beaf1ea27375a44095a0d1fb664ce2dd358e7fcbfb78c26a19344"; bytes32 internal constant Z_5 = hex"0eb01ebfc9ed27500cd4dfc979272d1f0913cc9f66540d7e8005811109e1cf2d"; bytes32 internal constant Z_6 = hex"887c22bd8750d34016ac3c66b5ff102dacdd73f6b014e710b51e8022af9a1968"; bytes32 internal constant Z_7 = hex"ffd70157e48063fc33c97a050f7f640233bf646cc98d9524c6b92bcf3ab56f83"; bytes32 internal constant Z_8 = hex"9867cc5f7f196b93bae1e27e6320742445d290f2263827498b54fec539f756af"; bytes32 internal constant Z_9 = hex"cefad4e508c098b9a7e1d8feb19955fb02ba9675585078710969d3440f5054e0"; bytes32 internal constant Z_10 = hex"f9dc3e7fe016e050eff260334f18a5d4fe391d82092319f5964f2e2eb7c1c3a5"; bytes32 internal constant Z_11 = hex"f8b13a49e282f609c317a833fb8d976d11517c571d1221a265d25af778ecf892"; bytes32 internal constant Z_12 = hex"3490c6ceeb450aecdc82e28293031d10c7d73bf85e57bf041a97360aa2c5d99c"; bytes32 internal constant Z_13 = hex"c1df82d9c4b87413eae2ef048f94b4d3554cea73d92b0f7af96e0271c691e2bb"; bytes32 internal constant Z_14 = hex"5c67add7c6caf302256adedf7ab114da0acfe870d449a3a489f781d659e8becc"; bytes32 internal constant Z_15 = hex"da7bce9f4e8618b6bd2f4132ce798cdc7a60e7e1460a7299e3c6342a579626d2"; bytes32 internal constant Z_16 = hex"2733e50f526ec2fa19a22b31e8ed50f23cd1fdf94c9154ed3a7609a2f1ff981f"; bytes32 internal constant Z_17 = hex"e1d3b5c807b281e4683cc6d6315cf95b9ade8641defcb32372f1c126e398ef7a"; bytes32 internal constant Z_18 = hex"5a2dce0a8a7f68bb74560f8f71837c2c2ebbcbf7fffb42ae1896f13f7c7479a0"; bytes32 internal constant Z_19 = hex"b46a28b6f55540f89444f63de0378e3d121be09e06cc9ded1c20e65876d36aa0"; bytes32 internal constant Z_20 = hex"c65e9645644786b620e2dd2ad648ddfcbf4a7e5b1a3a4ecfe7f64667a3f0b7e2"; bytes32 internal constant Z_21 = hex"f4418588ed35a2458cffeb39b93d26f18d2ab13bdce6aee58e7b99359ec2dfd9"; bytes32 internal constant Z_22 = hex"5a9c16dc00d6ef18b7933a6f8dc65ccb55667138776f7dea101070dc8796e377"; bytes32 internal constant Z_23 = hex"4df84f40ae0c8229d0d6069e5c8f39a7c299677a09d367fc7b05e3bc380ee652"; bytes32 internal constant Z_24 = hex"cdc72595f74c7b1043d0e1ffbab734648c838dfb0527d971b602bc216c9619ef"; bytes32 internal constant Z_25 = hex"0abf5ac974a1ed57f4050aa510dd9c74f508277b39d7973bb2dfccc5eeb0618d"; bytes32 internal constant Z_26 = hex"b8cd74046ff337f0a7bf2c8e03e10f642c1886798d71806ab1e888d9e5ee87d0"; bytes32 internal constant Z_27 = hex"838c5655cb21c6cb83313b5a631175dff4963772cce9108188b34ac87c81c41e"; bytes32 internal constant Z_28 = hex"662ee4dd2dd7b2bc707961b1e646c4047669dcb6584f0d8d770daf5d7e7deb2e"; bytes32 internal constant Z_29 = hex"388ab20e2573d171a88108e79d820e98f26c0b84aa8b2f4aa4968dbb818ea322"; bytes32 internal constant Z_30 = hex"93237c50ba75ee485f4c22adf2f741400bdf8d6a9cc7df7ecae576221665d735"; bytes32 internal constant Z_31 = hex"8448818bb4ae4562849e949e17ac16e0be16688e156b5cf15e098c627c0056a9"; } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; import "@summa-tx/memview-sol/contracts/TypedMemView.sol"; import { TypeCasts } from "./TypeCasts.sol"; /** * @title Message Library * @author Celo Labs Inc. * @notice Library for formatted messages used by Home and Replica. **/ library Message { using TypedMemView for bytes; using TypedMemView for bytes29; // Number of bytes in formatted message before `body` field uint256 internal constant PREFIX_LENGTH = 76; /** * @notice Returns formatted (packed) message with provided fields * @param _originDomain Domain of home chain * @param _sender Address of sender as bytes32 * @param _nonce Destination-specific nonce * @param _destinationDomain Domain of destination chain * @param _recipient Address of recipient on destination chain as bytes32 * @param _messageBody Raw bytes of message body * @return Formatted message **/ function formatMessage( uint32 _originDomain, bytes32 _sender, uint32 _nonce, uint32 _destinationDomain, bytes32 _recipient, bytes memory _messageBody ) internal pure returns (bytes memory) { return abi.encodePacked( _originDomain, _sender, _nonce, _destinationDomain, _recipient, _messageBody ); } /** * @notice Returns leaf of formatted message with provided fields. * @param _origin Domain of home chain * @param _sender Address of sender as bytes32 * @param _nonce Destination-specific nonce number * @param _destination Domain of destination chain * @param _recipient Address of recipient on destination chain as bytes32 * @param _body Raw bytes of message body * @return Leaf (hash) of formatted message **/ function messageHash( uint32 _origin, bytes32 _sender, uint32 _nonce, uint32 _destination, bytes32 _recipient, bytes memory _body ) internal pure returns (bytes32) { return keccak256( formatMessage( _origin, _sender, _nonce, _destination, _recipient, _body ) ); } /// @notice Returns message's origin field function origin(bytes29 _message) internal pure returns (uint32) { return uint32(_message.indexUint(0, 4)); } /// @notice Returns message's sender field function sender(bytes29 _message) internal pure returns (bytes32) { return _message.index(4, 32); } /// @notice Returns message's nonce field function nonce(bytes29 _message) internal pure returns (uint32) { return uint32(_message.indexUint(36, 4)); } /// @notice Returns message's destination field function destination(bytes29 _message) internal pure returns (uint32) { return uint32(_message.indexUint(40, 4)); } /// @notice Returns message's recipient field as bytes32 function recipient(bytes29 _message) internal pure returns (bytes32) { return _message.index(44, 32); } /// @notice Returns message's recipient field as an address function recipientAddress(bytes29 _message) internal pure returns (address) { return TypeCasts.bytes32ToAddress(recipient(_message)); } /// @notice Returns message's body field as bytes29 (refer to TypedMemView library for details on bytes29 type) function body(bytes29 _message) internal pure returns (bytes29) { return _message.slice(PREFIX_LENGTH, _message.len() - PREFIX_LENGTH, 0); } function leaf(bytes29 _message) internal view returns (bytes32) { return messageHash(origin(_message), sender(_message), nonce(_message), destination(_message), recipient(_message), TypedMemView.clone(body(_message))); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {MerkleLib} from "../libs/Merkle.sol"; /** * @title MerkleTreeManager * @author Celo Labs Inc. * @notice Contains a Merkle tree instance and * exposes view functions for the tree. */ contract MerkleTreeManager { // ============ Libraries ============ using MerkleLib for MerkleLib.Tree; MerkleLib.Tree public tree; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[49] private __GAP; // ============ Public Functions ============ /** * @notice Calculates and returns tree's current root */ function root() public view returns (bytes32) { return tree.root(); } /** * @notice Returns the number of inserted leaves in the tree (current index) */ function count() public view returns (uint256) { return tree.count; } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {QueueLib} from "../libs/Queue.sol"; // ============ External Imports ============ import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; /** * @title QueueManager * @author Celo Labs Inc. * @notice Contains a queue instance and * exposes view functions for the queue. **/ contract QueueManager is Initializable { // ============ Libraries ============ using QueueLib for QueueLib.Queue; QueueLib.Queue internal queue; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[49] private __GAP; // ============ Initializer ============ function __QueueManager_initialize() internal initializer { queue.initialize(); } // ============ Public Functions ============ /** * @notice Returns number of elements in queue */ function queueLength() external view returns (uint256) { return queue.length(); } /** * @notice Returns TRUE iff `_item` is in the queue */ function queueContains(bytes32 _item) external view returns (bool) { return queue.contains(_item); } /** * @notice Returns last item enqueued to the queue */ function queueEnd() external view returns (bytes32) { return queue.lastItem(); } } // SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity >=0.6.11; interface IUpdaterManager { function slashUpdater(address payable _reporter) external; function updater() external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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 OR Apache-2.0 pragma solidity >=0.6.11; import "@summa-tx/memview-sol/contracts/TypedMemView.sol"; library TypeCasts { using TypedMemView for bytes; using TypedMemView for bytes29; function coerceBytes32(string memory _s) internal pure returns (bytes32 _b) { _b = bytes(_s).ref(0).index(0, uint8(bytes(_s).length)); } // treat it as a null-terminated string of max 32 bytes function coerceString(bytes32 _buf) internal pure returns (string memory _newStr) { uint8 _slen = 0; while (_slen < 32 && _buf[_slen] != 0) { _slen++; } // solhint-disable-next-line no-inline-assembly assembly { _newStr := mload(0x40) mstore(0x40, add(_newStr, 0x40)) // may end up with extra mstore(_newStr, _slen) mstore(add(_newStr, 0x20), _buf) } } // alignment preserving cast function addressToBytes32(address _addr) internal pure returns (bytes32) { return bytes32(uint256(uint160(_addr))); } // alignment preserving cast function bytes32ToAddress(bytes32 _buf) internal pure returns (address) { return address(uint160(uint256(_buf))); } } // 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; 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 OR Apache-2.0 pragma solidity >=0.6.11; // ============ Internal Imports ============ import {Version0} from "./Version0.sol"; import {Common} from "./Common.sol"; import {MerkleLib} from "../libs/Merkle.sol"; import {Message} from "../libs/Message.sol"; import {IMessageRecipient} from "../interfaces/IMessageRecipient.sol"; // ============ External Imports ============ import {TypedMemView} from "@summa-tx/memview-sol/contracts/TypedMemView.sol"; /** * @title Replica * @author Celo Labs Inc. * @notice Track root updates on Home, * prove and dispatch messages to end recipients. */ contract Replica is Version0, Common { // ============ Libraries ============ using MerkleLib for MerkleLib.Tree; using TypedMemView for bytes; using TypedMemView for bytes29; using Message for bytes29; // ============ Enums ============ // Status of Message: // 0 - None - message has not been proven or processed // 1 - Proven - message inclusion proof has been validated // 2 - Processed - message has been dispatched to recipient enum MessageStatus { None, Proven, Processed } // ============ Immutables ============ // Minimum gas for message processing uint256 public immutable PROCESS_GAS; // Reserved gas (to ensure tx completes in case message processing runs out) uint256 public immutable RESERVE_GAS; // ============ Public Storage ============ // Domain of home chain uint32 public remoteDomain; // Number of seconds to wait before root becomes confirmable uint256 public optimisticSeconds; // re-entrancy guard uint8 private entered; // Mapping of roots to allowable confirmation times mapping(bytes32 => uint256) public confirmAt; // Mapping of message leaves to MessageStatus mapping(bytes32 => MessageStatus) public messages; // ============ Upgrade Gap ============ // gap for upgrade safety uint256[44] private __GAP; // ============ Events ============ /** * @notice Emitted when message is processed * @param messageHash Hash of message that failed to process * @param success TRUE if the call was executed successfully, FALSE if the call reverted * @param returnData the return data from the external call */ event Process( bytes32 indexed messageHash, bool indexed success, bytes indexed returnData ); // ============ Constructor ============ // solhint-disable-next-line no-empty-blocks constructor( uint32 _localDomain, uint256 _processGas, uint256 _reserveGas ) Common(_localDomain) { require(_processGas >= 850_000, "!process gas"); require(_reserveGas >= 15_000, "!reserve gas"); PROCESS_GAS = _processGas; RESERVE_GAS = _reserveGas; } // ============ Initializer ============ function initialize( uint32 _remoteDomain, address _updater, bytes32 _committedRoot, uint256 _optimisticSeconds ) public initializer { __Common_initialize(_updater); entered = 1; remoteDomain = _remoteDomain; committedRoot = _committedRoot; confirmAt[_committedRoot] = 1; optimisticSeconds = _optimisticSeconds; } // ============ External Functions ============ /** * @notice Called by external agent. Submits the signed update's new root, * marks root's allowable confirmation time, and emits an `Update` event. * @dev Reverts if update doesn't build off latest committedRoot * or if signature is invalid. * @param _oldRoot Old merkle root * @param _newRoot New merkle root * @param _signature Updater's signature on `_oldRoot` and `_newRoot` */ function update( bytes32 _oldRoot, bytes32 _newRoot, bytes memory _signature ) external notFailed { // ensure that update is building off the last submitted root require(_oldRoot == committedRoot, "not current update"); // validate updater signature require( _isUpdaterSignature(_oldRoot, _newRoot, _signature), "!updater sig" ); // Hook for future use _beforeUpdate(); // set the new root's confirmation timer confirmAt[_newRoot] = block.timestamp + optimisticSeconds; // update committedRoot committedRoot = _newRoot; emit Update(remoteDomain, _oldRoot, _newRoot, _signature); } /** * @notice First attempts to prove the validity of provided formatted * `message`. If the message is successfully proven, then tries to process * message. * @dev Reverts if `prove` call returns false * @param _message Formatted message (refer to Common.sol Message library) * @param _proof Merkle proof of inclusion for message's leaf * @param _index Index of leaf in home's merkle tree */ function proveAndProcess( bytes memory _message, bytes32[32] calldata _proof, uint256 _index ) external { require(prove(keccak256(_message), _proof, _index), "!prove"); process(_message); } /** * @notice Given formatted message, attempts to dispatch * message payload to end recipient. * @dev Recipient must implement a `handle` method (refer to IMessageRecipient.sol) * Reverts if formatted message's destination domain is not the Replica's domain, * if message has not been proven, * or if not enough gas is provided for the dispatch transaction. * @param _message Formatted message * @return _success TRUE iff dispatch transaction succeeded */ function process(bytes memory _message) public returns (bool _success) { bytes29 _m = _message.ref(0); // ensure message was meant for this domain require(_m.destination() == localDomain, "!destination"); // ensure message has been proven bytes32 _messageHash = _m.keccak(); require(messages[_messageHash] == MessageStatus.Proven, "!proven"); // check re-entrancy guard require(entered == 1, "!reentrant"); entered = 0; // update message status as processed messages[_messageHash] = MessageStatus.Processed; // A call running out of gas TYPICALLY errors the whole tx. We want to // a) ensure the call has a sufficient amount of gas to make a // meaningful state change. // b) ensure that if the subcall runs out of gas, that the tx as a whole // does not revert (i.e. we still mark the message processed) // To do this, we require that we have enough gas to process // and still return. We then delegate only the minimum processing gas. require(gasleft() >= PROCESS_GAS + RESERVE_GAS, "!gas"); // get the message recipient address _recipient = _m.recipientAddress(); // set up for assembly call uint256 _toCopy; uint256 _maxCopy = 256; uint256 _gas = PROCESS_GAS; // allocate memory for returndata bytes memory _returnData = new bytes(_maxCopy); bytes memory _calldata = abi.encodeWithSignature( "handle(uint32,bytes32,bytes)", _m.origin(), _m.sender(), _m.body().clone() ); // dispatch message to recipient // by assembly calling "handle" function // we call via assembly to avoid memcopying a very large returndata // returned by a malicious contract assembly { _success := call( _gas, // gas _recipient, // recipient 0, // ether value add(_calldata, 0x20), // inloc mload(_calldata), // inlen 0, // outloc 0 // outlen ) // limit our copy to 256 bytes _toCopy := returndatasize() if gt(_toCopy, _maxCopy) { _toCopy := _maxCopy } // Store the length of the copied bytes mstore(_returnData, _toCopy) // copy the bytes from returndata[0:_toCopy] returndatacopy(add(_returnData, 0x20), 0, _toCopy) } // emit process results emit Process(_messageHash, _success, _returnData); // reset re-entrancy guard entered = 1; } // ============ Public Functions ============ /** * @notice Check that the root has been submitted * and that the optimistic timeout period has expired, * meaning the root can be processed * @param _root the Merkle root, submitted in an update, to check * @return TRUE iff root has been submitted & timeout has expired */ function acceptableRoot(bytes32 _root) public view returns (bool) { uint256 _time = confirmAt[_root]; if (_time == 0) { return false; } return block.timestamp >= _time; } /** * @notice Attempts to prove the validity of message given its leaf, the * merkle proof of inclusion for the leaf, and the index of the leaf. * @dev Reverts if message's MessageStatus != None (i.e. if message was * already proven or processed) * @dev For convenience, we allow proving against any previous root. * This means that witnesses never need to be updated for the new root * @param _leaf Leaf of message to prove * @param _proof Merkle proof of inclusion for leaf * @param _index Index of leaf in home's merkle tree * @return Returns true if proof was valid and `prove` call succeeded **/ function prove( bytes32 _leaf, bytes32[32] calldata _proof, uint256 _index ) public returns (bool) { // ensure that message has not been proven or processed require(messages[_leaf] == MessageStatus.None, "!MessageStatus.None"); // calculate the expected root based on the proof bytes32 _calculatedRoot = MerkleLib.branchRoot(_leaf, _proof, _index); // if the root is valid, change status to Proven if (acceptableRoot(_calculatedRoot)) { messages[_leaf] = MessageStatus.Proven; return true; } return false; } /** * @notice Hash of Home domain concatenated with "OPTICS" */ function homeDomainHash() public view override returns (bytes32) { return _homeDomainHash(remoteDomain); } // ============ Internal Functions ============ /** * @notice Moves the contract into failed state * @dev Called when a Double Update is submitted */ function _fail() internal override { _setFailed(); } /// @notice Hook for potential future use // solhint-disable-next-line no-empty-blocks function _beforeUpdate() internal {} } // 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 OR Apache-2.0 pragma solidity >=0.6.11; interface IMessageRecipient { function handle( uint32 _origin, bytes32 _sender, bytes memory _message ) external; } // 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 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; } }
* @notice Returns TRUE iff `_item` is in the queue/
function queueContains(bytes32 _item) external view returns (bool) { return queue.contains(_item); }
1,209,562
[ 1, 1356, 5383, 21437, 1375, 67, 1726, 68, 353, 316, 326, 2389, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2389, 10846, 12, 3890, 1578, 389, 1726, 13, 3903, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 2389, 18, 12298, 24899, 1726, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42220/0x618C47cB34Bc8fA09c2b4f04b1a08d3eaA2509eB/sources/verified-sources/0x2c801aEcfD7c6C5cCDC7F5f7101eC151ed193800/sources/contracts/WeightedPool.sol
The protocol fees will always be charged using the token associated with the max weight in the pool. Since these Pools will register tokens only once, we can assume this index will be constant.
contract WeightedPool is BaseMinimalSwapInfoPool, WeightedMath { using FixedPoint for uint256; using WeightedPoolUserDataHelpers for bytes; uint256 private immutable _maxWeightTokenIndex; uint256 private immutable _normalizedWeight0; uint256 private immutable _normalizedWeight1; uint256 private immutable _normalizedWeight2; uint256 private immutable _normalizedWeight3; uint256 private immutable _normalizedWeight4; uint256 private immutable _normalizedWeight5; uint256 private immutable _normalizedWeight6; uint256 private immutable _normalizedWeight7; uint256 private _lastInvariant; constructor( IVault vault, string memory name, string memory symbol, IERC20[] memory tokens, uint256[] memory normalizedWeights, uint256 swapFeePercentage, uint256 pauseWindowDuration, uint256 bufferPeriodDuration, address owner ) BaseMinimalSwapInfoPool( vault, name, symbol, tokens, swapFeePercentage, pauseWindowDuration, bufferPeriodDuration, owner ) enum JoinKind { INIT, EXACT_TOKENS_IN_FOR_BPT_OUT, TOKEN_IN_FOR_EXACT_BPT_OUT } enum ExitKind { EXACT_BPT_IN_FOR_ONE_TOKEN_OUT, EXACT_BPT_IN_FOR_TOKENS_OUT, BPT_IN_FOR_EXACT_TOKENS_OUT } { uint256 numTokens = tokens.length; InputHelpers.ensureInputLengthMatch(numTokens, normalizedWeights.length); uint256 normalizedSum = 0; uint256 maxWeightTokenIndex = 0; uint256 maxNormalizedWeight = 0; for (uint8 i = 0; i < numTokens; i++) { uint256 normalizedWeight = normalizedWeights[i]; _require(normalizedWeight >= _MIN_WEIGHT, Errors.MIN_WEIGHT); normalizedSum = normalizedSum.add(normalizedWeight); if (normalizedWeight > maxNormalizedWeight) { maxWeightTokenIndex = i; maxNormalizedWeight = normalizedWeight; } } _maxWeightTokenIndex = maxWeightTokenIndex; _normalizedWeight0 = normalizedWeights.length > 0 ? normalizedWeights[0] : 0; _normalizedWeight1 = normalizedWeights.length > 1 ? normalizedWeights[1] : 0; _normalizedWeight2 = normalizedWeights.length > 2 ? normalizedWeights[2] : 0; _normalizedWeight3 = normalizedWeights.length > 3 ? normalizedWeights[3] : 0; _normalizedWeight4 = normalizedWeights.length > 4 ? normalizedWeights[4] : 0; _normalizedWeight5 = normalizedWeights.length > 5 ? normalizedWeights[5] : 0; _normalizedWeight6 = normalizedWeights.length > 6 ? normalizedWeights[6] : 0; _normalizedWeight7 = normalizedWeights.length > 7 ? normalizedWeights[7] : 0; } { uint256 numTokens = tokens.length; InputHelpers.ensureInputLengthMatch(numTokens, normalizedWeights.length); uint256 normalizedSum = 0; uint256 maxWeightTokenIndex = 0; uint256 maxNormalizedWeight = 0; for (uint8 i = 0; i < numTokens; i++) { uint256 normalizedWeight = normalizedWeights[i]; _require(normalizedWeight >= _MIN_WEIGHT, Errors.MIN_WEIGHT); normalizedSum = normalizedSum.add(normalizedWeight); if (normalizedWeight > maxNormalizedWeight) { maxWeightTokenIndex = i; maxNormalizedWeight = normalizedWeight; } } _maxWeightTokenIndex = maxWeightTokenIndex; _normalizedWeight0 = normalizedWeights.length > 0 ? normalizedWeights[0] : 0; _normalizedWeight1 = normalizedWeights.length > 1 ? normalizedWeights[1] : 0; _normalizedWeight2 = normalizedWeights.length > 2 ? normalizedWeights[2] : 0; _normalizedWeight3 = normalizedWeights.length > 3 ? normalizedWeights[3] : 0; _normalizedWeight4 = normalizedWeights.length > 4 ? normalizedWeights[4] : 0; _normalizedWeight5 = normalizedWeights.length > 5 ? normalizedWeights[5] : 0; _normalizedWeight6 = normalizedWeights.length > 6 ? normalizedWeights[6] : 0; _normalizedWeight7 = normalizedWeights.length > 7 ? normalizedWeights[7] : 0; } { uint256 numTokens = tokens.length; InputHelpers.ensureInputLengthMatch(numTokens, normalizedWeights.length); uint256 normalizedSum = 0; uint256 maxWeightTokenIndex = 0; uint256 maxNormalizedWeight = 0; for (uint8 i = 0; i < numTokens; i++) { uint256 normalizedWeight = normalizedWeights[i]; _require(normalizedWeight >= _MIN_WEIGHT, Errors.MIN_WEIGHT); normalizedSum = normalizedSum.add(normalizedWeight); if (normalizedWeight > maxNormalizedWeight) { maxWeightTokenIndex = i; maxNormalizedWeight = normalizedWeight; } } _maxWeightTokenIndex = maxWeightTokenIndex; _normalizedWeight0 = normalizedWeights.length > 0 ? normalizedWeights[0] : 0; _normalizedWeight1 = normalizedWeights.length > 1 ? normalizedWeights[1] : 0; _normalizedWeight2 = normalizedWeights.length > 2 ? normalizedWeights[2] : 0; _normalizedWeight3 = normalizedWeights.length > 3 ? normalizedWeights[3] : 0; _normalizedWeight4 = normalizedWeights.length > 4 ? normalizedWeights[4] : 0; _normalizedWeight5 = normalizedWeights.length > 5 ? normalizedWeights[5] : 0; _normalizedWeight6 = normalizedWeights.length > 6 ? normalizedWeights[6] : 0; _normalizedWeight7 = normalizedWeights.length > 7 ? normalizedWeights[7] : 0; } _require(normalizedSum == FixedPoint.ONE, Errors.NORMALIZED_WEIGHT_INVARIANT); function _normalizedWeight(IERC20 token) internal view virtual returns (uint256) { else { _revert(Errors.INVALID_TOKEN); } } if (token == _token0) { return _normalizedWeight0; } else if (token == _token1) { return _normalizedWeight1; } else if (token == _token2) { return _normalizedWeight2; } else if (token == _token3) { return _normalizedWeight3; } else if (token == _token4) { return _normalizedWeight4; } else if (token == _token5) { return _normalizedWeight5; } else if (token == _token6) { return _normalizedWeight6; } else if (token == _token7) { return _normalizedWeight7; } function _normalizedWeight(IERC20 token) internal view virtual returns (uint256) { else { _revert(Errors.INVALID_TOKEN); } } function _normalizedWeights() internal view virtual returns (uint256[] memory) { uint256 totalTokens = _getTotalTokens(); uint256[] memory normalizedWeights = new uint256[](totalTokens); { } return normalizedWeights; } function _normalizedWeights() internal view virtual returns (uint256[] memory) { uint256 totalTokens = _getTotalTokens(); uint256[] memory normalizedWeights = new uint256[](totalTokens); { } return normalizedWeights; } if (totalTokens > 0) { normalizedWeights[0] = _normalizedWeight0; } else { return normalizedWeights; } if (totalTokens > 1) { normalizedWeights[1] = _normalizedWeight1; } else { return normalizedWeights; } if (totalTokens > 2) { normalizedWeights[2] = _normalizedWeight2; } else { return normalizedWeights; } if (totalTokens > 3) { normalizedWeights[3] = _normalizedWeight3; } else { return normalizedWeights; } if (totalTokens > 4) { normalizedWeights[4] = _normalizedWeight4; } else { return normalizedWeights; } if (totalTokens > 5) { normalizedWeights[5] = _normalizedWeight5; } else { return normalizedWeights; } if (totalTokens > 6) { normalizedWeights[6] = _normalizedWeight6; } else { return normalizedWeights; } if (totalTokens > 7) { normalizedWeights[7] = _normalizedWeight7; } else { return normalizedWeights; } function getLastInvariant() external view returns (uint256) { return _lastInvariant; } function getInvariant() public view returns (uint256) { (, uint256[] memory balances, ) = getVault().getPoolTokens(getPoolId()); _upscaleArray(balances, _scalingFactors()); uint256[] memory normalizedWeights = _normalizedWeights(); return WeightedMath._calculateInvariant(normalizedWeights, balances); } function getNormalizedWeights() external view returns (uint256[] memory) { return _normalizedWeights(); } function _onSwapGivenIn( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) internal view virtual override whenNotPaused returns (uint256) { return WeightedMath._calcOutGivenIn( currentBalanceTokenIn, _normalizedWeight(swapRequest.tokenIn), currentBalanceTokenOut, _normalizedWeight(swapRequest.tokenOut), swapRequest.amount ); } function _onSwapGivenOut( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) internal view virtual override whenNotPaused returns (uint256) { return WeightedMath._calcInGivenOut( currentBalanceTokenIn, _normalizedWeight(swapRequest.tokenIn), currentBalanceTokenOut, _normalizedWeight(swapRequest.tokenOut), swapRequest.amount ); } function _onInitializePool( bytes32, address, address, bytes memory userData ) internal virtual override whenNotPaused returns (uint256, uint256[] memory) { WeightedPool.JoinKind kind = userData.joinKind(); _require(kind == WeightedPool.JoinKind.INIT, Errors.UNINITIALIZED); uint256[] memory amountsIn = userData.initialAmountsIn(); InputHelpers.ensureInputLengthMatch(_getTotalTokens(), amountsIn.length); _upscaleArray(amountsIn, _scalingFactors()); uint256[] memory normalizedWeights = _normalizedWeights(); uint256 invariantAfterJoin = WeightedMath._calculateInvariant(normalizedWeights, amountsIn); uint256 bptAmountOut = Math.mul(invariantAfterJoin, _getTotalTokens()); _lastInvariant = invariantAfterJoin; return (bptAmountOut, amountsIn); } function _onJoinPool( bytes32, address, address, uint256[] memory balances, uint256, uint256 protocolSwapFeePercentage, bytes memory userData ) internal virtual override whenNotPaused returns ( uint256, uint256[] memory, uint256[] memory ) { uint256[] memory normalizedWeights = _normalizedWeights(); uint256 invariantBeforeJoin = WeightedMath._calculateInvariant(normalizedWeights, balances); uint256[] memory dueProtocolFeeAmounts = _getDueProtocolFeeAmounts( balances, normalizedWeights, _lastInvariant, invariantBeforeJoin, protocolSwapFeePercentage ); _mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); (uint256 bptAmountOut, uint256[] memory amountsIn) = _doJoin(balances, normalizedWeights, userData); _lastInvariant = _invariantAfterJoin(balances, amountsIn, normalizedWeights); return (bptAmountOut, amountsIn, dueProtocolFeeAmounts); } function _doJoin( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { JoinKind kind = userData.joinKind(); if (kind == JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT) { return _joinExactTokensInForBPTOut(balances, normalizedWeights, userData); return _joinTokenInForExactBPTOut(balances, normalizedWeights, userData); _revert(Errors.UNHANDLED_JOIN_KIND); } } function _doJoin( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { JoinKind kind = userData.joinKind(); if (kind == JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT) { return _joinExactTokensInForBPTOut(balances, normalizedWeights, userData); return _joinTokenInForExactBPTOut(balances, normalizedWeights, userData); _revert(Errors.UNHANDLED_JOIN_KIND); } } } else if (kind == JoinKind.TOKEN_IN_FOR_EXACT_BPT_OUT) { } else { function _joinExactTokensInForBPTOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { (uint256[] memory amountsIn, uint256 minBPTAmountOut) = userData.exactTokensInForBptOut(); InputHelpers.ensureInputLengthMatch(_getTotalTokens(), amountsIn.length); _upscaleArray(amountsIn, _scalingFactors()); uint256 bptAmountOut = WeightedMath._calcBptOutGivenExactTokensIn( balances, normalizedWeights, amountsIn, totalSupply(), _swapFeePercentage ); _require(bptAmountOut >= minBPTAmountOut, Errors.BPT_OUT_MIN_AMOUNT); return (bptAmountOut, amountsIn); } function _joinTokenInForExactBPTOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { (uint256 bptAmountOut, uint256 tokenIndex) = userData.tokenInForExactBptOut(); _require(tokenIndex < _getTotalTokens(), Errors.OUT_OF_BOUNDS); uint256[] memory amountsIn = new uint256[](_getTotalTokens()); amountsIn[tokenIndex] = WeightedMath._calcTokenInGivenExactBptOut( balances[tokenIndex], normalizedWeights[tokenIndex], bptAmountOut, totalSupply(), _swapFeePercentage ); return (bptAmountOut, amountsIn); } function _onExitPool( bytes32, address, address, uint256[] memory balances, uint256, uint256 protocolSwapFeePercentage, bytes memory userData ) internal virtual override returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) { uint256[] memory normalizedWeights = _normalizedWeights(); if (_isNotPaused()) { uint256 invariantBeforeExit = WeightedMath._calculateInvariant(normalizedWeights, balances); dueProtocolFeeAmounts = _getDueProtocolFeeAmounts( balances, normalizedWeights, _lastInvariant, invariantBeforeExit, protocolSwapFeePercentage ); _mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); } (bptAmountIn, amountsOut) = _doExit(balances, normalizedWeights, userData); return (bptAmountIn, amountsOut, dueProtocolFeeAmounts); } function _onExitPool( bytes32, address, address, uint256[] memory balances, uint256, uint256 protocolSwapFeePercentage, bytes memory userData ) internal virtual override returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) { uint256[] memory normalizedWeights = _normalizedWeights(); if (_isNotPaused()) { uint256 invariantBeforeExit = WeightedMath._calculateInvariant(normalizedWeights, balances); dueProtocolFeeAmounts = _getDueProtocolFeeAmounts( balances, normalizedWeights, _lastInvariant, invariantBeforeExit, protocolSwapFeePercentage ); _mutateAmounts(balances, dueProtocolFeeAmounts, FixedPoint.sub); dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); } (bptAmountIn, amountsOut) = _doExit(balances, normalizedWeights, userData); return (bptAmountIn, amountsOut, dueProtocolFeeAmounts); } } else { _lastInvariant = _invariantAfterExit(balances, amountsOut, normalizedWeights); function _doExit( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { ExitKind kind = userData.exitKind(); if (kind == ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT) { return _exitExactBPTInForTokenOut(balances, normalizedWeights, userData); return _exitExactBPTInForTokensOut(balances, userData); return _exitBPTInForExactTokensOut(balances, normalizedWeights, userData); } } function _doExit( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view returns (uint256, uint256[] memory) { ExitKind kind = userData.exitKind(); if (kind == ExitKind.EXACT_BPT_IN_FOR_ONE_TOKEN_OUT) { return _exitExactBPTInForTokenOut(balances, normalizedWeights, userData); return _exitExactBPTInForTokensOut(balances, userData); return _exitBPTInForExactTokensOut(balances, normalizedWeights, userData); } } } else if (kind == ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT) { } else { function _exitExactBPTInForTokenOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view whenNotPaused returns (uint256, uint256[] memory) { (uint256 bptAmountIn, uint256 tokenIndex) = userData.exactBptInForTokenOut(); _require(tokenIndex < _getTotalTokens(), Errors.OUT_OF_BOUNDS); uint256[] memory amountsOut = new uint256[](_getTotalTokens()); amountsOut[tokenIndex] = WeightedMath._calcTokenOutGivenExactBptIn( balances[tokenIndex], normalizedWeights[tokenIndex], bptAmountIn, totalSupply(), _swapFeePercentage ); return (bptAmountIn, amountsOut); } function _exitExactBPTInForTokensOut(uint256[] memory balances, bytes memory userData) private view returns (uint256, uint256[] memory) { uint256 bptAmountIn = userData.exactBptInForTokensOut(); uint256[] memory amountsOut = WeightedMath._calcTokensOutGivenExactBptIn(balances, bptAmountIn, totalSupply()); return (bptAmountIn, amountsOut); } function _exitBPTInForExactTokensOut( uint256[] memory balances, uint256[] memory normalizedWeights, bytes memory userData ) private view whenNotPaused returns (uint256, uint256[] memory) { (uint256[] memory amountsOut, uint256 maxBPTAmountIn) = userData.bptInForExactTokensOut(); InputHelpers.ensureInputLengthMatch(amountsOut.length, _getTotalTokens()); _upscaleArray(amountsOut, _scalingFactors()); uint256 bptAmountIn = WeightedMath._calcBptInGivenExactTokensOut( balances, normalizedWeights, amountsOut, totalSupply(), _swapFeePercentage ); _require(bptAmountIn <= maxBPTAmountIn, Errors.BPT_IN_MAX_AMOUNT); return (bptAmountIn, amountsOut); } function _getDueProtocolFeeAmounts( uint256[] memory balances, uint256[] memory normalizedWeights, uint256 previousInvariant, uint256 currentInvariant, uint256 protocolSwapFeePercentage ) private view returns (uint256[] memory) { uint256[] memory dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); if (protocolSwapFeePercentage == 0) { return dueProtocolFeeAmounts; } balances[_maxWeightTokenIndex], normalizedWeights[_maxWeightTokenIndex], previousInvariant, currentInvariant, protocolSwapFeePercentage ); return dueProtocolFeeAmounts; } function _getDueProtocolFeeAmounts( uint256[] memory balances, uint256[] memory normalizedWeights, uint256 previousInvariant, uint256 currentInvariant, uint256 protocolSwapFeePercentage ) private view returns (uint256[] memory) { uint256[] memory dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); if (protocolSwapFeePercentage == 0) { return dueProtocolFeeAmounts; } balances[_maxWeightTokenIndex], normalizedWeights[_maxWeightTokenIndex], previousInvariant, currentInvariant, protocolSwapFeePercentage ); return dueProtocolFeeAmounts; } dueProtocolFeeAmounts[_maxWeightTokenIndex] = WeightedMath._calcDueTokenProtocolSwapFeeAmount( function _invariantAfterJoin( uint256[] memory balances, uint256[] memory amountsIn, uint256[] memory normalizedWeights ) private view returns (uint256) { _mutateAmounts(balances, amountsIn, FixedPoint.add); return WeightedMath._calculateInvariant(normalizedWeights, balances); } function _invariantAfterExit( uint256[] memory balances, uint256[] memory amountsOut, uint256[] memory normalizedWeights ) private view returns (uint256) { _mutateAmounts(balances, amountsOut, FixedPoint.sub); return WeightedMath._calculateInvariant(normalizedWeights, balances); } function _mutateAmounts( uint256[] memory toMutate, uint256[] memory arguments, function(uint256, uint256) pure returns (uint256) mutation ) private view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { toMutate[i] = mutation(toMutate[i], arguments[i]); } } function _mutateAmounts( uint256[] memory toMutate, uint256[] memory arguments, function(uint256, uint256) pure returns (uint256) mutation ) private view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { toMutate[i] = mutation(toMutate[i], arguments[i]); } } function getRate() public view returns (uint256) { return Math.mul(getInvariant(), _getTotalTokens()).divDown(totalSupply()); } }
16,318,409
[ 1, 1986, 1771, 1656, 281, 903, 3712, 506, 1149, 2423, 1450, 326, 1147, 3627, 598, 326, 943, 3119, 316, 326, 2845, 18, 7897, 4259, 453, 8192, 903, 1744, 2430, 1338, 3647, 16, 732, 848, 6750, 333, 770, 903, 506, 5381, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 15437, 329, 2864, 353, 3360, 2930, 2840, 12521, 966, 2864, 16, 15437, 329, 10477, 288, 203, 565, 1450, 15038, 2148, 364, 2254, 5034, 31, 203, 565, 1450, 15437, 329, 2864, 19265, 13375, 364, 1731, 31, 203, 203, 565, 2254, 5034, 3238, 11732, 389, 1896, 6544, 1345, 1016, 31, 203, 203, 565, 2254, 5034, 3238, 11732, 389, 17762, 6544, 20, 31, 203, 565, 2254, 5034, 3238, 11732, 389, 17762, 6544, 21, 31, 203, 565, 2254, 5034, 3238, 11732, 389, 17762, 6544, 22, 31, 203, 565, 2254, 5034, 3238, 11732, 389, 17762, 6544, 23, 31, 203, 565, 2254, 5034, 3238, 11732, 389, 17762, 6544, 24, 31, 203, 565, 2254, 5034, 3238, 11732, 389, 17762, 6544, 25, 31, 203, 565, 2254, 5034, 3238, 11732, 389, 17762, 6544, 26, 31, 203, 565, 2254, 5034, 3238, 11732, 389, 17762, 6544, 27, 31, 203, 203, 565, 2254, 5034, 3238, 389, 2722, 382, 8688, 31, 203, 203, 203, 565, 3885, 12, 203, 3639, 467, 12003, 9229, 16, 203, 3639, 533, 3778, 508, 16, 203, 3639, 533, 3778, 3273, 16, 203, 3639, 467, 654, 39, 3462, 8526, 3778, 2430, 16, 203, 3639, 2254, 5034, 8526, 3778, 5640, 16595, 16, 203, 3639, 2254, 5034, 7720, 14667, 16397, 16, 203, 3639, 2254, 5034, 11722, 3829, 5326, 16, 203, 3639, 2254, 5034, 1613, 5027, 5326, 16, 203, 3639, 1758, 3410, 203, 565, 262, 203, 3639, 3360, 2930, 2840, 12521, 966, 2864, 12, 203, 5411, 9229, 16, 203, 5411, 508, 16, 203, 5411, 3273, 16, 203, 5411, 2430, 16, 203, 5411, 7720, 14667, 16397, 16, 2 ]
pragma solidity ^0.6.4; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./abdk-libraries-solidity/ABDKMathQuad.sol"; /** * @title A collection of data structures and functions to manage Rebates * Used for low-level state changes, require() conditions should be evaluated * at the caller function scope. */ library Rebates { using SafeMath for uint256; using ABDKMathQuad for uint256; using ABDKMathQuad for bytes16; // Tracks allocation settlements in a Pool per epoch struct Pool { uint256 fees; // total fees in the rebate pool uint256 allocation; // total effective allocation accumulated uint256 settlementsCount; } /** * @dev Deposit tokens into the rebate pool * @param _tokens Amount of fees collected in tokens * @param _allocation Effective stake allocated by the indexer for a period of epochs */ function addToPool( Rebates.Pool storage pool, uint256 _tokens, uint256 _allocation ) internal { pool.fees = pool.fees.add(_tokens); pool.allocation = pool.allocation.add(_allocation); pool.settlementsCount += 1; } /** * @dev Redeem tokens from the rebate pool * @param _tokens Amount of fees collected in tokens * @param _allocation Effective stake allocated by the indexer for a period of epochs * @return Amount of tokens to be released according to Cobb-Douglas rebate reward formula */ function redeem( Rebates.Pool storage pool, uint256 _tokens, uint256 _allocation ) internal returns (uint256) { uint256 tokens = calcRebateReward( 2, // TODO: Fixed to do the sqrt() _tokens, _allocation, pool.allocation, pool.fees ); pool.settlementsCount -= 1; return tokens; } /** * @dev Calculate rebate using production function * @param _indexerAlloc Effective allocation for (epoch,indexer,subgraphDeploymentID) * @param _indexerFees Fees collected on (epoch,indexer,subgraphDeploymentID) * @param _poolAlloc Pooled effective allocation for epoch * @param _poolFees Pooled collected fees for epoch * @return Amount of tokens to be released according to Cobb-Douglas rebate reward formula */ function calcRebateReward( uint256, /*_invAlpha*/ uint256 _indexerAlloc, uint256 _indexerFees, uint256 _poolAlloc, uint256 _poolFees ) public pure returns (uint256) { // NOTE: We sqrt() because alpha is fractional so we expect the inverse of alpha if (_poolAlloc == 0 || _poolFees == 0) { return 0; } // Here we use ABDKMathQuad to do the square root of terms // We have to covert it to a bytes16 fixed point number, do sqrt(), then convert it // back to uint256. uint256 wraps the result of toUInt(), since it returns uint64 bytes16 iAlloc = _indexerAlloc.fromUInt(); bytes16 pAlloc = _poolAlloc.fromUInt(); bytes16 aRatio = iAlloc.div(pAlloc); bytes16 iFees = _indexerFees.fromUInt(); bytes16 pFees = _poolFees.fromUInt(); bytes16 fRatio = iFees.div(pFees); bytes16 termA = aRatio.sqrt(); bytes16 termB = fRatio.sqrt(); bytes16 reward = termA.mul(termB); return uint256(pFees.mul(reward).toUInt()); } }
* @dev Calculate rebate using production function @param _indexerAlloc Effective allocation for (epoch,indexer,subgraphDeploymentID) @param _indexerFees Fees collected on (epoch,indexer,subgraphDeploymentID) @param _poolAlloc Pooled effective allocation for epoch @param _poolFees Pooled collected fees for epoch @return Amount of tokens to be released according to Cobb-Douglas rebate reward formula/ NOTE: We sqrt() because alpha is fractional so we expect the inverse of alpha
function calcRebateReward( uint256, /*_invAlpha*/ uint256 _indexerAlloc, uint256 _indexerFees, uint256 _poolAlloc, uint256 _poolFees ) public pure returns (uint256) { if (_poolAlloc == 0 || _poolFees == 0) { return 0; } bytes16 pAlloc = _poolAlloc.fromUInt(); bytes16 aRatio = iAlloc.div(pAlloc); bytes16 iFees = _indexerFees.fromUInt(); bytes16 pFees = _poolFees.fromUInt(); bytes16 fRatio = iFees.div(pFees); bytes16 termA = aRatio.sqrt(); bytes16 termB = fRatio.sqrt(); bytes16 reward = termA.mul(termB); return uint256(pFees.mul(reward).toUInt()); }
13,098,798
[ 1, 8695, 283, 70, 340, 1450, 12449, 445, 225, 389, 24541, 8763, 512, 21446, 13481, 364, 261, 12015, 16, 24541, 16, 1717, 4660, 6733, 734, 13, 225, 389, 24541, 2954, 281, 5782, 281, 12230, 603, 261, 12015, 16, 24541, 16, 1717, 4660, 6733, 734, 13, 225, 389, 6011, 8763, 453, 22167, 11448, 13481, 364, 7632, 225, 389, 6011, 2954, 281, 453, 22167, 12230, 1656, 281, 364, 7632, 327, 16811, 434, 2430, 358, 506, 15976, 4888, 358, 385, 947, 70, 17, 3244, 637, 9521, 283, 70, 340, 19890, 8013, 19, 5219, 30, 1660, 5700, 1435, 2724, 4190, 353, 20462, 1427, 732, 4489, 326, 8322, 434, 4190, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7029, 426, 70, 340, 17631, 1060, 12, 203, 3639, 2254, 5034, 16, 1748, 67, 5768, 9690, 5549, 203, 3639, 2254, 5034, 389, 24541, 8763, 16, 203, 3639, 2254, 5034, 389, 24541, 2954, 281, 16, 203, 3639, 2254, 5034, 389, 6011, 8763, 16, 203, 3639, 2254, 5034, 389, 6011, 2954, 281, 203, 565, 262, 1071, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 67, 6011, 8763, 422, 374, 747, 389, 6011, 2954, 281, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 1731, 2313, 293, 8763, 273, 389, 6011, 8763, 18, 2080, 14342, 5621, 203, 3639, 1731, 2313, 279, 8541, 273, 277, 8763, 18, 2892, 12, 84, 8763, 1769, 203, 203, 3639, 1731, 2313, 277, 2954, 281, 273, 389, 24541, 2954, 281, 18, 2080, 14342, 5621, 203, 3639, 1731, 2313, 293, 2954, 281, 273, 389, 6011, 2954, 281, 18, 2080, 14342, 5621, 203, 3639, 1731, 2313, 284, 8541, 273, 277, 2954, 281, 18, 2892, 12, 84, 2954, 281, 1769, 203, 203, 3639, 1731, 2313, 2481, 37, 273, 279, 8541, 18, 24492, 5621, 203, 3639, 1731, 2313, 2481, 38, 273, 284, 8541, 18, 24492, 5621, 203, 203, 3639, 1731, 2313, 19890, 273, 2481, 37, 18, 16411, 12, 6408, 38, 1769, 203, 203, 3639, 327, 2254, 5034, 12, 84, 2954, 281, 18, 16411, 12, 266, 2913, 2934, 869, 14342, 10663, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// RUN: --target substrate --emit cfg contract test { /******************/ /* Multiply tests */ /******************/ // BEGIN-CHECK: test::function::f1 function f1() pure public { for (uint i = 0; i < 10; i++) { // this multiply can be done with a 64 bit instruction print("i:{}".format(i * 100)); } // CHECK: zext uint256 ((trunc uint64 %i) * uint64 100) } // BEGIN-CHECK: test::function::f2 function f2(bool x) pure public { uint i = 0; for (;;) { print("i:{}".format(i * 100)); i += 1; if (x) break; } // CHECK: %i * uint256 100 } // BEGIN-CHECK: test::function::f3 function f3(bool x) pure public { uint i = 0; for (;;) { print("i:{}".format((i & 255) * 100)); i += 1; if (x) break; } // CHECK: (zext uint256 ((trunc uint64 (%i & uint256 255)) * uint64 100)) } // BEGIN-CHECK: test::function::f4 function f4() pure public { for (uint i = 0; i < 10; i++) { // this multiply can be done with a 64 bit instruction print("i:{}".format(i * 32768)); } // CHECK: (%i << uint256 15) } // BEGIN-CHECK: test::function::f5 function f5() pure public { for (int i = -50; i < -10; i++) { // this multiply can be done with a 64 bit instruction print("i:{}".format(i * 32769)); } // CHECK: sext int256 ((trunc int64 %i) * int64 32769) } /******************/ /* Division tests */ /******************/ // BEGIN-CHECK: test::function::f6 function f6() pure public { for (uint i = 1e9; i < 1e9+10; i++) { print("i:{}".format(i / 32768)); } // CHECK: (%i >> uint256 15) } // BEGIN-CHECK: test::function::f7 function f7(uint64 arg1) pure public { // we're upcasting to 256 bits, but known bits will track this uint i = arg1; print("i:{}".format(i / 1e6)); // CHECK: zext uint256 ((trunc uint64 %i) / uint64 1000000)) } // BEGIN-CHECK: test::function::f8 function f8() pure public { // too many values to track; (101 values) for (uint i = 1e9; i < 1e9+101; i++) { print("i:{}".format(i / 1e6)); } // CHECK: (%i / uint256 1000000) } /****************/ /* Modulo tests */ /****************/ // BEGIN-CHECK: test::function::f9 function f9() pure public { // too many values to track; (101 values) for (uint i = 1e9; i < 1e9+101; i++) { print("i:{}".format(i % 0x1_0000_0000)); } // CHECK: (%i & uint256 4294967295) } // BEGIN-CHECK: test::function::f10 function f10() pure public { for (int i = 30; i >= 0; i--) { print("i:{}".format(i % 0x1_0000_0001)); } // CHECK: (sext int256 ((trunc int64 %i) % int64 4294967297)) } // BEGIN-CHECK: test::function::f11 function f11() pure public { for (int i = 0; i != 102; i++) { print("i:{}".format(i % 0x1_0000_0001)); } // CHECK: (%i % int256 4294967297) } }
BEGIN-CHECK: test::function::f4 this multiply can be done with a 64 bit instruction
function f4() pure public { for (uint i = 0; i < 10; i++) { }
15,807,385
[ 1, 16061, 17, 10687, 30, 1842, 2866, 915, 2866, 74, 24, 333, 10194, 848, 506, 2731, 598, 279, 5178, 2831, 7592, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 284, 24, 1435, 16618, 1071, 288, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 1728, 31, 277, 27245, 288, 203, 3639, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/8453/0x2DE9EBBf50E3f57858d78b51F7fF9a790064d5A1/sources/contracts/RelicsAction.sol
@notice set price for mint nft @dev price: 1000 = 1 ether, 1 = 0.001 ether
function setPrice(uint64 _price) external onlyOwner { cfg.price = _price; emit SetConfig(cfg); }
11,537,834
[ 1, 542, 6205, 364, 312, 474, 290, 1222, 225, 6205, 30, 4336, 273, 404, 225, 2437, 16, 404, 273, 374, 18, 11664, 225, 2437, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 5147, 12, 11890, 1105, 389, 8694, 13, 3903, 1338, 5541, 288, 203, 3639, 2776, 18, 8694, 273, 389, 8694, 31, 203, 3639, 3626, 1000, 809, 12, 7066, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: @openzeppelin/contracts/math/Math.sol 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); } } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/interfaces/IVat.sol pragma solidity ^0.6.10; /// @dev Interface to interact with the vat contract from MakerDAO /// Taken from https://github.com/makerdao/developerguides/blob/master/devtools/working-with-dsproxy/working-with-dsproxy.md interface IVat { // function can(address, address) external view returns (uint); function hope(address) external; function nope(address) external; function live() external view returns (uint); function ilks(bytes32) external view returns (uint, uint, uint, uint, uint); function urns(bytes32, address) external view returns (uint, uint); function gem(bytes32, address) external view returns (uint); // function dai(address) external view returns (uint); function frob(bytes32, address, address, address, int, int) external; function fork(bytes32, address, address, int, int) external; function move(address, address, uint) external; function flux(bytes32, address, address, uint) external; } // File: contracts/interfaces/IPot.sol pragma solidity ^0.6.10; /// @dev interface for the pot contract from MakerDao /// Taken from https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr.sol interface IPot { function chi() external view returns (uint256); function pie(address) external view returns (uint256); // Not a function, but a public variable. function rho() external returns (uint256); function drip() external returns (uint256); function join(uint256) external; function exit(uint256) external; } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/interfaces/IWeth.sol pragma solidity ^0.6.10; interface IWeth { function deposit() external payable; function withdraw(uint) external; function approve(address, uint) external returns (bool) ; function transfer(address, uint) external returns (bool); function transferFrom(address, address, uint) external returns (bool); } // File: contracts/interfaces/IGemJoin.sol pragma solidity ^0.6.10; /// @dev Interface to interact with the `Join.sol` contract from MakerDAO using ERC20 interface IGemJoin { function rely(address usr) external; function deny(address usr) external; function cage() external; function join(address usr, uint WAD) external; function exit(address usr, uint WAD) external; } // File: contracts/interfaces/IDaiJoin.sol pragma solidity ^0.6.10; /// @dev Interface to interact with the `Join.sol` contract from MakerDAO using Dai interface IDaiJoin { function rely(address usr) external; function deny(address usr) external; function cage() external; function join(address usr, uint WAD) external; function exit(address usr, uint WAD) external; } // File: contracts/interfaces/IChai.sol pragma solidity ^0.6.10; /// @dev interface for the chai contract /// Taken from https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr.sol interface IChai { function balanceOf(address account) external view returns (uint256); function transfer(address dst, uint wad) external returns (bool); function move(address src, address dst, uint wad) external returns (bool); function transferFrom(address src, address dst, uint wad) external returns (bool); function approve(address usr, uint wad) external returns (bool); function dai(address usr) external returns (uint wad); function join(address dst, uint wad) external; function exit(address src, uint wad) external; function draw(address src, uint wad) external; function permit(address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s) external; function nonces(address account) external view returns (uint256); } // File: contracts/interfaces/ITreasury.sol pragma solidity ^0.6.10; interface ITreasury { function debt() external view returns(uint256); function savings() external view returns(uint256); function pushDai(address user, uint256 dai) external; function pullDai(address user, uint256 dai) external; function pushChai(address user, uint256 chai) external; function pullChai(address user, uint256 chai) external; function pushWeth(address to, uint256 weth) external; function pullWeth(address to, uint256 weth) external; function shutdown() external; function live() external view returns(bool); function vat() external view returns (IVat); function weth() external view returns (IWeth); function dai() external view returns (IERC20); function daiJoin() external view returns (IDaiJoin); function wethJoin() external view returns (IGemJoin); function pot() external view returns (IPot); function chai() external view returns (IChai); } // File: contracts/interfaces/IDelegable.sol pragma solidity ^0.6.10; interface IDelegable { function addDelegate(address) external; function addDelegateBySignature(address, address, uint, uint8, bytes32, bytes32) external; } // File: contracts/interfaces/IERC2612.sol // Code adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2237/ pragma solidity ^0.6.0; /** * @dev Interface of the ERC2612 standard as defined in the EIP. * * Adds the {permit} method, which can be used to change one's * {IERC20-allowance} without having to send a transaction, by signing a * message. This allows users to spend tokens without having to hold Ether. * * See https://eips.ethereum.org/EIPS/eip-2612. */ interface IERC2612 { /** * @dev Sets `amount` 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: * * - `owner` cannot be the zero address. * - `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 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; /** * @dev Returns the current ERC2612 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); } // File: contracts/interfaces/IFYDai.sol pragma solidity ^0.6.10; interface IFYDai is IERC20, IERC2612 { function isMature() external view returns(bool); function maturity() external view returns(uint); function chi0() external view returns(uint); function rate0() external view returns(uint); function chiGrowth() external view returns(uint); function rateGrowth() external view returns(uint); function mature() external; function unlocked() external view returns (uint); function mint(address, uint) external; function burn(address, uint) external; function flashMint(uint, bytes calldata) external; function redeem(address, address, uint256) external returns (uint256); // function transfer(address, uint) external returns (bool); // function transferFrom(address, address, uint) external returns (bool); // function approve(address, uint) external returns (bool); } // File: contracts/interfaces/IController.sol pragma solidity ^0.6.10; interface IController is IDelegable { function treasury() external view returns (ITreasury); function series(uint256) external view returns (IFYDai); function seriesIterator(uint256) external view returns (uint256); function totalSeries() external view returns (uint256); function containsSeries(uint256) external view returns (bool); function posted(bytes32, address) external view returns (uint256); function debtFYDai(bytes32, uint256, address) external view returns (uint256); function debtDai(bytes32, uint256, address) external view returns (uint256); function totalDebtDai(bytes32, address) external view returns (uint256); function isCollateralized(bytes32, address) external view returns (bool); function inDai(bytes32, uint256, uint256) external view returns (uint256); function inFYDai(bytes32, uint256, uint256) external view returns (uint256); function erase(bytes32, address) external returns (uint256, uint256); function shutdown() external; function post(bytes32, address, address, uint256) external; function withdraw(bytes32, address, address, uint256) external; function borrow(bytes32, uint256, address, address, uint256) external; function repayFYDai(bytes32, uint256, address, address, uint256) external returns (uint256); function repayDai(bytes32, uint256, address, address, uint256) external returns (uint256); } // File: contracts/helpers/Delegable.sol pragma solidity ^0.6.10; /// @dev Delegable enables users to delegate their account management to other users. /// Delegable implements addDelegateBySignature, to add delegates using a signature instead of a separate transaction. contract Delegable is IDelegable { event Delegate(address indexed user, address indexed delegate, bool enabled); // keccak256("Signature(address user,address delegate,uint256 nonce,uint256 deadline)"); bytes32 public immutable SIGNATURE_TYPEHASH = 0x0d077601844dd17f704bafff948229d27f33b57445915754dfe3d095fda2beb7; bytes32 public immutable DELEGABLE_DOMAIN; mapping(address => uint) public signatureCount; mapping(address => mapping(address => bool)) public delegated; constructor () public { uint256 chainId; assembly { chainId := chainid() } DELEGABLE_DOMAIN = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes('Yield')), keccak256(bytes('1')), chainId, address(this) ) ); } /// @dev Require that msg.sender is the account holder or a delegate modifier onlyHolderOrDelegate(address holder, string memory errorMessage) { require( msg.sender == holder || delegated[holder][msg.sender], errorMessage ); _; } /// @dev Enable a delegate to act on the behalf of caller function addDelegate(address delegate) public override { _addDelegate(msg.sender, delegate); } /// @dev Stop a delegate from acting on the behalf of caller function revokeDelegate(address delegate) public { _revokeDelegate(msg.sender, delegate); } /// @dev Add a delegate through an encoded signature function addDelegateBySignature(address user, address delegate, uint deadline, uint8 v, bytes32 r, bytes32 s) public override { require(deadline >= block.timestamp, 'Delegable: Signature expired'); bytes32 hashStruct = keccak256( abi.encode( SIGNATURE_TYPEHASH, user, delegate, signatureCount[user]++, deadline ) ); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DELEGABLE_DOMAIN, hashStruct ) ); address signer = ecrecover(digest, v, r, s); require( signer != address(0) && signer == user, 'Delegable: Invalid signature' ); _addDelegate(user, delegate); } /// @dev Enable a delegate to act on the behalf of an user function _addDelegate(address user, address delegate) internal { require(!delegated[user][delegate], "Delegable: Already delegated"); delegated[user][delegate] = true; emit Delegate(user, delegate, true); } /// @dev Stop a delegate from acting on the behalf of an user function _revokeDelegate(address user, address delegate) internal { require(delegated[user][delegate], "Delegable: Already undelegated"); delegated[user][delegate] = false; emit Delegate(user, delegate, false); } } // File: contracts/helpers/DecimalMath.sol pragma solidity ^0.6.10; /// @dev Implements simple fixed point math mul and div operations for 27 decimals. contract DecimalMath { using SafeMath for uint256; uint256 constant public UNIT = 1e27; /// @dev Multiplies x and y, assuming they are both fixed point with 27 digits. function muld(uint256 x, uint256 y) internal pure returns (uint256) { return x.mul(y).div(UNIT); } /// @dev Divides x between y, assuming they are both fixed point with 27 digits. function divd(uint256 x, uint256 y) internal pure returns (uint256) { return x.mul(UNIT).div(y); } /// @dev Multiplies x and y, rounding up to the closest representable number. /// Assumes x and y are both fixed point with `decimals` digits. function muldrup(uint256 x, uint256 y) internal pure returns (uint256) { uint256 z = x.mul(y); return z.mod(UNIT) == 0 ? z.div(UNIT) : z.div(UNIT).add(1); } /// @dev Divides x between y, rounding up to the closest representable number. /// Assumes x and y are both fixed point with `decimals` digits. function divdrup(uint256 x, uint256 y) internal pure returns (uint256) { uint256 z = x.mul(UNIT); return z.mod(y) == 0 ? z.div(y) : z.div(y).add(1); } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.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. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/helpers/Orchestrated.sol pragma solidity ^0.6.10; /** * @dev Orchestrated allows to define static access control between multiple contracts. * This contract would be used as a parent contract of any contract that needs to restrict access to some methods, * which would be marked with the `onlyOrchestrated` modifier. * During deployment, the contract deployer (`owner`) can register any contracts that have privileged access by calling `orchestrate`. * Once deployment is completed, `owner` should call `transferOwnership(address(0))` to avoid any more contracts ever gaining privileged access. */ contract Orchestrated is Ownable { event GrantedAccess(address access, bytes4 signature); mapping(address => mapping (bytes4 => bool)) public orchestration; constructor () public Ownable() {} /// @dev Restrict usage to authorized users /// @param err The error to display if the validation fails modifier onlyOrchestrated(string memory err) { require(orchestration[msg.sender][msg.sig], err); _; } /// @dev Add orchestration /// @param user Address of user or contract having access to this contract. /// @param signature bytes4 signature of the function we are giving orchestrated access to. /// It seems to me a bad idea to give access to humans, and would use this only for predictable smart contracts. function orchestrate(address user, bytes4 signature) public onlyOwner { orchestration[user][signature] = true; emit GrantedAccess(user, signature); } /// @dev Adds orchestration for the provided function signatures function batchOrchestrate(address user, bytes4[] memory signatures) public onlyOwner { for (uint256 i = 0; i < signatures.length; i++) { orchestrate(user, signatures[i]); } } } // File: contracts/Controller.sol pragma solidity ^0.6.10; /** * @dev The Controller manages collateral and debt levels for all users, and it is a major user entry point for the Yield protocol. * Controller keeps track of a number of fyDai contracts. * Controller allows users to post and withdraw Chai and Weth collateral. * Any transactions resulting in a user weth collateral below dust are reverted. * Controller allows users to borrow fyDai against their Chai and Weth collateral. * Controller allows users to repay their fyDai debt with fyDai or with Dai. * Controller integrates with fyDai contracts for minting fyDai on borrowing, and burning fyDai on repaying debt with fyDai. * Controller relies on Treasury for all other asset transfers. * Controller allows orchestrated contracts to erase any amount of debt or collateral for an user. This is to be used during liquidations or during unwind. * Users can delegate the control of their accounts in Controllers to any address. */ contract Controller is IController, Orchestrated(), Delegable(), DecimalMath { using SafeMath for uint256; event Posted(bytes32 indexed collateral, address indexed user, int256 amount); event Borrowed(bytes32 indexed collateral, uint256 indexed maturity, address indexed user, int256 amount); bytes32 public constant CHAI = "CHAI"; bytes32 public constant WETH = "ETH-A"; uint256 public constant DUST = 50e15; // 0.05 ETH IVat public vat; IPot public pot; ITreasury public override treasury; mapping(uint256 => IFYDai) public override series; // FYDai series, indexed by maturity uint256[] public override seriesIterator; // We need to know all the series mapping(bytes32 => mapping(address => uint256)) public override posted; // Collateral posted by each user mapping(bytes32 => mapping(uint256 => mapping(address => uint256))) public override debtFYDai; // Debt owed by each user, by series bool public live = true; /// @dev Set up addresses for vat, pot and Treasury. constructor ( address treasury_, address[] memory fyDais ) public { treasury = ITreasury(treasury_); vat = treasury.vat(); pot = treasury.pot(); for (uint256 i = 0; i < fyDais.length; i += 1) { addSeries(fyDais[i]); } } /// @dev Modified functions only callable while the Controller is not unwinding due to a MakerDAO shutdown. modifier onlyLive() { require(live == true, "Controller: Not available during unwind"); _; } /// @dev Only valid collateral types are Weth and Chai. modifier validCollateral(bytes32 collateral) { require( collateral == WETH || collateral == CHAI, "Controller: Unrecognized collateral" ); _; } /// @dev Only series added through `addSeries` are valid. modifier validSeries(uint256 maturity) { require( containsSeries(maturity), "Controller: Unrecognized series" ); _; } /// @dev Safe casting from uint256 to int256 function toInt256(uint256 x) internal pure returns(int256) { require( x <= uint256(type(int256).max), "Controller: Cast overflow" ); return int256(x); } /// @dev Disables post, withdraw, borrow and repay. To be called only when Treasury shuts down. function shutdown() public override { require( treasury.live() == false, "Controller: Treasury is live" ); live = false; } /// @dev Return if the borrowing power for a given collateral of a user is equal or greater /// than its debt for the same collateral /// @param collateral Valid collateral type /// @param user Address of the user vault function isCollateralized(bytes32 collateral, address user) public view override returns (bool) { return powerOf(collateral, user) >= totalDebtDai(collateral, user); } /// @dev Return if the collateral of an user is between zero and the dust level /// @param collateral Valid collateral type /// @param user Address of the user vault function aboveDustOrZero(bytes32 collateral, address user) public view returns (bool) { uint256 postedCollateral = posted[collateral][user]; return postedCollateral == 0 || DUST < postedCollateral; } /// @dev Return the total number of series registered function totalSeries() public view override returns (uint256) { return seriesIterator.length; } /// @dev Returns if a series has been added to the Controller. /// @param maturity Maturity of the series to verify. function containsSeries(uint256 maturity) public view override returns (bool) { return address(series[maturity]) != address(0); } /// @dev Adds an fyDai series to this Controller /// After deployment, ownership should be renounced, so that no more series can be added. /// @param fyDaiContract Address of the fyDai series to add. function addSeries(address fyDaiContract) private { uint256 maturity = IFYDai(fyDaiContract).maturity(); require( !containsSeries(maturity), "Controller: Series already added" ); series[maturity] = IFYDai(fyDaiContract); seriesIterator.push(maturity); } /// @dev Dai equivalent of an fyDai amount. /// After maturity, the Dai value of an fyDai grows according to either the stability fee (for WETH collateral) or the Dai Saving Rate (for Chai collateral). /// @param collateral Valid collateral type /// @param maturity Maturity of an added series /// @param fyDaiAmount Amount of fyDai to convert. /// @return Dai equivalent of an fyDai amount. function inDai(bytes32 collateral, uint256 maturity, uint256 fyDaiAmount) public view override validCollateral(collateral) returns (uint256) { IFYDai fyDai = series[maturity]; if (fyDai.isMature()){ if (collateral == WETH){ return muld(fyDaiAmount, fyDai.rateGrowth()); } else if (collateral == CHAI) { return muld(fyDaiAmount, fyDai.chiGrowth()); } } else { return fyDaiAmount; } } /// @dev fyDai equivalent of a Dai amount. /// After maturity, the fyDai value of a Dai decreases according to either the stability fee (for WETH collateral) or the Dai Saving Rate (for Chai collateral). /// @param collateral Valid collateral type /// @param maturity Maturity of an added series /// @param daiAmount Amount of Dai to convert. /// @return fyDai equivalent of a Dai amount. function inFYDai(bytes32 collateral, uint256 maturity, uint256 daiAmount) public view override validCollateral(collateral) returns (uint256) { IFYDai fyDai = series[maturity]; if (fyDai.isMature()){ if (collateral == WETH){ return divd(daiAmount, fyDai.rateGrowth()); } else if (collateral == CHAI) { return divd(daiAmount, fyDai.chiGrowth()); } } else { return daiAmount; } } /// @dev Debt in dai of an user /// After maturity, the Dai debt of a position grows according to either the stability fee (for WETH collateral) or the Dai Saving Rate (for Chai collateral). /// @param collateral Valid collateral type /// @param maturity Maturity of an added series /// @param user Address of the user vault /// @return Debt in dai of an user // // rate_now // debt_now = debt_mat * ---------- // rate_mat // function debtDai(bytes32 collateral, uint256 maturity, address user) public view override returns (uint256) { return inDai(collateral, maturity, debtFYDai[collateral][maturity][user]); } /// @dev Total debt of an user across all series, in Dai /// The debt is summed across all series, taking into account interest on the debt after a series matures. /// This function loops through all maturities, limiting the contract to hundreds of maturities. /// @param collateral Valid collateral type /// @param user Address of the user vault /// @return Total debt of an user across all series, in Dai function totalDebtDai(bytes32 collateral, address user) public view override returns (uint256) { uint256 totalDebt; uint256[] memory _seriesIterator = seriesIterator; for (uint256 i = 0; i < _seriesIterator.length; i += 1) { if (debtFYDai[collateral][_seriesIterator[i]][user] > 0) { totalDebt = totalDebt.add(debtDai(collateral, _seriesIterator[i], user)); } } // We don't expect hundreds of maturities per controller return totalDebt; } /// @dev Borrowing power (in dai) of a user for a specific series and collateral. /// @param collateral Valid collateral type /// @param user Address of the user vault /// @return Borrowing power of an user in dai. // // powerOf[user](wad) = posted[user](wad) * price()(ray) // function powerOf(bytes32 collateral, address user) public view returns (uint256) { // dai = price * collateral if (collateral == WETH){ (,, uint256 spot,,) = vat.ilks(WETH); // Stability fee and collateralization ratio for Weth return muld(posted[collateral][user], spot); } else if (collateral == CHAI) { uint256 chi = pot.chi(); return muld(posted[collateral][user], chi); } else { revert("Controller: Invalid collateral type"); } } /// @dev Returns the amount of collateral locked in borrowing operations. /// @param collateral Valid collateral type. /// @param user Address of the user vault. function locked(bytes32 collateral, address user) public view validCollateral(collateral) returns (uint256) { if (collateral == WETH){ (,, uint256 spot,,) = vat.ilks(WETH); // Stability fee and collateralization ratio for Weth return divdrup(totalDebtDai(collateral, user), spot); } else if (collateral == CHAI) { return divdrup(totalDebtDai(collateral, user), pot.chi()); } } /// @dev Takes collateral assets from `from` address, and credits them to `to` collateral account. /// `from` can delegate to other addresses to take assets from him. Also needs to use `ERC20.approve`. /// Calling ERC20.approve for Treasury contract is a prerequisite to this function /// @param collateral Valid collateral type. /// @param from Wallet to take collateral from. /// @param to Yield vault to put the collateral in. /// @param amount Amount of collateral to move. // from --- Token ---> us(to) function post(bytes32 collateral, address from, address to, uint256 amount) public override validCollateral(collateral) onlyHolderOrDelegate(from, "Controller: Only Holder Or Delegate") onlyLive { posted[collateral][to] = posted[collateral][to].add(amount); if (collateral == WETH){ require( aboveDustOrZero(collateral, to), "Controller: Below dust" ); treasury.pushWeth(from, amount); } else if (collateral == CHAI) { treasury.pushChai(from, amount); } emit Posted(collateral, to, toInt256(amount)); } /// @dev Returns collateral to `to` wallet, taking it from `from` Yield vault account. /// `from` can delegate to other addresses to take assets from him. /// @param collateral Valid collateral type. /// @param from Yield vault to take collateral from. /// @param to Wallet to put the collateral in. /// @param amount Amount of collateral to move. // us(from) --- Token ---> to function withdraw(bytes32 collateral, address from, address to, uint256 amount) public override validCollateral(collateral) onlyHolderOrDelegate(from, "Controller: Only Holder Or Delegate") onlyLive { posted[collateral][from] = posted[collateral][from].sub(amount); // Will revert if not enough posted require( isCollateralized(collateral, from), "Controller: Too much debt" ); if (collateral == WETH){ require( aboveDustOrZero(collateral, from), "Controller: Below dust" ); treasury.pullWeth(to, amount); } else if (collateral == CHAI) { treasury.pullChai(to, amount); } emit Posted(collateral, from, -toInt256(amount)); } /// @dev Mint fyDai for a given series for wallet `to` by increasing the user debt in Yield vault `from` /// `from` can delegate to other addresses to borrow using his vault. /// The collateral needed changes according to series maturity and MakerDAO rate and chi, depending on collateral type. /// @param collateral Valid collateral type. /// @param maturity Maturity of an added series /// @param from Yield vault that gets an increased debt. /// @param to Wallet to put the fyDai in. /// @param fyDaiAmount Amount of fyDai to borrow. // // posted[user](wad) >= (debtFYDai[user](wad)) * amount (wad)) * collateralization (ray) // // us(from) --- fyDai ---> to // debt++ function borrow(bytes32 collateral, uint256 maturity, address from, address to, uint256 fyDaiAmount) public override validCollateral(collateral) validSeries(maturity) onlyHolderOrDelegate(from, "Controller: Only Holder Or Delegate") onlyLive { IFYDai fyDai = series[maturity]; debtFYDai[collateral][maturity][from] = debtFYDai[collateral][maturity][from].add(fyDaiAmount); require( isCollateralized(collateral, from), "Controller: Too much debt" ); fyDai.mint(to, fyDaiAmount); emit Borrowed(collateral, maturity, from, toInt256(fyDaiAmount)); } /// @dev Burns fyDai from `from` wallet to repay debt in a Yield Vault. /// User debt is decreased for the given collateral and fyDai series, in Yield vault `to`. /// `from` can delegate to other addresses to take fyDai from him for the repayment. /// @param collateral Valid collateral type. /// @param maturity Maturity of an added series /// @param from Wallet providing the fyDai for repayment. /// @param to Yield vault to repay debt for. /// @param fyDaiAmount Amount of fyDai to use for debt repayment. // // debt_nominal // debt_discounted = debt_nominal - repay_amount * --------------- // debt_now // // user(from) --- fyDai ---> us(to) // debt-- function repayFYDai(bytes32 collateral, uint256 maturity, address from, address to, uint256 fyDaiAmount) public override validCollateral(collateral) validSeries(maturity) onlyHolderOrDelegate(from, "Controller: Only Holder Or Delegate") onlyLive returns (uint256) { uint256 toRepay = Math.min(fyDaiAmount, debtFYDai[collateral][maturity][to]); series[maturity].burn(from, toRepay); _repay(collateral, maturity, to, toRepay); return toRepay; } /// @dev Burns Dai from `from` wallet to repay debt in a Yield Vault. /// User debt is decreased for the given collateral and fyDai series, in Yield vault `to`. /// The amount of debt repaid changes according to series maturity and MakerDAO rate and chi, depending on collateral type. /// `from` can delegate to other addresses to take Dai from him for the repayment. /// Calling ERC20.approve for Treasury contract is a prerequisite to this function /// @param collateral Valid collateral type. /// @param maturity Maturity of an added series /// @param from Wallet providing the Dai for repayment. /// @param to Yield vault to repay debt for. /// @param daiAmount Amount of Dai to use for debt repayment. // // debt_nominal // debt_discounted = debt_nominal - repay_amount * --------------- // debt_now // // user --- dai ---> us // debt-- function repayDai(bytes32 collateral, uint256 maturity, address from, address to, uint256 daiAmount) public override validCollateral(collateral) validSeries(maturity) onlyHolderOrDelegate(from, "Controller: Only Holder Or Delegate") onlyLive returns (uint256) { uint256 toRepay = Math.min(daiAmount, debtDai(collateral, maturity, to)); treasury.pushDai(from, toRepay); // Have Treasury process the dai _repay(collateral, maturity, to, inFYDai(collateral, maturity, toRepay)); return toRepay; } /// @dev Removes an amount of debt from an user's vault. /// Internal function. /// @param collateral Valid collateral type. /// @param maturity Maturity of an added series /// @param user Yield vault to repay debt for. /// @param fyDaiAmount Amount of fyDai to use for debt repayment. // // principal // principal_repayment = gross_repayment * ---------------------- // principal + interest // function _repay(bytes32 collateral, uint256 maturity, address user, uint256 fyDaiAmount) internal { debtFYDai[collateral][maturity][user] = debtFYDai[collateral][maturity][user].sub(fyDaiAmount); emit Borrowed(collateral, maturity, user, -toInt256(fyDaiAmount)); } /// @dev Removes all collateral and debt for an user, for a given collateral type. /// This function can only be called by other Yield contracts, not users directly. /// @param collateral Valid collateral type. /// @param user Address of the user vault /// @return The amounts of collateral and debt removed from Controller. function erase(bytes32 collateral, address user) public override validCollateral(collateral) onlyOrchestrated("Controller: Not Authorized") returns (uint256, uint256) { uint256 userCollateral = posted[collateral][user]; delete posted[collateral][user]; uint256 userDebt; uint256[] memory _seriesIterator = seriesIterator; for (uint256 i = 0; i < _seriesIterator.length; i += 1) { uint256 maturity = _seriesIterator[i]; userDebt = userDebt.add(debtDai(collateral, maturity, user)); // SafeMath shouldn't be needed delete debtFYDai[collateral][maturity][user]; } // We don't expect hundreds of maturities per controller return (userCollateral, userDebt); } }
Debt owed by each user, by series
mapping(bytes32 => mapping(uint256 => mapping(address => uint256))) public override debtFYDai;
608,348
[ 1, 758, 23602, 2523, 329, 635, 1517, 729, 16, 635, 4166, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 3890, 1578, 516, 2874, 12, 11890, 5034, 516, 2874, 12, 2867, 516, 2254, 5034, 20349, 1071, 3849, 18202, 88, 42, 61, 40, 10658, 31, 282, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; import "./WorkflowToken.sol"; import "./Workflows.sol"; contract WorkflowMarket is WorkflowToken, Workflows { address creator; event RatingChanged(address indexed _address, uint256 _thumbsup); constructor() public { balances[msg.sender] = _totalSupply; // Give the creator initially all the tokens creator = msg.sender; // Set the creator of the contract } }
Give the creator initially all the tokens
balances[msg.sender] = _totalSupply;
12,951,987
[ 1, 43, 688, 326, 11784, 22458, 777, 326, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 273, 389, 4963, 3088, 1283, 31, 540, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.19; pragma experimental ABIEncoderV2; contract Anticorruption{ struct BasicInfo{ // Basic info of every entity } struct SchemesInfo{ // Schemes basic Info } function AddEntity(uint AdharcardNo, string name, address BankAccountNo) { // Add new Entity } function GetEntity(uint AdharcardNo) returns (string Name ,uint BankAccountNo ) { // Get info About Entity } function AddScheme(string _name,uint _amount) returns (string Status) { // Add new Schemes } function GetScheme(string name) { // Get Schemes } function AddAuthorizedPerson(uint AdharcardNo) returns (string Status) { // AddAuthorizedPerson } function AddAuthorizedCompany(uint CIN) returns (string Status) { // AddAuthorizedCompany } function MoneyForEntityForPerticularSchemes(string name) returns (uint Money) { // GetMoneyForEntityForPerticularSchemes } function TotalMoneyForEntity(string name) returns (uint Money) { // TotalMoneyForEntity } function MoneyToNextLevel() returns (string Status){ // MoneyToNextLevel } function MoneyAPersonGetting() returns (uint Money){ // MoneyAPersonGetting } function TransferMoney(uint From, uint To) returns (string Status){ // TransferMoney } }
Get info About Entity
function GetEntity(uint AdharcardNo) returns (string Name ,uint BankAccountNo ) { }
5,458,860
[ 1, 967, 1123, 9771, 659, 3887, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 968, 1943, 12, 11890, 4052, 30250, 3327, 2279, 13, 1135, 261, 1080, 1770, 269, 11890, 25610, 3032, 2279, 262, 288, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.19; // ERC20 token protocol, see more details at // https://theethereum.wiki/w/index.php/ERC20_Token_Standard // And also https://github.com/ethereum/eips/issues/20 contract Token { string public name; string public symbol; uint8 public decimals; function totalSupply() constant returns (uint256 supply); function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } // Safe mathematics to make the code more readable contract SafeMath { function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } } // Ownable interface to simplify owner checks contract Ownable { address public owner; function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) onlyOwner { require(_newOwner != address(0)); owner = _newOwner; } } // Interface for trading discounts and rebates for specific accounts contract AccountModifiersInterface { function accountModifiers(address _user) constant returns(uint takeFeeDiscount, uint rebatePercentage); function tradeModifiers(address _maker, address _taker) constant returns(uint takeFeeDiscount, uint rebatePercentage); } // Interface for trade tacker contract TradeTrackerInterface { function tradeComplete(address _tokenGet, uint _amountGet, address _tokenGive, uint _amountGive, address _get, address _give, uint _takerFee, uint _makerRebate); } // Exchange contract contract TokenStore is SafeMath, Ownable { // The account that will receive fees address feeAccount; // The account that stores fee discounts/rebates address accountModifiers; // Trade tracker account address tradeTracker; // We charge only the takers and this is the fee, percentage times 1 ether uint public fee; // Mapping of token addresses to mapping of account balances (token 0 means Ether) mapping (address => mapping (address => uint)) public tokens; // Mapping of user accounts to mapping of order hashes to uints (amount of order that has been filled) mapping (address => mapping (bytes32 => uint)) public orderFills; // Address of a next and previous versions of the contract, also status of the contract // can be used for user-triggered fund migrations address public successor; address public predecessor; bool public deprecated; uint16 public version; // Logging events // Note: Order creation is handled off-chain, see explanation further below event Cancel(address tokenGet, uint amountGet, address tokenGive, uint amountGive, uint expires, uint nonce, address user, uint8 v, bytes32 r, bytes32 s); event Trade(address tokenGet, uint amountGet, address tokenGive, uint amountGive, address get, address give, uint nonce); event Deposit(address token, address user, uint amount, uint balance); event Withdraw(address token, address user, uint amount, uint balance); event FundsMigrated(address user); function TokenStore(uint _fee, address _predecessor) { feeAccount = owner; fee = _fee; predecessor = _predecessor; deprecated = false; if (predecessor != address(0)) { version = TokenStore(predecessor).version() + 1; } else { version = 1; } } // Throw on default handler to prevent direct transactions of Ether function() { revert(); } modifier deprecable() { require(!deprecated); _; } function deprecate(bool _deprecated, address _successor) onlyOwner { deprecated = _deprecated; successor = _successor; } function changeFeeAccount(address _feeAccount) onlyOwner { require(_feeAccount != address(0)); feeAccount = _feeAccount; } function changeAccountModifiers(address _accountModifiers) onlyOwner { accountModifiers = _accountModifiers; } function changeTradeTracker(address _tradeTracker) onlyOwner { tradeTracker = _tradeTracker; } // Fee can only be decreased! function changeFee(uint _fee) onlyOwner { require(_fee <= fee); fee = _fee; } // Allows a user to get her current discount/rebate function getAccountModifiers() constant returns(uint takeFeeDiscount, uint rebatePercentage) { if (accountModifiers != address(0)) { return AccountModifiersInterface(accountModifiers).accountModifiers(msg.sender); } else { return (0, 0); } } //////////////////////////////////////////////////////////////////////////////// // Deposits, withdrawals, balances //////////////////////////////////////////////////////////////////////////////// function deposit() payable deprecable { tokens[0][msg.sender] = safeAdd(tokens[0][msg.sender], msg.value); Deposit(0, msg.sender, msg.value, tokens[0][msg.sender]); } function withdraw(uint _amount) { require(tokens[0][msg.sender] >= _amount); tokens[0][msg.sender] = safeSub(tokens[0][msg.sender], _amount); if (!msg.sender.call.value(_amount)()) { revert(); } Withdraw(0, msg.sender, _amount, tokens[0][msg.sender]); } function depositToken(address _token, uint _amount) deprecable { // Note that Token(_token).approve(this, _amount) needs to be called // first or this contract will not be able to do the transfer. require(_token != 0); if (!Token(_token).transferFrom(msg.sender, this, _amount)) { revert(); } tokens[_token][msg.sender] = safeAdd(tokens[_token][msg.sender], _amount); Deposit(_token, msg.sender, _amount, tokens[_token][msg.sender]); } function withdrawToken(address _token, uint _amount) { require(_token != 0); require(tokens[_token][msg.sender] >= _amount); tokens[_token][msg.sender] = safeSub(tokens[_token][msg.sender], _amount); if (!Token(_token).transfer(msg.sender, _amount)) { revert(); } Withdraw(_token, msg.sender, _amount, tokens[_token][msg.sender]); } function balanceOf(address _token, address _user) constant returns (uint) { return tokens[_token][_user]; } //////////////////////////////////////////////////////////////////////////////// // Trading //////////////////////////////////////////////////////////////////////////////// // Note: Order creation happens off-chain but the orders are signed by creators, // we validate the contents and the creator address in the logic below function trade(address _tokenGet, uint _amountGet, address _tokenGive, uint _amountGive, uint _expires, uint _nonce, address _user, uint8 _v, bytes32 _r, bytes32 _s, uint _amount) { bytes32 hash = sha256(this, _tokenGet, _amountGet, _tokenGive, _amountGive, _expires, _nonce); // Check order signatures and expiration, also check if not fulfilled yet if (ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash), _v, _r, _s) != _user || block.number > _expires || safeAdd(orderFills[_user][hash], _amount) > _amountGet) { revert(); } tradeBalances(_tokenGet, _amountGet, _tokenGive, _amountGive, _user, msg.sender, _amount); orderFills[_user][hash] = safeAdd(orderFills[_user][hash], _amount); Trade(_tokenGet, _amount, _tokenGive, _amountGive * _amount / _amountGet, _user, msg.sender, _nonce); } function tradeBalances(address _tokenGet, uint _amountGet, address _tokenGive, uint _amountGive, address _user, address _caller, uint _amount) private { uint feeTakeValue = safeMul(_amount, fee) / (1 ether); uint rebateValue = 0; uint tokenGiveValue = safeMul(_amountGive, _amount) / _amountGet; // Proportionate to request ratio // Apply modifiers if (accountModifiers != address(0)) { var (feeTakeDiscount, rebatePercentage) = AccountModifiersInterface(accountModifiers).tradeModifiers(_user, _caller); // Check that the discounts/rebates are never higher then 100% if (feeTakeDiscount > 100) { feeTakeDiscount = 0; } if (rebatePercentage > 100) { rebatePercentage = 0; } feeTakeValue = safeMul(feeTakeValue, 100 - feeTakeDiscount) / 100; // discounted fee rebateValue = safeMul(rebatePercentage, feeTakeValue) / 100; // % of actual taker fee } tokens[_tokenGet][_user] = safeAdd(tokens[_tokenGet][_user], safeAdd(_amount, rebateValue)); tokens[_tokenGet][_caller] = safeSub(tokens[_tokenGet][_caller], safeAdd(_amount, feeTakeValue)); tokens[_tokenGive][_user] = safeSub(tokens[_tokenGive][_user], tokenGiveValue); tokens[_tokenGive][_caller] = safeAdd(tokens[_tokenGive][_caller], tokenGiveValue); tokens[_tokenGet][feeAccount] = safeAdd(tokens[_tokenGet][feeAccount], safeSub(feeTakeValue, rebateValue)); if (tradeTracker != address(0)) { TradeTrackerInterface(tradeTracker).tradeComplete(_tokenGet, _amount, _tokenGive, tokenGiveValue, _user, _caller, feeTakeValue, rebateValue); } } function testTrade(address _tokenGet, uint _amountGet, address _tokenGive, uint _amountGive, uint _expires, uint _nonce, address _user, uint8 _v, bytes32 _r, bytes32 _s, uint _amount, address _sender) constant returns(bool) { if (tokens[_tokenGet][_sender] < _amount || availableVolume(_tokenGet, _amountGet, _tokenGive, _amountGive, _expires, _nonce, _user, _v, _r, _s) < _amount) { return false; } return true; } function availableVolume(address _tokenGet, uint _amountGet, address _tokenGive, uint _amountGive, uint _expires, uint _nonce, address _user, uint8 _v, bytes32 _r, bytes32 _s) constant returns(uint) { bytes32 hash = sha256(this, _tokenGet, _amountGet, _tokenGive, _amountGive, _expires, _nonce); if (ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash), _v, _r, _s) != _user || block.number > _expires) { return 0; } uint available1 = safeSub(_amountGet, orderFills[_user][hash]); uint available2 = safeMul(tokens[_tokenGive][_user], _amountGet) / _amountGive; if (available1 < available2) return available1; return available2; } function amountFilled(address _tokenGet, uint _amountGet, address _tokenGive, uint _amountGive, uint _expires, uint _nonce, address _user) constant returns(uint) { bytes32 hash = sha256(this, _tokenGet, _amountGet, _tokenGive, _amountGive, _expires, _nonce); return orderFills[_user][hash]; } function cancelOrder(address _tokenGet, uint _amountGet, address _tokenGive, uint _amountGive, uint _expires, uint _nonce, uint8 _v, bytes32 _r, bytes32 _s) { bytes32 hash = sha256(this, _tokenGet, _amountGet, _tokenGive, _amountGive, _expires, _nonce); if (!(ecrecover(sha3("\x19Ethereum Signed Message:\n32", hash), _v, _r, _s) == msg.sender)) { revert(); } orderFills[msg.sender][hash] = _amountGet; Cancel(_tokenGet, _amountGet, _tokenGive, _amountGive, _expires, _nonce, msg.sender, _v, _r, _s); } //////////////////////////////////////////////////////////////////////////////// // Migrations //////////////////////////////////////////////////////////////////////////////// // User-triggered (!) fund migrations in case contract got updated // Similar to withdraw but we use a successor account instead // As we don't store user tokens list on chain, it has to be passed from the outside function migrateFunds(address[] _tokens) { // Get the latest successor in the chain require(successor != address(0)); TokenStore newExchange = TokenStore(successor); for (uint16 n = 0; n < 20; n++) { // We will look past 20 contracts in the future address nextSuccessor = newExchange.successor(); if (nextSuccessor == address(this)) { // Circular succession revert(); } if (nextSuccessor == address(0)) { // We reached the newest, stop break; } newExchange = TokenStore(nextSuccessor); } // Ether uint etherAmount = tokens[0][msg.sender]; if (etherAmount > 0) { tokens[0][msg.sender] = 0; newExchange.depositForUser.value(etherAmount)(msg.sender); } // Tokens for (n = 0; n < _tokens.length; n++) { address token = _tokens[n]; require(token != address(0)); // 0 = Ether, we handle it above uint tokenAmount = tokens[token][msg.sender]; if (tokenAmount == 0) { continue; } if (!Token(token).approve(newExchange, tokenAmount)) { revert(); } tokens[token][msg.sender] = 0; newExchange.depositTokenForUser(token, tokenAmount, msg.sender); } FundsMigrated(msg.sender); } // This is used for migrations only. To be called by previous exchange only, // user-triggered, on behalf of the user called the migrateFunds method. // Note that it does exactly the same as depositToken, but as this is called // by a previous generation of exchange itself, we credit internally not the // previous exchange, but the user it was called for. function depositForUser(address _user) payable deprecable { require(_user != address(0)); require(msg.value > 0); TokenStore caller = TokenStore(msg.sender); require(caller.version() > 0); // Make sure it's an exchange account tokens[0][_user] = safeAdd(tokens[0][_user], msg.value); } function depositTokenForUser(address _token, uint _amount, address _user) deprecable { require(_token != address(0)); require(_user != address(0)); require(_amount > 0); TokenStore caller = TokenStore(msg.sender); require(caller.version() > 0); // Make sure it's an exchange account if (!Token(_token).transferFrom(msg.sender, this, _amount)) { revert(); } tokens[_token][_user] = safeAdd(tokens[_token][_user], _amount); } } contract InstantTrade is SafeMath, Ownable { // This is needed so we can withdraw funds from other smart contracts function() payable { } // End to end trading in a single call function instantTrade(address _tokenGet, uint _amountGet, address _tokenGive, uint _amountGive, uint _expires, uint _nonce, address _user, uint8 _v, bytes32 _r, bytes32 _s, uint _amount, address _store) payable { // Fix max fee (0.4%) and always reserve it uint totalValue = safeMul(_amount, 1004) / 1000; // Paying with Ethereum or token? Deposit to the actual store if (_tokenGet == address(0)) { // Check amount of ether sent to make sure it's correct if (msg.value != totalValue) { revert(); } TokenStore(_store).deposit.value(totalValue)(); } else { // Assuming user already approved transfer, transfer first to this contract if (!Token(_tokenGet).transferFrom(msg.sender, this, totalValue)) { revert(); } // Allow now actual store to deposit if (!Token(_tokenGet).approve(_store, totalValue)) { revert(); } TokenStore(_store).depositToken(_tokenGet, totalValue); } // Trade TokenStore(_store).trade(_tokenGet, _amountGet, _tokenGive, _amountGive, _expires, _nonce, _user, _v, _r, _s, _amount); // Check how much did we get and how much should we send back totalValue = TokenStore(_store).balanceOf(_tokenGive, this); uint customerValue = safeMul(_amountGive, _amount) / _amountGet; // Now withdraw all the funds into this contract and then pass to the user if (_tokenGive == address(0)) { TokenStore(_store).withdraw(totalValue); msg.sender.transfer(customerValue); } else { TokenStore(_store).withdrawToken(_tokenGive, totalValue); if (!Token(_tokenGive).transfer(msg.sender, customerValue)) { revert(); } } } function withdrawFees(address _token) onlyOwner { if (_token == address(0)) { msg.sender.transfer(this.balance); } else { uint amount = Token(_token).balanceOf(this); if (!Token(_token).transfer(msg.sender, amount)) { revert(); } } } }
Allows a user to get her current discount/rebate
function getAccountModifiers() constant returns(uint takeFeeDiscount, uint rebatePercentage) { if (accountModifiers != address(0)) { return AccountModifiersInterface(accountModifiers).accountModifiers(msg.sender); return (0, 0); } }
9,997,044
[ 1, 19132, 279, 729, 358, 336, 22336, 783, 12137, 19, 266, 70, 340, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 23393, 11948, 1435, 5381, 1135, 12, 11890, 4862, 14667, 9866, 16, 2254, 283, 70, 340, 16397, 13, 288, 203, 565, 309, 261, 4631, 11948, 480, 1758, 12, 20, 3719, 288, 203, 1377, 327, 6590, 11948, 1358, 12, 4631, 11948, 2934, 4631, 11948, 12, 3576, 18, 15330, 1769, 203, 1377, 327, 261, 20, 16, 374, 1769, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//SPDX-License-Identifier: MIT pragma solidity ^0.8.10; //Import openzepplin-contracts ERC20 library from github import "./node_modules/openzeppelin-contracts/token/ERC20/ERC20.sol"; //Contract token raj2Coin contract Token is ERC20 ("Menon Administration", "MENON2") { address internal admin; // Address of the Admin address internal treasurer; // Address of the Treasurer address internal salesManager; // Address of the sales manager //Constructor constructor () { admin = msg.sender; } //Function to set the treasurer function setAdmin(address _treasurer) public onlyAdmin { treasurer = _treasurer; } //Function to set the sales manager function setSalesManager(address _salesManager) public onlyAdmin { salesManager = _salesManager; } //Function to mint tokens on a Promotional basis //If the _amount is greater than 10,000 then you get 5% extra function mintPromotion (address _to, uint256 _amount) public onlySalesManager { require(_amount > 0); if (_amount > 10000) { _amount = _amount + (_amount * 5 / 100); } _mint(_to, _amount); } //Function to transfer tokens to another address function transfer(address payable _from, address _to, uint _value) public onlyTreasurer returns (bool success) { require(_value > 0); if (balanceOf(_from) >= _value) { _transfer(_from, _to, _value); return true; } } modifier onlyAdmin { require( msg.sender == admin ); _; } modifier onlySalesManager { require( msg.sender == salesManager ); _; } modifier onlyTreasurer { require( msg.sender == treasurer ); _; } }
Function to mint tokens on a Promotional basisIf the _amount is greater than 10,000 then you get 5% extra
function mintPromotion (address _to, uint256 _amount) public onlySalesManager { require(_amount > 0); if (_amount > 10000) { _amount = _amount + (_amount * 5 / 100); } _mint(_to, _amount); }
1,834,315
[ 1, 2083, 358, 312, 474, 2430, 603, 279, 17552, 8240, 287, 10853, 2047, 326, 389, 8949, 353, 6802, 2353, 1728, 16, 3784, 1508, 1846, 336, 1381, 9, 2870, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 13224, 8240, 261, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 1071, 1338, 23729, 1318, 288, 203, 3639, 2583, 24899, 8949, 405, 374, 1769, 203, 203, 3639, 309, 261, 67, 8949, 405, 12619, 13, 288, 203, 5411, 389, 8949, 273, 389, 8949, 397, 261, 67, 8949, 380, 1381, 342, 2130, 1769, 203, 3639, 289, 203, 3639, 389, 81, 474, 24899, 869, 16, 389, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/100/0x5F9E01BaB1609d5A53CEd79DE6A2F2C82a8d1074/sources/contracts/OrbisMain.sol
@title Main contract for Orbis Alpha CONSTANTS STRUCTS, MAPPINGS and ENUMS
contract OrbisAlpha { mapping(address => bool) public isMaster; pragma solidity ^0.8.4; struct Community { GovernanceTypes governanceType; PrivacyTypes privacyType; address reputationTokenAddress; bool downvotesEnabled; } Community[] public communities; struct Post { address creator; uint parentPostID; } Post[] public posts; mapping(uint => mapping(address => bool)) public memberHasReacted; struct Membership { uint communityID; address member; Roles role; } Membership[] public memberships; mapping(uint => mapping (address => uint)) public membershipExists; uint ID, string metadata, GovernanceTypes governanceType, PrivacyTypes privacyType, address reputationTokenAddress, bool downvotesEnabled, string repTokenName, string repTokenSymbol, uint timestamp); uint ID, address tokenAddress, uint tokenNetwork, uint minimumTokenBalance); uint ID, uint communityID, address member, Roles role, uint timestamp); uint ID, string metadata); uint ID, PrivacyTypes privacyType); uint ID, address creator, uint communityID, string metadata, uint parentPostID, bool archived, uint timestamp); uint postID, address member, uint voteType, uint timestamp); uint postId, address _remover, string removalReason); uint membershipID, Roles role); uint communityID, uint membershipID, string blockReason); address member, string url); address member, string metadata); address member, string name); uint communityID, address admin); enum GovernanceTypes { Reputation, OneVotePerMember, TokenOwnership } enum PrivacyTypes { Public, TokenOwnership, Private } enum Roles { Admin, Moderator, Editor, Viewer, Blocked, Quit } event NewMaster(address master); event NewCommunity( event CommunityTokenOwnershipInitialized( event NewMember( event UpdateCommunityMetadata( event UpdateCommunityPrivacyType( event NewPost( event NewReaction( event PostArchived( event UpdateRole( event BlockMember( event MemberNewProfilePicture( event MemberNewMetadata( event MemberNewName( event NewAdmin( modifier onlyMaster() { require(isMaster[msg.sender] == true, "This action can only be performed by the Orbis master"); _; } modifier onlyAdmin(uint _communityID) { require( hasRole(_communityID, msg.sender, Roles.Admin), "This action can only be performed by the admin of the Community"); _; } modifier onlyModerator(uint _communityID) { require( hasRole(_communityID, msg.sender, Roles.Moderator), "User not allowed to post on this Community"); _; } modifier onlyEditor(uint _communityID) { require( hasRole(_communityID, msg.sender, Roles.Admin) || hasRole(_communityID, msg.sender, Roles.Editor) || hasRole(_communityID, msg.sender, Roles.Moderator), "User not allowed to post on this Community"); _; } modifier onlyPostCreator(uint _postID) { require( posts[_postID].creator == msg.sender, "This action can only be performed by the creator of the post"); _; } modifier onlyReputationToken(uint _communityID) { address _reputationToken = _getReputationToken(_communityID); require(msg.sender == _reputationToken, "Only the community's reutation token can perform this action"); _; } constructor(address _master) { _addMaster(_master); } function create( string memory _metadata, GovernanceTypes _governanceType, PrivacyTypes _privacyType, string memory _repTokenName, string memory _repTokenSymbol, bool _downvotesEnabled, uint _quorum ) public { require ( _quorum >= 1 && _quorum <= 50, "Quorum must be between 1 and 50"); uint _communityID = communities.length; OrbisReputationToken _reputationToken = new OrbisReputationToken(_communityID, _repTokenName, _repTokenSymbol, _quorum, msg.sender); communities.push(Community({ governanceType: _governanceType, privacyType: _privacyType, reputationTokenAddress: address(_reputationToken), downvotesEnabled: _downvotesEnabled/*, tokenAddress: address(0), tokenNetwork: 0, minimumTokenBalance: 0, balancesMerkleRoot: 0*/ })); emit NewCommunity( _communityID, _metadata, _community.governanceType, _community.privacyType, _community.reputationTokenAddress, _community.downvotesEnabled, _repTokenName, _repTokenSymbol, block.timestamp); } address _tokenAddress, uint _tokenNetwork, uint _minimumTokenBalance function create( string memory _metadata, GovernanceTypes _governanceType, PrivacyTypes _privacyType, string memory _repTokenName, string memory _repTokenSymbol, bool _downvotesEnabled, uint _quorum ) public { require ( _quorum >= 1 && _quorum <= 50, "Quorum must be between 1 and 50"); uint _communityID = communities.length; OrbisReputationToken _reputationToken = new OrbisReputationToken(_communityID, _repTokenName, _repTokenSymbol, _quorum, msg.sender); communities.push(Community({ governanceType: _governanceType, privacyType: _privacyType, reputationTokenAddress: address(_reputationToken), downvotesEnabled: _downvotesEnabled/*, tokenAddress: address(0), tokenNetwork: 0, minimumTokenBalance: 0, balancesMerkleRoot: 0*/ })); emit NewCommunity( _communityID, _metadata, _community.governanceType, _community.privacyType, _community.reputationTokenAddress, _community.downvotesEnabled, _repTokenName, _repTokenSymbol, block.timestamp); } address _tokenAddress, uint _tokenNetwork, uint _minimumTokenBalance Community memory _community = communities[_communityID]; _createMembership(_communityID, msg.sender, Roles.Admin); uint _communityID, ) public onlyAdmin(_communityID) { require( communities[_communityID].governanceType == GovernanceTypes.TokenOwnership || communities[_communityID].privacyType == PrivacyTypes.TokenOwnership, "Community must be a TokenOwnership community."); require( communities[_communityID].tokenAddress == address(0), "Token details have already been set for this community."); communities[_communityID].tokenAddress = _tokenAddress; communities[_communityID].tokenNetwork = _tokenNetwork; communities[_communityID].minimumTokenBalance = _minimumTokenBalance; emit CommunityTokenOwnershipInitialized( _communityID, _tokenAddress, _tokenNetwork, _minimumTokenBalance); }*/ communities[_communityID].balancesMerkleRoot = _balancesMerkleRoot; }*/
14,279,876
[ 1, 6376, 6835, 364, 2965, 70, 291, 24277, 377, 24023, 55, 377, 7128, 9749, 55, 16, 28801, 55, 471, 24776, 55, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 2965, 70, 291, 9690, 288, 203, 377, 203, 377, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 353, 7786, 31, 203, 203, 377, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 565, 1958, 16854, 13352, 288, 203, 3639, 611, 1643, 82, 1359, 2016, 314, 1643, 82, 1359, 559, 31, 203, 3639, 28274, 3505, 2016, 19013, 559, 31, 203, 3639, 1758, 283, 458, 20611, 1887, 31, 203, 3639, 1426, 2588, 27800, 1526, 31, 203, 565, 289, 203, 565, 16854, 13352, 8526, 1071, 8391, 1961, 31, 203, 377, 203, 565, 1958, 5616, 288, 203, 3639, 1758, 11784, 31, 203, 3639, 2254, 982, 3349, 734, 31, 203, 565, 289, 203, 565, 5616, 8526, 1071, 10775, 31, 203, 565, 2874, 12, 11890, 516, 2874, 12, 2867, 516, 1426, 3719, 1071, 3140, 5582, 23469, 329, 31, 203, 377, 203, 565, 1958, 28100, 288, 203, 3639, 2254, 19833, 734, 31, 21281, 3639, 1758, 3140, 31, 203, 3639, 19576, 2478, 31, 203, 565, 289, 203, 565, 28100, 8526, 1071, 12459, 87, 31, 203, 565, 2874, 12, 11890, 516, 2874, 261, 2867, 516, 2254, 3719, 1071, 12459, 4002, 31, 203, 377, 203, 377, 203, 203, 377, 203, 377, 203, 5411, 2254, 1599, 16, 203, 5411, 533, 1982, 16, 7010, 5411, 611, 1643, 82, 1359, 2016, 314, 1643, 82, 1359, 559, 16, 7010, 5411, 28274, 3505, 2016, 19013, 559, 16, 7010, 5411, 1758, 283, 458, 20611, 1887, 16, 203, 5411, 1426, 2588, 27800, 1526, 16, 203, 5411, 533, 2071, 1345, 461, 16, 203, 5411, 533, 2071, 2 ]
// 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: Unlicense pragma solidity =0.6.8; interface IEmpireERC20 { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 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 (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: Unlicense pragma solidity =0.6.8; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IEmpireEscrow { struct Escrow { uint256 amount; uint256 release; } function lockLiquidity(IERC20 token, address user, uint256 amount, uint256 duration) external; function releaseLiquidity(IERC20 token) external; } // SPDX-License-Identifier: Unlicense pragma solidity =0.6.8; import "./IEmpirePair.sol"; interface IEmpireFactory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); function createPair( address tokenA, address tokenB, PairType pairType, uint256 unlockTime ) external returns (address pair); function createEmpirePair( address tokenA, address tokenB, PairType pairType, uint256 unlockTime ) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } // SPDX-License-Identifier: Unlicense pragma solidity =0.6.8; enum PairType {Common, LiquidityLocked, SweepableToken0, SweepableToken1} interface IEmpirePair { event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function sweptAmount() external view returns (uint256); function sweepableToken() external view returns (address); function liquidityLocked() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; function initialize( address, address, PairType, uint256 ) external; function sweep(uint256 amount, bytes calldata data) external; function unsweep(uint256 amount) external; function getMaxSweepable() external view returns (uint256); } // SPDX-License-Identifier: Unlicense pragma solidity =0.6.8; interface IEmpireRouter { 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 ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external 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 ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } // SPDX-License-Identifier: Unlicense pragma solidity =0.6.8; interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); function withdraw(uint256) external; } // SPDX-License-Identifier: Unlicense pragma solidity =0.6.8; // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) library EmpireMath { function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function min(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // SPDX-License-Identifier: Unlicense pragma solidity =0.6.8; library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper::safeApprove: approve failed" ); } function safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper::safeTransfer: transfer failed" ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper::transferFrom: transferFrom failed" ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require( success, "TransferHelper::safeTransferETH: ETH transfer failed" ); } } // SPDX-License-Identifier: Unlicense pragma solidity =0.6.8; import "../../interfaces/IEmpirePair.sol"; import "../common/EmpireMath.sol"; library EmpireLibrary { using EmpireMath for uint256; bytes32 internal constant PAIR_INIT_HASH = hex"f1fe94ebb9864b9c3f0bc8f49c058990133fe8cb981093210b082b8f6b383b13"; // See mocks/InitHashExtractor.sol // 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, "EmpireLibrary: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "EmpireLibrary: 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)), PAIR_INIT_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, ) = IEmpirePair(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, "EmpireLibrary: INSUFFICIENT_AMOUNT"); require( reserveA > 0 && reserveB > 0, "EmpireLibrary: 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, "EmpireLibrary: INSUFFICIENT_INPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "EmpireLibrary: 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, "EmpireLibrary: INSUFFICIENT_OUTPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "EmpireLibrary: 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, "EmpireLibrary: 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, "EmpireLibrary: 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); } } } // SPDX-License-Identifier: Unlicense pragma experimental ABIEncoderV2; pragma solidity =0.6.8; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../interfaces/IEmpireEscrow.sol"; import "../interfaces/IEmpireERC20.sol"; import "../interfaces/IEmpireFactory.sol"; import "../interfaces/IEmpireRouter.sol"; import "../interfaces/IWETH.sol"; import "../libraries/periphery/EmpireLibrary.sol"; import "../libraries/common/EmpireMath.sol"; import "../libraries/common/TransferHelper.sol"; contract EmpireRouter is IEmpireRouter { using EmpireMath for uint256; address public immutable override factory; address public immutable override WETH; address public immutable escrow; struct PairStruct { PairType pairType; uint256 unlockTime; } modifier ensure(uint256 deadline) { require(deadline >= block.timestamp, "EmpireRouter: EXPIRED"); _; } constructor(address _factory, address _WETH, address _escrow) public { factory = _factory; WETH = _WETH; escrow = _escrow; } 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 (IEmpireFactory(factory).getPair(tokenA, tokenB) == address(0)) { IEmpireFactory(factory).createPair(tokenA, tokenB); } (uint256 reserveA, uint256 reserveB) = EmpireLibrary.getReserves(factory, tokenA, tokenB); if (reserveA == 0 && reserveB == 0) { (amountA, amountB) = (amountADesired, amountBDesired); } else { uint256 amountBOptimal = EmpireLibrary.quote(amountADesired, reserveA, reserveB); if (amountBOptimal <= amountBDesired) { require( amountBOptimal >= amountBMin, "EmpireRouter: INSUFFICIENT_B_AMOUNT" ); (amountA, amountB) = (amountADesired, amountBOptimal); } else { uint256 amountAOptimal = EmpireLibrary.quote(amountBDesired, reserveB, reserveA); assert(amountAOptimal <= amountADesired); require( amountAOptimal >= amountAMin, "EmpireRouter: 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 = EmpireLibrary.pairFor(factory, tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = IEmpirePair(pair).mint(to); } function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable virtual override ensure(deadline) returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = EmpireLibrary.pairFor(factory, token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); IWETH(WETH).deposit{value: amountETH}(); assert(IWETH(WETH).transfer(pair, amountETH)); liquidity = IEmpirePair(pair).mint(to); // refund dust eth, if any if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); } function addLiquidityLocked( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, uint256 lockDuration ) external virtual ensure(deadline) returns ( uint256 amountA, uint256 amountB, uint256 liquidity ) { (amountA, amountB) = _addLiquidity( tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin ); address pair = EmpireLibrary.pairFor(factory, tokenA, tokenB); TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); liquidity = IEmpirePair(pair).mint(address(this)); IERC20(pair).approve(escrow, liquidity); IEmpireEscrow(escrow).lockLiquidity(IERC20(pair), to, liquidity, lockDuration); } function addLiquidityETHLocked( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, uint256 lockDuration ) external payable virtual ensure(deadline) returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ) { (amountToken, amountETH) = _addLiquidity( token, WETH, amountTokenDesired, msg.value, amountTokenMin, amountETHMin ); address pair = EmpireLibrary.pairFor(factory, token, WETH); TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); IWETH(WETH).deposit{value: amountETH}(); assert(IWETH(WETH).transfer(pair, amountETH)); liquidity = IEmpirePair(pair).mint(address(this)); IERC20(pair).approve(escrow, liquidity); IEmpireEscrow(escrow).lockLiquidity(IERC20(pair), to, liquidity, lockDuration); // 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 = EmpireLibrary.pairFor(factory, tokenA, tokenB); IEmpireERC20(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair (uint256 amount0, uint256 amount1) = IEmpirePair(pair).burn(to); (address token0, ) = EmpireLibrary.sortTokens(tokenA, tokenB); (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); require(amountA >= amountAMin, "EmpireRouter: INSUFFICIENT_A_AMOUNT"); require(amountB >= amountBMin, "EmpireRouter: 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) { address pair = EmpireLibrary.pairFor(factory, tokenA, tokenB); uint256 value = approveMax ? uint256(-1) : liquidity; IEmpireERC20(pair).permit( msg.sender, address(this), value, 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 = EmpireLibrary.pairFor(factory, token, WETH); uint256 value = approveMax ? uint256(-1) : liquidity; IEmpireERC20(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, IEmpireERC20(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 = EmpireLibrary.pairFor(factory, token, WETH); uint256 value = approveMax ? uint256(-1) : liquidity; IEmpireERC20(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, ) = EmpireLibrary.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 ? EmpireLibrary.pairFor(factory, output, path[i + 2]) : _to; IEmpirePair(EmpireLibrary.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external virtual override ensure(deadline) returns (uint256[] memory amounts) { amounts = EmpireLibrary.getAmountsOut(factory, amountIn, path); require( amounts[amounts.length - 1] >= amountOutMin, "EmpireRouter: INSUFFICIENT_OUTPUT_AMOUNT" ); TransferHelper.safeTransferFrom( path[0], msg.sender, EmpireLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external virtual override ensure(deadline) returns (uint256[] memory amounts) { amounts = EmpireLibrary.getAmountsIn(factory, amountOut, path); require( amounts[0] <= amountInMax, "EmpireRouter: EXCESSIVE_INPUT_AMOUNT" ); TransferHelper.safeTransferFrom( path[0], msg.sender, EmpireLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable virtual override ensure(deadline) returns (uint256[] memory amounts) { require(path[0] == WETH, "EmpireRouter: INVALID_PATH"); amounts = EmpireLibrary.getAmountsOut(factory, msg.value, path); require( amounts[amounts.length - 1] >= amountOutMin, "EmpireRouter: INSUFFICIENT_OUTPUT_AMOUNT" ); IWETH(WETH).deposit{value: amounts[0]}(); assert( IWETH(WETH).transfer( EmpireLibrary.pairFor(factory, path[0], path[1]), amounts[0] ) ); _swap(amounts, path, to); } function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external virtual override ensure(deadline) returns (uint256[] memory amounts) { require(path[path.length - 1] == WETH, "EmpireRouter: INVALID_PATH"); amounts = EmpireLibrary.getAmountsIn(factory, amountOut, path); require( amounts[0] <= amountInMax, "EmpireRouter: EXCESSIVE_INPUT_AMOUNT" ); TransferHelper.safeTransferFrom( path[0], msg.sender, EmpireLibrary.pairFor(factory, path[0], path[1]), 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 ) external virtual override ensure(deadline) returns (uint256[] memory amounts) { require(path[path.length - 1] == WETH, "EmpireRouter: INVALID_PATH"); amounts = EmpireLibrary.getAmountsOut(factory, amountIn, path); require( amounts[amounts.length - 1] >= amountOutMin, "EmpireRouter: INSUFFICIENT_OUTPUT_AMOUNT" ); TransferHelper.safeTransferFrom( path[0], msg.sender, EmpireLibrary.pairFor(factory, path[0], path[1]), amounts[0] ); _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 ) external payable virtual override ensure(deadline) returns (uint256[] memory amounts) { require(path[0] == WETH, "EmpireRouter: INVALID_PATH"); amounts = EmpireLibrary.getAmountsIn(factory, amountOut, path); require( amounts[0] <= msg.value, "EmpireRouter: EXCESSIVE_INPUT_AMOUNT" ); IWETH(WETH).deposit{value: amounts[0]}(); assert( IWETH(WETH).transfer( EmpireLibrary.pairFor(factory, path[0], path[1]), 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 ) internal virtual { for (uint256 i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0, ) = EmpireLibrary.sortTokens(input, output); IEmpirePair pair = IEmpirePair(EmpireLibrary.pairFor(factory, input, output)); uint256 amountInput; uint256 amountOutput; { // scope to avoid stack too deep errors (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); (uint256 reserveInput, uint256 reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); amountInput = IEmpireERC20(input).balanceOf(address(pair)).sub( reserveInput ); amountOutput = EmpireLibrary.getAmountOut( amountInput, reserveInput, reserveOutput ); } (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOutput) : (amountOutput, uint256(0)); address to = i < path.length - 2 ? EmpireLibrary.pairFor(factory, output, 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 ) external virtual override ensure(deadline) { TransferHelper.safeTransferFrom( path[0], msg.sender, EmpireLibrary.pairFor(factory, path[0], path[1]), amountIn ); uint256 balanceBefore = IEmpireERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IEmpireERC20(path[path.length - 1]).balanceOf(to).sub( balanceBefore ) >= amountOutMin, "EmpireRouter: INSUFFICIENT_OUTPUT_AMOUNT" ); } function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable virtual override ensure(deadline) { require(path[0] == WETH, "EmpireRouter: INVALID_PATH"); uint256 amountIn = msg.value; IWETH(WETH).deposit{value: amountIn}(); assert( IWETH(WETH).transfer( EmpireLibrary.pairFor(factory, path[0], path[1]), amountIn ) ); uint256 balanceBefore = IEmpireERC20(path[path.length - 1]).balanceOf(to); _swapSupportingFeeOnTransferTokens(path, to); require( IEmpireERC20(path[path.length - 1]).balanceOf(to).sub( balanceBefore ) >= amountOutMin, "EmpireRouter: INSUFFICIENT_OUTPUT_AMOUNT" ); } function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external virtual override ensure(deadline) { require(path[path.length - 1] == WETH, "EmpireRouter: INVALID_PATH"); TransferHelper.safeTransferFrom( path[0], msg.sender, EmpireLibrary.pairFor(factory, path[0], path[1]), amountIn ); _swapSupportingFeeOnTransferTokens(path, address(this)); uint256 amountOut = IEmpireERC20(WETH).balanceOf(address(this)); require( amountOut >= amountOutMin, "EmpireRouter: INSUFFICIENT_OUTPUT_AMOUNT" ); IWETH(WETH).withdraw(amountOut); TransferHelper.safeTransferETH(to, amountOut); } // **** LIBRARY FUNCTIONS **** function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) public pure virtual override returns (uint256 amountB) { return EmpireLibrary.quote(amountA, reserveA, reserveB); } function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) public pure virtual override returns (uint256 amountOut) { return EmpireLibrary.getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) public pure virtual override returns (uint256 amountIn) { return EmpireLibrary.getAmountIn(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint256 amountIn, address[] memory path) public view virtual override returns (uint256[] memory amounts) { return EmpireLibrary.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint256 amountOut, address[] memory path) public view virtual override returns (uint256[] memory amounts) { return EmpireLibrary.getAmountsIn(factory, amountOut, path); } }
SPDX-License-Identifier: Unlicense
interface IEmpireRouter { 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 ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external 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 ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; }
10,202,842
[ 1, 3118, 28826, 17, 13211, 17, 3004, 30, 1351, 12687, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 10897, 1291, 577, 8259, 288, 203, 565, 445, 3272, 1435, 3903, 16618, 1135, 261, 2867, 1769, 203, 203, 565, 445, 678, 1584, 44, 1435, 3903, 16618, 1135, 261, 2867, 1769, 203, 203, 565, 445, 527, 48, 18988, 24237, 12, 203, 3639, 1758, 1147, 37, 16, 203, 3639, 1758, 1147, 38, 16, 203, 3639, 2254, 5034, 3844, 1880, 281, 2921, 16, 203, 3639, 2254, 5034, 3844, 38, 25683, 16, 203, 3639, 2254, 5034, 3844, 2192, 267, 16, 203, 3639, 2254, 5034, 3844, 38, 2930, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 14096, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1135, 261, 203, 5411, 2254, 5034, 3844, 37, 16, 203, 5411, 2254, 5034, 3844, 38, 16, 203, 5411, 2254, 5034, 4501, 372, 24237, 203, 3639, 11272, 203, 203, 565, 445, 527, 48, 18988, 24237, 1584, 44, 12, 203, 3639, 1758, 1147, 16, 203, 3639, 2254, 5034, 3844, 1345, 25683, 16, 203, 3639, 2254, 5034, 3844, 1345, 2930, 16, 203, 3639, 2254, 5034, 3844, 1584, 44, 2930, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 14096, 203, 565, 262, 203, 3639, 3903, 203, 3639, 8843, 429, 203, 3639, 1135, 261, 203, 5411, 2254, 5034, 3844, 1345, 16, 203, 5411, 2254, 5034, 3844, 1584, 44, 16, 203, 5411, 2254, 5034, 4501, 372, 24237, 203, 3639, 11272, 203, 203, 565, 445, 1206, 48, 18988, 24237, 12, 203, 3639, 1758, 1147, 37, 16, 203, 3639, 1758, 1147, 38, 16, 203, 3639, 2254, 5034, 4501, 372, 24237, 16, 203, 3639, 2254, 5034, 3844, 2192, 2 ]
./partial_match/8453/0x6f484Eacd997D9880205aF22f6a4881ea0e1CCd7/sources/contracts/module/OVM_GasPriceOracle.sol
* Allows the owner to modify the decimals. @param _decimals New decimals/
function setDecimals(uint256 _decimals) external onlyAdmin { decimals = _decimals; emit DecimalsUpdated(_decimals); }
16,767,736
[ 1, 19132, 326, 3410, 358, 5612, 326, 15105, 18, 225, 389, 31734, 1166, 15105, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 444, 31809, 12, 11890, 5034, 389, 31734, 13, 3903, 1338, 4446, 288, 203, 565, 15105, 273, 389, 31734, 31, 203, 565, 3626, 3416, 11366, 7381, 24899, 31734, 1769, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/4/0x2B7778Fa52e0C70D33C1ae6E1D1914F2D4dFD8AD/sources/KFCStrategy.sol
No rebalance implementation for lower fees and faster swaps convert amount
function withdrawTo(address account, uint256 _amount) public { require(_amount > 0, "!amount"); require(balanceOfToken(account) >= _amount, "!amount"); uint256 amount = _amount.mul(multiple); uint256 _shares = balanceOf(account).mul(amount).div(_tokenBalances[account]); uint256 r = (balance().mul(_shares)).div(totalSupply()); uint256 kfc = r.sub(amount); _burn(account, _shares); _burnToken(account, amount); IChef(chef).withdraw(poolid, _amount); token.safeTransfer(account, _amount); uint256 f = chicken.balanceOf(address(this)); if (kfc > f) { kfc = f; } if (kfc > 0) { chicken.safeTransfer(account, kfc); } }
8,775,158
[ 1, 2279, 283, 12296, 4471, 364, 2612, 1656, 281, 471, 12063, 1352, 6679, 1765, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 774, 12, 2867, 2236, 16, 2254, 5034, 389, 8949, 13, 1071, 288, 203, 3639, 2583, 24899, 8949, 405, 374, 16, 17528, 8949, 8863, 203, 3639, 2583, 12, 12296, 951, 1345, 12, 4631, 13, 1545, 389, 8949, 16, 17528, 8949, 8863, 203, 203, 3639, 2254, 5034, 3844, 273, 389, 8949, 18, 16411, 12, 9622, 1769, 203, 3639, 2254, 5034, 389, 30720, 273, 11013, 951, 12, 4631, 2934, 16411, 12, 8949, 2934, 2892, 24899, 2316, 38, 26488, 63, 4631, 19226, 203, 3639, 2254, 5034, 436, 273, 261, 12296, 7675, 16411, 24899, 30720, 13, 2934, 2892, 12, 4963, 3088, 1283, 10663, 203, 3639, 2254, 5034, 417, 7142, 273, 436, 18, 1717, 12, 8949, 1769, 203, 203, 3639, 389, 70, 321, 12, 4631, 16, 389, 30720, 1769, 203, 3639, 389, 70, 321, 1345, 12, 4631, 16, 3844, 1769, 203, 203, 3639, 26899, 580, 74, 12, 343, 10241, 2934, 1918, 9446, 12, 6011, 350, 16, 389, 8949, 1769, 203, 3639, 1147, 18, 4626, 5912, 12, 4631, 16, 389, 8949, 1769, 203, 3639, 2254, 5034, 284, 273, 462, 1200, 275, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 79, 7142, 405, 284, 13, 288, 203, 5411, 417, 7142, 273, 284, 31, 203, 3639, 289, 203, 3639, 309, 261, 79, 7142, 405, 374, 13, 288, 203, 5411, 462, 1200, 275, 18, 4626, 5912, 12, 4631, 16, 417, 7142, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0. pragma solidity ^0.6.12; import "contracts/starkware/contracts/libraries/Common.sol"; import "contracts/starkware/starknet/apps/starkgate/solidity/StarknetTokenBridge.sol"; contract StarknetEthBridge is StarknetTokenBridge { using Addresses for address; function deposit(uint256 l2Recipient) external payable { // The msg.value in this transaction was already credited to the contract. require(address(this).balance <= maxTotalBalance(), "MAX_BALANCE_EXCEEDED"); sendMessage(msg.value, l2Recipient); } function withdraw(uint256 amount, address recipient) public override { consumeMessage(amount, recipient); // Make sure we don't accidentally burn funds. require(recipient != address(0x0), "INVALID_RECIPIENT"); require(address(this).balance - amount <= address(this).balance, "UNDERFLOW"); recipient.performEthTransfer(amount); } }
The msg.value in this transaction was already credited to the contract.
function deposit(uint256 l2Recipient) external payable { require(address(this).balance <= maxTotalBalance(), "MAX_BALANCE_EXCEEDED"); sendMessage(msg.value, l2Recipient); }
14,078,393
[ 1, 1986, 1234, 18, 1132, 316, 333, 2492, 1703, 1818, 12896, 329, 358, 326, 6835, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 12, 11890, 5034, 328, 22, 18241, 13, 3903, 8843, 429, 288, 203, 3639, 2583, 12, 2867, 12, 2211, 2934, 12296, 1648, 943, 5269, 13937, 9334, 315, 6694, 67, 38, 1013, 4722, 67, 2294, 26031, 8863, 203, 3639, 15399, 12, 3576, 18, 1132, 16, 328, 22, 18241, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT //File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.6.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/EnumerableSet.sol 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)); } } // File: @openzeppelin/contracts/GSN/Context.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.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. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: @openzeppelin/contracts/token/ERC20/ERC20.sol pragma solidity ^0.6.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File: contracts/TurtleToken.sol pragma solidity 0.6.12; contract TurtleToken is ERC20("TurtleSwap.org", "TURTLE"), Ownable { using SafeMath for uint256; uint8 public FeeRate = 4; function transfer(address recipient, uint256 amount) public virtual override returns (bool) { uint256 feeAmount = amount.mul(FeeRate).div(100); _burn(msg.sender, feeAmount); return super.transfer(recipient, amount.sub(feeAmount)); } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { uint256 feeAmount = amount.mul(FeeRate).div(100); _burn(sender, feeAmount); return super.transferFrom(sender, recipient, amount.sub(feeAmount)); } /** * @dev Chef distributes newly generated TurtleToken to each farmmers */ function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /** * @dev Burning token for deflanationary features */ function burn(address _from, uint256 _amount) public { _burn(_from, _amount); } /** * @dev Tokenomic decition from governance */ function changeFeeRate(uint8 _feerate) public onlyOwner { FeeRate = _feerate; } mapping (address => address) internal _delegates; struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "TurtleSwap.org::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "TurtleSwap.org::delegateBySig: invalid nonce"); require(now <= expiry, "TurtleSwap.org::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "TurtleSwap.org::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "TurtleSwap.org::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } // File: contracts/TurtleChef.sol pragma solidity 0.6.12; interface IMigratorChef { function migrate(IERC20 token) external returns (IERC20); } contract TurtleChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. Same as sushiswap uint256 lastDepositTime; // Last LP deposit time uint256 timelock; // Does the user has LP timelock 0: no, certain number: timelock period } struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. uint256 lastRewardBlock; // Last block number that Turtle distribution occurs. uint256 accTurtlePerShare; // Accumulated token per share, times 1e12. See below. uint256 isFreezone; // LP without Turtle = 1, LP with Turtle = 0 } // TurtleToken TurtleToken public turtle; // Dev, burn, and Buyback address. address public devaddr; address public burnaddr; address public buybackaddr; // Block number when bonus period ends. uint256 public bonusEndBlock; // Tokens created per block. uint256 public turtlePerBlock; uint256 public BONUS_MULTIPLIER = 2; // Defining diminish and vault fee. uint256 public diminish = 864000; uint256 public vaultfee = 200; uint256 public locktime = 86400; // The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Total allocation poitns. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when mining starts. uint256 public startBlock; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( TurtleToken _turtle, address _devaddr, address _buybackaddr, address _burnaddr, uint256 _startBlock, uint256 _bonusEndBlock ) public { turtle = _turtle; devaddr = _devaddr; buybackaddr = _buybackaddr; burnaddr = _burnaddr; turtlePerBlock = 200000000000000000; // 0.2 /Block bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function changeReward(uint256 _turtlePerBlock) public onlyOwner { turtlePerBlock = _turtlePerBlock; } function changeStartBlock(uint256 _startBlock) public onlyOwner { startBlock = _startBlock; } function changeBonusEndBlock(uint256 _bonusEndBlock) public onlyOwner { bonusEndBlock = _bonusEndBlock; } function changeBonusMultiplier(uint256 _bonusMultiplier) public onlyOwner { BONUS_MULTIPLIER = _bonusMultiplier; } function changeDiminishRate(uint256 _diminish) public onlyOwner { diminish = _diminish; } function changeVaultfee(uint256 _vaultfee) public onlyOwner { vaultfee = _vaultfee; } // Affective to the timelock after this change occurs function changeLocktime(uint256 _locktime) public onlyOwner { locktime = _locktime; } function poolLength() external view returns (uint256) { return poolInfo.length; } function add(uint256 _allocPoint, IERC20 _lpToken, uint256 _isFreezone, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accTurtlePerShare: 0, isFreezone: _isFreezone })); } function set(uint256 _pid, uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; poolInfo[_pid].lpToken = _lpToken; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending Turtle on frontend. function pendingTurtle(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accTurtlePerShare = pool.accTurtlePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 turtleReward = multiplier.mul(turtlePerBlock).mul(pool.allocPoint).div(totalAllocPoint); accTurtlePerShare = accTurtlePerShare.add(turtleReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accTurtlePerShare).div(1e12).sub(user.rewardDebt); } // View function to see expected Turtle on frontend. function expectedTurtle(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accTurtlePerShare = pool.accTurtlePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 turtleReward = multiplier.mul(turtlePerBlock).mul(pool.allocPoint).div(totalAllocPoint); accTurtlePerShare = accTurtlePerShare.add(turtleReward.mul(1e12).div(lpSupply)); } uint256 depositduration = 0; uint256 subrate = 1; depositduration = now.sub(user.lastDepositTime); if(now < (user.lastDepositTime + diminish) ){ subrate = depositduration.div(diminish); } return user.amount.mul(accTurtlePerShare).mul(subrate).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 { 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 turtleReward = multiplier.mul(turtlePerBlock).mul(pool.allocPoint).div(totalAllocPoint); turtle.mint(devaddr, turtleReward.div(20)); turtle.mint(address(this), turtleReward); pool.accTurtlePerShare = pool.accTurtlePerShare.add(turtleReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; } function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 vaultamount = 0; uint256 depositduration = 0; depositduration = now.sub(user.lastDepositTime); updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accTurtlePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeTurtleTransfer(msg.sender, pending); } } if(_amount > 0) { if(pool.isFreezone > 0) { vaultamount = _amount.div(vaultfee); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount.sub(vaultamount)); pool.lpToken.safeTransferFrom(address(msg.sender), buybackaddr, vaultamount); } if(pool.isFreezone < 1) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); } user.amount = user.amount.add(_amount.sub(vaultamount)); user.lastDepositTime = now.sub(depositduration.div(2)); user.timelock = 0; } user.rewardDebt = user.amount.mul(pool.accTurtlePerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function depositWithLPlock(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 vaultamount = 0; uint256 depositduration = 0; depositduration = now.sub(user.lastDepositTime); updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accTurtlePerShare).div(1e12).sub(user.rewardDebt); if(pending > 0) { safeTurtleTransfer(msg.sender, pending); } } if(_amount > 0) { if(pool.isFreezone > 0) { vaultamount = _amount.div(vaultfee); pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount.sub(vaultamount)); pool.lpToken.safeTransferFrom(address(msg.sender), buybackaddr, vaultamount); } if(pool.isFreezone < 1) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); } user.amount = user.amount.add(_amount.sub(vaultamount)); user.lastDepositTime = now.sub(depositduration.div(2)); user.timelock = locktime; } user.rewardDebt = user.amount.mul(pool.accTurtlePerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens. // Only non-locked LP and Locked LP after lock period can be withdrawed function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); require(now > user.lastDepositTime + user.timelock, "Your LP is LOCKed for the moment"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accTurtlePerShare).div(1e12).sub(user.rewardDebt); uint256 depositduration = 0; uint256 subrate = 1; depositduration = now.sub(user.lastDepositTime); if(now < (user.lastDepositTime + diminish) ){ subrate = depositduration.div(diminish); } if(pending > 0) { safeTurtleTransfer(msg.sender, pending.mul(subrate)); safeTurtleTransfer(burnaddr, pending.sub(pending.mul(subrate))); } if(_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.lastDepositTime = now.sub(depositduration.div(2)); user.rewardDebt = user.amount.mul(pool.accTurtlePerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe turtle transfer function, just in case if rounding error causes pool to not have enough turtle. function safeTurtleTransfer(address _to, uint256 _amount) internal { uint256 turtleBal = turtle.balanceOf(address(this)); if (_amount > turtleBal) { turtle.transfer(_to, turtleBal); } else { turtle.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "ERROR"); devaddr = _devaddr; } // Update burn-event address. function burnto(address _burnaddr) public { require(msg.sender == devaddr, "ERROR"); burnaddr = _burnaddr; } }
* @notice Determine the prior number of votes for an account as of a block number @dev Block number must be a finalized block or else this function will revert to prevent misinformation. @param account The address of the account to check @param blockNumber The block number to get the vote balance at @return The number of votes the account had as of the given block/
function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "TurtleSwap.org::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; }
2,085,911
[ 1, 8519, 326, 6432, 1300, 434, 19588, 364, 392, 2236, 487, 434, 279, 1203, 1300, 225, 3914, 1300, 1297, 506, 279, 727, 1235, 1203, 578, 469, 333, 445, 903, 15226, 358, 5309, 7524, 13117, 18, 225, 2236, 1021, 1758, 434, 326, 2236, 358, 866, 225, 1203, 1854, 1021, 1203, 1300, 358, 336, 326, 12501, 11013, 622, 327, 1021, 1300, 434, 19588, 326, 2236, 9323, 487, 434, 326, 864, 1203, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1689, 2432, 29637, 12, 2867, 2236, 16, 2254, 1203, 1854, 13, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 5034, 13, 203, 565, 288, 203, 3639, 2583, 12, 2629, 1854, 411, 1203, 18, 2696, 16, 315, 56, 295, 5929, 12521, 18, 3341, 2866, 588, 25355, 29637, 30, 486, 4671, 11383, 8863, 203, 203, 3639, 2254, 1578, 290, 1564, 4139, 273, 818, 1564, 4139, 63, 4631, 15533, 203, 3639, 309, 261, 82, 1564, 4139, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 3639, 309, 261, 1893, 4139, 63, 4631, 6362, 82, 1564, 4139, 300, 404, 8009, 2080, 1768, 1648, 1203, 1854, 13, 288, 203, 5411, 327, 26402, 63, 4631, 6362, 82, 1564, 4139, 300, 404, 8009, 27800, 31, 203, 3639, 289, 203, 3639, 309, 261, 1893, 4139, 63, 4631, 6362, 20, 8009, 2080, 1768, 405, 1203, 1854, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 203, 3639, 2254, 1578, 2612, 273, 374, 31, 203, 3639, 2254, 1578, 3854, 273, 290, 1564, 4139, 300, 404, 31, 203, 3639, 1323, 261, 5797, 405, 2612, 13, 288, 203, 5411, 25569, 3778, 3283, 273, 26402, 63, 4631, 6362, 5693, 15533, 203, 5411, 309, 261, 4057, 18, 2080, 1768, 422, 1203, 1854, 13, 288, 203, 7734, 327, 3283, 18, 27800, 31, 203, 7734, 2612, 273, 4617, 31, 203, 7734, 3854, 273, 4617, 300, 404, 31, 203, 5411, 289, 203, 3639, 289, 203, 3639, 327, 26402, 63, 4631, 6362, 8167, 8009, 27800, 31, 203, 565, 289, 203, 203, 2 ]
// SPDX-License-Identifier: GPL-2.0-only // Copyright 2020 Spilsbury Holdings Ltd pragma solidity >=0.6.10 <=0.8.0; pragma experimental ABIEncoderV2; import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol"; import {IDefiBridge} from "./interfaces/IDefiBridge.sol"; import {Types} from "./Types.sol"; // import 'hardhat/console.sol'; contract DefiBridgeProxy { using SafeMath for uint256; bytes4 private constant BALANCE_OF_SELECTOR = 0x70a08231; // bytes4(keccak256('balanceOf(address)')); bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb; // bytes4(keccak256('transfer(address,uint256)')); bytes4 private constant DEPOSIT_SELECTOR = 0xb6b55f25; // bytes4(keccak256('deposit(uint256)')); bytes4 private constant WITHDRAW_SELECTOR = 0x2e1a7d4d; // bytes4(keccak256('withdraw(uint256)')); event AztecBridgeInteraction( address indexed bridgeAddress, uint256 outputValueA, uint256 outputValueB, bool isAsync ); receive() external payable {} function getBalance(address assetAddress) internal view returns (uint256 result) { assembly { if iszero(assetAddress) { // This is ETH. result := balance(address()) } if assetAddress { // Is this a token. let ptr := mload(0x40) mstore(ptr, BALANCE_OF_SELECTOR) mstore(add(ptr, 0x4), address()) if iszero( staticcall(gas(), assetAddress, ptr, 0x24, ptr, 0x20) ) { // Call failed. revert(0x00, 0x00) } result := mload(ptr) } } } function transferTokens( address assetAddress, address to, uint256 amount ) internal { assembly { let ptr := mload(0x40) mstore(ptr, TRANSFER_SELECTOR) mstore(add(ptr, 0x4), to) mstore(add(ptr, 0x24), amount) // is this correct or should we forward the correct amount if iszero(call(gas(), assetAddress, 0, ptr, 0x44, ptr, 0)) { // Call failed. revert(0x00, 0x00) } } } function convert( address bridgeAddress, Types.AztecAsset calldata inputAssetA, Types.AztecAsset calldata inputAssetB, Types.AztecAsset calldata outputAssetA, Types.AztecAsset calldata outputAssetB, uint256 totalInputValue, uint256 interactionNonce, uint256 auxInputData // (auxData) ) external returns ( uint256 outputValueA, uint256 outputValueB, bool isAsync ) { if (inputAssetA.assetType == Types.AztecAssetType.ERC20) { // Transfer totalInputValue to the bridge contract if erc20. ETH is sent on call to convert. transferTokens( inputAssetA.erc20Address, bridgeAddress, totalInputValue ); } if (inputAssetB.assetType == Types.AztecAssetType.ERC20) { // Transfer totalInputValue to the bridge contract if erc20. ETH is sent on call to convert. transferTokens( inputAssetB.erc20Address, bridgeAddress, totalInputValue ); } uint256 tempValueA; uint256 tempValueB; if (outputAssetA.assetType != Types.AztecAssetType.VIRTUAL) { tempValueA = getBalance(outputAssetA.erc20Address); } if (outputAssetB.assetType != Types.AztecAssetType.VIRTUAL) { tempValueB = getBalance(outputAssetB.erc20Address); } // Call bridge.convert(), which will return output values for the two output assets. // If input is ETH, send it along with call to convert. IDefiBridge bridgeContract = IDefiBridge(bridgeAddress); (outputValueA, outputValueB, isAsync) = bridgeContract.convert{ value: inputAssetA.assetType == Types.AztecAssetType.ETH ? totalInputValue : 0 }( inputAssetA, inputAssetB, outputAssetA, outputAssetB, totalInputValue, interactionNonce, uint64(auxInputData) ); if ( outputAssetA.assetType != Types.AztecAssetType.VIRTUAL && outputAssetA.assetType != Types.AztecAssetType.NOT_USED ) { require( outputValueA == SafeMath.sub( getBalance(outputAssetA.erc20Address), tempValueA ), "DefiBridgeProxy: INCORRECT_ASSET_VALUE" ); } if ( outputAssetB.assetType != Types.AztecAssetType.VIRTUAL && outputAssetB.assetType != Types.AztecAssetType.NOT_USED ) { require( outputValueB == SafeMath.sub( getBalance(outputAssetB.erc20Address), tempValueB ), "DefiBridgeProxy: INCORRECT_ASSET_VALUE" ); } if (isAsync) { require( outputValueA == 0 && outputValueB == 0, "DefiBridgeProxy: ASYNC_NONZERO_OUTPUT_VALUES" ); } emit AztecBridgeInteraction( bridgeAddress, outputValueA, outputValueB, isAsync ); } function canFinalise(address bridgeAddress, uint256 interactionNonce) external view returns (bool ready) { IDefiBridge bridgeContract = IDefiBridge(bridgeAddress); (ready) = bridgeContract.canFinalise(interactionNonce); } function finalise( address bridgeAddress, Types.AztecAsset calldata inputAssetA, Types.AztecAsset calldata inputAssetB, Types.AztecAsset calldata outputAssetA, Types.AztecAsset calldata outputAssetB, uint256 interactionNonce, uint256 auxInputData // (auxData) ) external returns (uint256 outputValueA, uint256 outputValueB) { uint256 tempValueA; uint256 tempValueB; if (outputAssetA.assetType != Types.AztecAssetType.VIRTUAL) { tempValueA = getBalance(outputAssetA.erc20Address); } if (outputAssetB.assetType != Types.AztecAssetType.VIRTUAL) { tempValueB = getBalance(outputAssetB.erc20Address); } IDefiBridge bridgeContract = IDefiBridge(bridgeAddress); require( bridgeContract.canFinalise(interactionNonce), "DefiBridgeProxy: NOT_READY" ); (outputValueA, outputValueB) = bridgeContract.finalise( inputAssetA, inputAssetB, outputAssetA, outputAssetB, interactionNonce, uint64(auxInputData) ); if ( outputAssetA.assetType != Types.AztecAssetType.VIRTUAL && outputAssetA.assetType != Types.AztecAssetType.NOT_USED ) { require( outputValueA == SafeMath.sub( getBalance(outputAssetA.erc20Address), tempValueA ), "DefiBridgeProxy: INCORRECT_ASSET_VALUE" ); } if ( outputAssetB.assetType != Types.AztecAssetType.VIRTUAL && outputAssetB.assetType != Types.AztecAssetType.NOT_USED ) { require( outputValueB == SafeMath.sub( getBalance(outputAssetB.erc20Address), tempValueB ), "DefiBridgeProxy: INCORRECT_ASSET_VALUE" ); } emit AztecBridgeInteraction( bridgeAddress, outputValueA, outputValueB, false ); } }
Call bridge.convert(), which will return output values for the two output assets. If input is ETH, send it along with call to convert.
IDefiBridge bridgeContract = IDefiBridge(bridgeAddress);
13,042,395
[ 1, 1477, 10105, 18, 6283, 9334, 1492, 903, 327, 876, 924, 364, 326, 2795, 876, 7176, 18, 971, 810, 353, 512, 2455, 16, 1366, 518, 7563, 598, 745, 358, 1765, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 467, 3262, 77, 13691, 10105, 8924, 273, 467, 3262, 77, 13691, 12, 18337, 1887, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/11155111/0xe06bC4190870c5Df8Aa3fA776FC0D686581b1aB6/sources/contracts/HexStableCoin.sol
* Function for approving for retrieving tokens for the merchant, from the requested address: - Check the amount and existence of the `_id` request; - {value} - amount of tokens; - {from} - address where from transfer requesting tokens; - Transfer tokens to `merchant`;/ The address `from` must allow the admin to spend the `value` of his tokens
function approveRetrieve(uint256 _id) public onlyRole(ADMIN_ROLE) { require( _id != 0 && request[_id] != address(0), "HexStableCoin: wrong id" ); uint256 value = amounts[request[_id]]; address from = request[_id]; transferFrom(from, merchant, value); emit ApproveRetrieve(from, merchant, _id); }
3,835,009
[ 1, 2083, 364, 6617, 6282, 364, 17146, 2430, 364, 326, 20411, 16, 628, 326, 3764, 1758, 30, 225, 300, 2073, 326, 3844, 471, 15782, 434, 326, 1375, 67, 350, 68, 590, 31, 225, 300, 288, 1132, 97, 300, 3844, 434, 2430, 31, 225, 300, 288, 2080, 97, 300, 1758, 1625, 628, 7412, 18709, 2430, 31, 225, 300, 12279, 2430, 358, 1375, 25705, 68, 31, 19, 1021, 1758, 1375, 2080, 68, 1297, 1699, 326, 3981, 358, 17571, 326, 1375, 1132, 68, 434, 18423, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6617, 537, 5767, 12, 11890, 5034, 389, 350, 13, 1071, 1338, 2996, 12, 15468, 67, 16256, 13, 288, 203, 3639, 2583, 12, 203, 5411, 389, 350, 480, 374, 597, 590, 63, 67, 350, 65, 480, 1758, 12, 20, 3631, 203, 5411, 315, 7037, 30915, 27055, 30, 7194, 612, 6, 203, 3639, 11272, 203, 3639, 2254, 5034, 460, 273, 30980, 63, 2293, 63, 67, 350, 13563, 31, 203, 3639, 1758, 628, 273, 590, 63, 67, 350, 15533, 203, 3639, 7412, 1265, 12, 2080, 16, 20411, 16, 460, 1769, 203, 3639, 3626, 1716, 685, 537, 5767, 12, 2080, 16, 20411, 16, 389, 350, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// 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: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // 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 Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute. return (a / 2) + (b / 2) + (((a % 2) + (b % 2)) / 2); } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds up instead * of rounding down. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b - 1) / b can overflow on addition, so we distribute. return a / b + (a % b == 0 ? 0 : 1); } } // SPDX-License-Identifier: MIT 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 Wrappers over Solidity's arithmetic operations. * * NOTE: `SignedSafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SignedSafeMath { /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { return a * b; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { return a / b; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { return a - b; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { return a + b; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/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*(10**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*(10**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); } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** * @title A contract that provides modifiers to prevent reentrancy to state-changing and view-only methods. This contract * is inspired by https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol * and https://github.com/balancer-labs/balancer-core/blob/master/contracts/BPool.sol. */ contract Lockable { bool private _notEntered; constructor() { // 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 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. _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 making it call a `private` * function that does the actual state modification. */ modifier nonReentrant() { _preEntranceCheck(); _preEntranceSet(); _; _postEntranceReset(); } /** * @dev Designed to prevent a view-only method from being re-entered during a call to a `nonReentrant()` state-changing method. */ modifier nonReentrantView() { _preEntranceCheck(); _; } // Internal methods are used to avoid copying the require statement's bytecode to every `nonReentrant()` method. // On entry into a function, `_preEntranceCheck()` should always be called to check if the function is being // re-entered. Then, if the function modifies state, it should call `_postEntranceSet()`, perform its logic, and // then call `_postEntranceReset()`. // View-only methods can simply call `_preEntranceCheck()` to make sure that it is not being re-entered. function _preEntranceCheck() internal view { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); } function _preEntranceSet() internal { // Any calls to nonReentrant after this point will fail _notEntered = false; } function _postEntranceReset() internal { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "./Timer.sol"; /** * @title Base class that provides time overrides, but only if being run in test mode. */ abstract contract Testable { // If the contract is being run in production, then `timerAddress` will be the 0x0 address. // Note: this variable should be set on construction and never modified. address public timerAddress; /** * @notice Constructs the Testable contract. Called by child contracts. * @param _timerAddress Contract that stores the current time in a testing environment. * Must be set to 0x0 for production environments that use live time. */ constructor(address _timerAddress) { timerAddress = _timerAddress; } /** * @notice Reverts if not running in test mode. */ modifier onlyIfTest { require(timerAddress != address(0x0)); _; } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set current Testable time to. */ function setCurrentTime(uint256 time) external onlyIfTest { Timer(timerAddress).setCurrentTime(time); } /** * @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode. * Otherwise, it will return the block timestamp. * @return uint for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { if (timerAddress != address(0x0)) { return Timer(timerAddress).getCurrentTime(); } else { return block.timestamp; // solhint-disable-line not-rely-on-time } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** * @title Universal store of current contract time for testing environments. */ contract Timer { uint256 private currentTime; constructor() { currentTime = block.timestamp; // solhint-disable-line not-rely-on-time } /** * @notice Sets the current time. * @dev Will revert if not running in test mode. * @param time timestamp to set `currentTime` to. */ function setCurrentTime(uint256 time) external { currentTime = time; } /** * @notice Gets the currentTime variable set in the Timer. * @return uint256 for the current Testable timestamp. */ function getCurrentTime() public view returns (uint256) { return currentTime; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; interface AddressWhitelistInterface { function addToWhitelist(address newElement) external; function removeFromWhitelist(address newElement) external; function isOnWhitelist(address newElement) external view returns (bool); function getWhitelist() external view returns (address[] memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title ERC20 interface that includes burn and mint methods. */ abstract contract ExpandedIERC20 is IERC20 { /** * @notice Burns a specific amount of the caller's tokens. * @dev Only burns the caller's tokens, so it is safe to leave this method permissionless. */ function burn(uint256 value) external virtual; /** * @dev Burns `value` tokens owned by `recipient`. * @param recipient address to burn tokens from. * @param value amount of tokens to burn. */ function burnFrom(address recipient, uint256 value) external virtual returns (bool); /** * @notice Mints tokens and adds them to the balance of the `to` address. * @dev This method should be permissioned to only allow designated parties to mint tokens. */ function mint(address to, uint256 value) external virtual returns (bool); function addMinter(address account) external virtual; function addBurner(address account) external virtual; function resetOwner(address account) external virtual; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "../../../../common/implementation/FixedPoint.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; interface ExpiringContractInterface { function expirationTimestamp() external view returns (uint256); } abstract contract LongShortPairFinancialProductLibrary { function percentageLongCollateralAtExpiry(int256 expiryPrice) public view virtual returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "../common/financial-product-libraries/long-short-pair-libraries/LongShortPairFinancialProductLibrary.sol"; import "../../common/implementation/Testable.sol"; import "../../common/implementation/Lockable.sol"; import "../../common/implementation/FixedPoint.sol"; import "../../common/interfaces/ExpandedIERC20.sol"; import "../../oracle/interfaces/OracleInterface.sol"; import "../../common/interfaces/AddressWhitelistInterface.sol"; import "../../oracle/interfaces/FinderInterface.sol"; import "../../oracle/interfaces/OptimisticOracleInterface.sol"; import "../../oracle/interfaces/IdentifierWhitelistInterface.sol"; import "../../oracle/implementation/Constants.sol"; /** * @title Long Short Pair. * @notice Uses a combination of long and short tokens to tokenize the bounded price exposure to a given identifier. */ contract LongShortPair is Testable, Lockable { using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; /************************************* * LONG SHORT PAIR DATA STRUCTURES * *************************************/ // Define the contract's constructor parameters as a struct to enable more variables to be specified. struct ConstructorParams { string pairName; // Name of the long short pair contract. uint64 expirationTimestamp; // Unix timestamp of when the contract will expire. uint256 collateralPerPair; // How many units of collateral are required to mint one pair of synthetic tokens. bytes32 priceIdentifier; // Price identifier, registered in the DVM for the long short pair. ExpandedIERC20 longToken; // Token used as long in the LSP. Mint and burn rights needed by this contract. ExpandedIERC20 shortToken; // Token used as short in the LSP. Mint and burn rights needed by this contract. IERC20 collateralToken; // Collateral token used to back LSP synthetics. LongShortPairFinancialProductLibrary financialProductLibrary; // Contract providing settlement payout logic. bytes customAncillaryData; // Custom ancillary data to be passed along with the price request to the OO. uint256 prepaidProposerReward; // Preloaded reward to incentivize settlement price proposals. uint256 optimisticOracleLivenessTime; // OO liveness time for price requests. uint256 optimisticOracleProposerBond; // OO proposer bond for price requests. FinderInterface finder; // DVM finder to find other UMA ecosystem contracts. address timerAddress; // Timer used to synchronize contract time in testing. Set to 0x000... in production. } enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived } // @dev note contractState and expirationTimestamp are declared in this order so they use the same storage slot. ContractState public contractState; uint64 public expirationTimestamp; string public pairName; // Amount of collateral a pair of tokens is always redeemable for. uint256 public collateralPerPair; // Price returned from the Optimistic oracle at settlement time. int256 public expiryPrice; // Number between 0 and 1e18 to allocate collateral between long & short tokens at redemption. 0 entitles each short // to collateralPerPair and long worth 0. 1e18 makes each long worth collateralPerPair and short 0. uint256 public expiryPercentLong; bytes32 public priceIdentifier; IERC20 public collateralToken; ExpandedIERC20 public longToken; ExpandedIERC20 public shortToken; FinderInterface public finder; LongShortPairFinancialProductLibrary public financialProductLibrary; // Optimistic oracle customization parameters. bytes public customAncillaryData; uint256 public prepaidProposerReward; uint256 public optimisticOracleLivenessTime; uint256 public optimisticOracleProposerBond; /**************************************** * EVENTS * ****************************************/ event TokensCreated(address indexed sponsor, uint256 indexed collateralUsed, uint256 indexed tokensMinted); event TokensRedeemed(address indexed sponsor, uint256 indexed collateralReturned, uint256 indexed tokensRedeemed); event ContractExpired(address indexed caller); event PositionSettled(address indexed sponsor, uint256 collateralReturned, uint256 longTokens, uint256 shortTokens); /**************************************** * MODIFIERS * ****************************************/ modifier preExpiration() { require(getCurrentTime() < expirationTimestamp, "Only callable pre-expiry"); _; } modifier postExpiration() { require(getCurrentTime() >= expirationTimestamp, "Only callable post-expiry"); _; } modifier onlyOpenState() { require(contractState == ContractState.Open, "Contract state is not Open"); _; } /** * @notice Construct the LongShortPair * @param params Constructor params used to initialize the LSP. Key-valued object with the following structure: * - `pairName`: Name of the long short pair contract. * - `expirationTimestamp`: Unix timestamp of when the contract will expire. * - `collateralPerPair`: How many units of collateral are required to mint one pair of synthetic tokens. * - `priceIdentifier`: Price identifier, registered in the DVM for the long short pair. * - `longToken`: Token used as long in the LSP. Mint and burn rights needed by this contract. * - `shortToken`: Token used as short in the LSP. Mint and burn rights needed by this contract. * - `collateralToken`: Collateral token used to back LSP synthetics. * - `financialProductLibrary`: Contract providing settlement payout logic. * - `customAncillaryData`: Custom ancillary data to be passed along with the price request to the OO. * - `prepaidProposerReward`: Preloaded reward to incentivize settlement price proposals. * - `optimisticOracleLivenessTime`: OO liveness time for price requests. * - `optimisticOracleProposerBond`: OO proposer bond for price requests. * - `finder`: DVM finder to find other UMA ecosystem contracts. * - `timerAddress`: Timer used to synchronize contract time in testing. Set to 0x000... in production. */ constructor(ConstructorParams memory params) Testable(params.timerAddress) { finder = params.finder; require(bytes(params.pairName).length > 0, "Pair name cant be empty"); require(params.expirationTimestamp > getCurrentTime(), "Expiration timestamp in past"); require(params.collateralPerPair > 0, "Collateral per pair cannot be 0"); require(_getIdentifierWhitelist().isIdentifierSupported(params.priceIdentifier), "Identifier not registered"); require(address(_getOptimisticOracle()) != address(0), "Invalid finder"); require(address(params.financialProductLibrary) != address(0), "Invalid FinancialProductLibrary"); require(_getCollateralWhitelist().isOnWhitelist(address(params.collateralToken)), "Collateral not whitelisted"); require(params.optimisticOracleLivenessTime > 0, "OO liveness cannot be 0"); require(params.optimisticOracleLivenessTime < 5200 weeks, "OO liveness too large"); pairName = params.pairName; expirationTimestamp = params.expirationTimestamp; collateralPerPair = params.collateralPerPair; priceIdentifier = params.priceIdentifier; longToken = params.longToken; shortToken = params.shortToken; collateralToken = params.collateralToken; financialProductLibrary = params.financialProductLibrary; OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); require( optimisticOracle.stampAncillaryData(params.customAncillaryData, address(this)).length <= optimisticOracle.ancillaryBytesLimit(), "Ancillary Data too long" ); customAncillaryData = params.customAncillaryData; prepaidProposerReward = params.prepaidProposerReward; optimisticOracleLivenessTime = params.optimisticOracleLivenessTime; optimisticOracleProposerBond = params.optimisticOracleProposerBond; } /**************************************** * POSITION FUNCTIONS * ****************************************/ /** * @notice Creates a pair of long and short tokens equal in number to tokensToCreate. Pulls the required collateral * amount into this contract, defined by the collateralPerPair value. * @dev The caller must approve this contract to transfer `tokensToCreate * collateralPerPair` amount of collateral. * @param tokensToCreate number of long and short synthetic tokens to create. * @return collateralUsed total collateral used to mint the synthetics. */ function create(uint256 tokensToCreate) public preExpiration() nonReentrant() returns (uint256 collateralUsed) { // Note the use of mulCeil to prevent small collateralPerPair causing rounding of collateralUsed to 0 enabling // callers to mint dust LSP tokens without paying any collateral. collateralUsed = FixedPoint.Unsigned(tokensToCreate).mulCeil(FixedPoint.Unsigned(collateralPerPair)).rawValue; collateralToken.safeTransferFrom(msg.sender, address(this), collateralUsed); require(longToken.mint(msg.sender, tokensToCreate)); require(shortToken.mint(msg.sender, tokensToCreate)); emit TokensCreated(msg.sender, collateralUsed, tokensToCreate); } /** * @notice Redeems a pair of long and short tokens equal in number to tokensToRedeem. Returns the commensurate * amount of collateral to the caller for the pair of tokens, defined by the collateralPerPair value. * @dev This contract must have the `Burner` role for the `longToken` and `shortToken` in order to call `burnFrom`. * @dev The caller does not need to approve this contract to transfer any amount of `tokensToRedeem` since long * and short tokens are burned, rather than transferred, from the caller. * @param tokensToRedeem number of long and short synthetic tokens to redeem. * @return collateralReturned total collateral returned in exchange for the pair of synthetics. */ function redeem(uint256 tokensToRedeem) public nonReentrant() returns (uint256 collateralReturned) { require(longToken.burnFrom(msg.sender, tokensToRedeem)); require(shortToken.burnFrom(msg.sender, tokensToRedeem)); collateralReturned = FixedPoint.Unsigned(tokensToRedeem).mul(FixedPoint.Unsigned(collateralPerPair)).rawValue; collateralToken.safeTransfer(msg.sender, collateralReturned); emit TokensRedeemed(msg.sender, collateralReturned, tokensToRedeem); } /** * @notice Settle long and/or short tokens in for collateral at a rate informed by the contract settlement. * @dev Uses financialProductLibrary to compute the redemption rate between long and short tokens. * @dev This contract must have the `Burner` role for the `longToken` and `shortToken` in order to call `burnFrom`. * @dev The caller does not need to approve this contract to transfer any amount of `tokensToRedeem` since long * and short tokens are burned, rather than transferred, from the caller. * @param longTokensToRedeem number of long tokens to settle. * @param shortTokensToRedeem number of short tokens to settle. * @return collateralReturned total collateral returned in exchange for the pair of synthetics. */ function settle(uint256 longTokensToRedeem, uint256 shortTokensToRedeem) public postExpiration() nonReentrant() returns (uint256 collateralReturned) { // If the contract state is open and postExpiration passed then `expire()` has not yet been called. require(contractState != ContractState.Open, "Unexpired contract"); // Get the current settlement price and store it. If it is not resolved, will revert. if (contractState != ContractState.ExpiredPriceReceived) { expiryPrice = _getOraclePriceExpiration(expirationTimestamp); // Cap the return value at 1. expiryPercentLong = Math.min( financialProductLibrary.percentageLongCollateralAtExpiry(expiryPrice), FixedPoint.fromUnscaledUint(1).rawValue ); contractState = ContractState.ExpiredPriceReceived; } require(longToken.burnFrom(msg.sender, longTokensToRedeem)); require(shortToken.burnFrom(msg.sender, shortTokensToRedeem)); // expiryPercentLong is a number between 0 and 1e18. 0 means all collateral goes to short tokens and 1e18 means // all collateral goes to the long token. Total collateral returned is the sum of payouts. uint256 longCollateralRedeemed = FixedPoint .Unsigned(longTokensToRedeem) .mul(FixedPoint.Unsigned(collateralPerPair)) .mul(FixedPoint.Unsigned(expiryPercentLong)) .rawValue; uint256 shortCollateralRedeemed = FixedPoint .Unsigned(shortTokensToRedeem) .mul(FixedPoint.Unsigned(collateralPerPair)) .mul(FixedPoint.fromUnscaledUint(1).sub(FixedPoint.Unsigned(expiryPercentLong))) .rawValue; collateralReturned = longCollateralRedeemed + shortCollateralRedeemed; collateralToken.safeTransfer(msg.sender, collateralReturned); emit PositionSettled(msg.sender, collateralReturned, longTokensToRedeem, shortTokensToRedeem); } /**************************************** * GLOBAL STATE FUNCTIONS * ****************************************/ function expire() public postExpiration() onlyOpenState() nonReentrant() { _requestOraclePriceExpiration(); contractState = ContractState.ExpiredPriceRequested; emit ContractExpired(msg.sender); } /**************************************** * GLOBAL ACCESSORS FUNCTIONS * ****************************************/ /** * @notice Returns the number of long and short tokens a sponsor wallet holds. * @param sponsor address of the sponsor to query. * @return [uint256, uint256]. First is long tokens held by sponsor and second is short tokens held by sponsor. */ function getPositionTokens(address sponsor) public view nonReentrantView() returns (uint256, uint256) { return (longToken.balanceOf(sponsor), shortToken.balanceOf(sponsor)); } /**************************************** * INTERNAL FUNCTIONS * ****************************************/ function _getOraclePriceExpiration(uint256 requestedTime) internal returns (int256) { // Create an instance of the oracle and get the price. If the price is not resolved revert. OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); require(optimisticOracle.hasPrice(address(this), priceIdentifier, requestedTime, customAncillaryData)); int256 oraclePrice = optimisticOracle.settleAndGetPrice(priceIdentifier, requestedTime, customAncillaryData); return oraclePrice; } function _requestOraclePriceExpiration() internal { OptimisticOracleInterface optimisticOracle = _getOptimisticOracle(); // Use the prepaidProposerReward as the proposer reward. if (prepaidProposerReward > 0) collateralToken.safeApprove(address(optimisticOracle), prepaidProposerReward); optimisticOracle.requestPrice( priceIdentifier, expirationTimestamp, customAncillaryData, collateralToken, prepaidProposerReward ); // Set the Optimistic oracle liveness for the price request. optimisticOracle.setCustomLiveness( priceIdentifier, expirationTimestamp, customAncillaryData, optimisticOracleLivenessTime ); // Set the Optimistic oracle proposer bond for the price request. optimisticOracle.setBond( priceIdentifier, expirationTimestamp, customAncillaryData, optimisticOracleProposerBond ); } function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) { return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist)); } function _getCollateralWhitelist() internal view returns (AddressWhitelistInterface) { return AddressWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist)); } function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) { return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle)); } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** * @title Stores common interface names used throughout the DVM by registration in the Finder. */ library OracleInterfaces { bytes32 public constant Oracle = "Oracle"; bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist"; bytes32 public constant Store = "Store"; bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin"; bytes32 public constant Registry = "Registry"; bytes32 public constant CollateralWhitelist = "CollateralWhitelist"; bytes32 public constant OptimisticOracle = "OptimisticOracle"; bytes32 public constant Bridge = "Bridge"; bytes32 public constant GenericHandler = "GenericHandler"; bytes32 public constant SkinnyOptimisticOracle = "SkinnyOptimisticOracle"; } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** * @title Provides addresses of the live contracts implementing certain interfaces. * @dev Examples are the Oracle or Store interfaces. */ interface FinderInterface { /** * @notice Updates the address of the contract that implements `interfaceName`. * @param interfaceName bytes32 encoding of the interface name that is either changed or registered. * @param implementationAddress address of the deployed contract that implements the interface. */ function changeImplementationAddress(bytes32 interfaceName, address implementationAddress) external; /** * @notice Gets the address of the contract that implements the given `interfaceName`. * @param interfaceName queried interface. * @return implementationAddress address of the deployed contract that implements the interface. */ function getImplementationAddress(bytes32 interfaceName) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** * @title Interface for whitelists of supported identifiers that the oracle can provide prices for. */ interface IdentifierWhitelistInterface { /** * @notice Adds the provided identifier as a supported identifier. * @dev Price requests using this identifier will succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function addSupportedIdentifier(bytes32 identifier) external; /** * @notice Removes the identifier from the whitelist. * @dev Price requests using this identifier will no longer succeed after this call. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. */ function removeSupportedIdentifier(bytes32 identifier) external; /** * @notice Checks whether an identifier is on the whitelist. * @param identifier bytes32 encoding of the string identifier. Eg: BTC/USD. * @return bool if the identifier is supported (or not). */ function isIdentifierSupported(bytes32 identifier) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OptimisticOracleInterface { // Struct representing the state of a price request. enum State { Invalid, // Never requested. Requested, // Requested, no other actions taken. Proposed, // Proposed, but not expired or disputed yet. Expired, // Proposed, not disputed, past liveness. Disputed, // Disputed, but no DVM price returned yet. Resolved, // Disputed and DVM price is available. Settled // Final price has been set in the contract (can get here from Expired or Resolved). } // Struct representing a price request. struct Request { address proposer; // Address of the proposer. address disputer; // Address of the disputer. IERC20 currency; // ERC20 token used to pay rewards and fees. bool settled; // True if the request is settled. bool refundOnDispute; // True if the requester should be refunded their reward on dispute. int256 proposedPrice; // Price that the proposer submitted. int256 resolvedPrice; // Price resolved once the request is settled. uint256 expirationTime; // Time at which the request auto-settles without a dispute. uint256 reward; // Amount of the currency to pay to the proposer on settlement. uint256 finalFee; // Final fee to pay to the Store upon request to the DVM. uint256 bond; // Bond that the proposer and disputer must pay on top of the final fee. uint256 customLiveness; // Custom liveness value set by the requester. } // This value must be <= the Voting contract's `ancillaryBytesLimit` value otherwise it is possible // that a price can be requested to this contract successfully, but cannot be disputed because the DVM refuses // to accept a price request made with ancillary data length over a certain size. uint256 public constant ancillaryBytesLimit = 8192; /** * @notice Requests a new price. * @param identifier price identifier being requested. * @param timestamp timestamp of the price being requested. * @param ancillaryData ancillary data representing additional args being passed with the price request. * @param currency ERC20 token used for payment of rewards and fees. Must be approved for use with the DVM. * @param reward reward offered to a successful proposer. Will be pulled from the caller. Note: this can be 0, * which could make sense if the contract requests and proposes the value in the same call or * provides its own reward system. * @return totalBond default bond (final fee) + final fee that the proposer and disputer will be required to pay. * This can be changed with a subsequent call to setBond(). */ function requestPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, IERC20 currency, uint256 reward ) external virtual returns (uint256 totalBond); /** * @notice Set the proposal bond associated with a price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param bond custom bond amount to set. * @return totalBond new bond + final fee that the proposer and disputer will be required to pay. This can be * changed again with a subsequent call to setBond(). */ function setBond( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 bond ) external virtual returns (uint256 totalBond); /** * @notice Sets the request to refund the reward if the proposal is disputed. This can help to "hedge" the caller * in the event of a dispute-caused delay. Note: in the event of a dispute, the winner still receives the other's * bond, so there is still profit to be made even if the reward is refunded. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. */ function setRefundOnDispute( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual; /** * @notice Sets a custom liveness value for the request. Liveness is the amount of time a proposal must wait before * being auto-resolved. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param customLiveness new custom liveness. */ function setCustomLiveness( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, uint256 customLiveness ) external virtual; /** * @notice Proposes a price value on another address' behalf. Note: this address will receive any rewards that come * from this proposal. However, any bonds are pulled from the caller. * @param proposer address to set as the proposer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePriceFor( address proposer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) public virtual returns (uint256 totalBond); /** * @notice Proposes a price value for an existing price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @param proposedPrice price being proposed. * @return totalBond the amount that's pulled from the proposer's wallet as a bond. The bond will be returned to * the proposer once settled if the proposal is correct. */ function proposePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData, int256 proposedPrice ) external virtual returns (uint256 totalBond); /** * @notice Disputes a price request with an active proposal on another address' behalf. Note: this address will * receive any rewards that come from this dispute. However, any bonds are pulled from the caller. * @param disputer address to set as the disputer. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the caller's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was value (the proposal was incorrect). */ function disputePriceFor( address disputer, address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public virtual returns (uint256 totalBond); /** * @notice Disputes a price value for an existing price request with an active proposal. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return totalBond the amount that's pulled from the disputer's wallet as a bond. The bond will be returned to * the disputer once settled if the dispute was valid (the proposal was incorrect). */ function disputePrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 totalBond); /** * @notice Retrieves a price that was previously requested by a caller. Reverts if the request is not settled * or settleable. Note: this method is not view so that this call may actually settle the price request if it * hasn't been settled. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return resolved price. */ function settleAndGetPrice( bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (int256); /** * @notice Attempts to settle an outstanding price request. Will revert if it isn't settleable. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return payout the amount that the "winner" (proposer or disputer) receives on settlement. This amount includes * the returned bonds as well as additional rewards. */ function settle( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) external virtual returns (uint256 payout); /** * @notice Gets the current data structure containing all information about a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the Request data structure. */ function getRequest( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (Request memory); /** * @notice Returns the state of a price request. * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return the State enum value. */ function getState( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (State); /** * @notice Checks if a given request has resolved or been settled (i.e the optimistic oracle has a price). * @param requester sender of the initial price request. * @param identifier price identifier to identify the existing request. * @param timestamp timestamp to identify the existing request. * @param ancillaryData ancillary data of the price being requested. * @return true if price has resolved or settled, false otherwise. */ function hasPrice( address requester, bytes32 identifier, uint256 timestamp, bytes memory ancillaryData ) public view virtual returns (bool); function stampAncillaryData(bytes memory ancillaryData, address requester) public view virtual returns (bytes memory); } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity ^0.8.0; /** * @title Financial contract facing Oracle interface. * @dev Interface used by financial contracts to interact with the Oracle. Voters will use a different interface. */ abstract contract OracleInterface { /** * @notice Enqueues a request (if a request isn't already present) for the given `identifier`, `time` pair. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. */ function requestPrice(bytes32 identifier, uint256 time) public virtual; /** * @notice Whether the price for `identifier` and `time` is available. * @dev Time must be in the past and the identifier must be supported. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return bool if the DVM has resolved to a price for the given identifier and timestamp. */ function hasPrice(bytes32 identifier, uint256 time) public view virtual returns (bool); /** * @notice Gets the price for `identifier` and `time` if it has already been requested and resolved. * @dev If the price is not available, the method reverts. * @param identifier uniquely identifies the price requested. eg BTC/USD (encoded as bytes32) could be requested. * @param time unix timestamp for the price request. * @return int256 representing the resolved price for the given identifier and timestamp. */ function getPrice(bytes32 identifier, uint256 time) public view virtual returns (int256); } pragma solidity >=0.5.0; interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } pragma solidity >=0.5.0; interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } pragma solidity >=0.6.2; interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } pragma solidity >=0.6.2; import './IUniswapV2Router01.sol'; interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } // SPDX-License-Identifier: BSD-3-Clause AND MIT pragma solidity 0.8.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IUSDC} from "./interfaces/IUSDC.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {FixedPoint} from "@uma/core/contracts/common/implementation/FixedPoint.sol"; import {IUniswapV2Factory} from "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol"; import {IUniswapV2Pair} from "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol"; import {IUniswapV2Router02} from "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol"; import {LongShortPair} from "@uma/core/contracts/financial-templates/long-short-pair/LongShortPair.sol"; import {Staking} from "./staking/core/Staking.sol"; /** * @title Domination Finance vault * @notice Provide and withdraw dominance pair liquidity in fewer transactions. */ contract Vault { using SafeERC20 for IERC20; using SafeERC20 for IUSDC; using FixedPoint for FixedPoint.Unsigned; using FixedPoint for FixedPoint.Signed; event VaultDeposited(address user, address lsp, uint amountUSDC); enum WithdrawMode { Basic, Redeem, Settle } /** * @notice Deposit USDC into the vault. Convert it all into LSP liquidity * @dev Keep params in usage order https://levelup.gitconnected.com/stack-too-deep-error-in-solidity-ca83326ff0f0 * @param usdcForArb Portion of supplied USDC to use for arbitrage. Will be deposited along with profits. * @param tokensToBuyForArb If buying+redeeming to arb pools, amount of tokens. See arbitrage() for more detail. * @param router Address of Uniswap, Quickswap, etc. router. * @param priceDeviation_ FixedPoint.Unsigned fraction: maximum % difference between long+short and collateralPerPair * @param lsp LongShortPair for the target dominance pair. * @param amount How much USDC to supply. * @param longStaking Optional. Staking contract for long LP token. Must be during staking window. * @param shortStaking Optional. Staking contract for long LP token. Must be during staking window. * @param deadline timestamp beyond which tx will revert. */ function deposit( uint usdcForArb, uint tokensToBuyForArb, IUniswapV2Router02 router, FixedPoint.Unsigned calldata priceDeviation_, LongShortPair lsp, Signature calldata usdcSignature, uint amount, Staking longStaking, Staking shortStaking, uint deadline ) public { require(deadline >= block.timestamp, "EXPIRED"); // save gas, fail early IUSDC USDC = IUSDC(address(lsp.collateralToken())); if (hasSignature(usdcSignature)) { USDC.permit(msg.sender, address(this), amount, deadline, usdcSignature.v, usdcSignature.r, usdcSignature.s); } USDC.safeTransferFrom(msg.sender, address(this), amount); if (usdcForArb > 0) { _arbitrage(usdcForArb, tokensToBuyForArb, lsp, router, deadline); amount = USDC.balanceOf(address(this)); } (uint tokensToMint, uint mintUSDC, uint longValue, uint shortValue) = computeLPAmounts( router, priceDeviation_, lsp, amount ); require(longValue + shortValue + mintUSDC <= amount, "BUG"); USDC.approve(address(lsp), mintUSDC); lsp.create(tokensToMint); USDC.approve(address(router), shortValue + longValue); { // pool and stake the long tokens. // Avoid "stack to deep" error. Copy to top of stack. IUniswapV2Router02 router_ = router; IERC20 long = IERC20(lsp.longToken()); long.approve(address(router_), tokensToMint); { // Avoid "stack to deep" error. Copy to top of stack. uint deadline_ = deadline; address recipient = address(longStaking) == address(0) ? msg.sender : address(this); router_.addLiquidity( address(long), address(USDC), tokensToMint, longValue, tokensToMint, longValue, recipient, deadline_ ); } if (address(longStaking) != address(0)) { IUniswapV2Factory factory = IUniswapV2Factory(router.factory()); IERC20 longLP = IERC20(factory.getPair(address(long), address(USDC))); uint longLPAmount = longLP.balanceOf(address(this)); longLP.approve(address(longStaking), longLPAmount); longStaking.stakeFor(msg.sender, longLPAmount); } } { // pool and stake short tokens // Avoid "stack to deep" error. Copy to top of stack. IUniswapV2Router02 router_ = router; IERC20 short = IERC20(lsp.shortToken()); short.approve(address(router_), tokensToMint); { // Avoid "stack to deep" error. Copy to top of stack. uint deadline_ = deadline; address recipient = address(shortStaking) == address(0) ? msg.sender : address(this); router_.addLiquidity( address(short), address(USDC), tokensToMint, shortValue, tokensToMint, shortValue, recipient, deadline_ ); } if (address(shortStaking) != address(0)) { IUniswapV2Factory factory = IUniswapV2Factory(router.factory()); IERC20 shortLP = IERC20(factory.getPair(address(short), address(USDC))); uint shortLPAmount = shortLP.balanceOf(address(this)); shortLP.approve(address(shortStaking), shortLPAmount); shortStaking.stakeFor(msg.sender, shortLPAmount); } } emit VaultDeposited(msg.sender, address(lsp), amount); } /** * @notice Compute the percent difference between collateralPerPair and the sum of synth prices. * A nonzero difference indicates an arbitrage opportunity. * @return [(long price + short price) - collateralPerPair] / collateralPerPair */ function priceDeviation ( FixedPoint.Unsigned memory long, FixedPoint.Unsigned memory short, FixedPoint.Unsigned memory collateralPerPair ) internal pure returns (FixedPoint.Unsigned memory) { FixedPoint.Signed memory max = FixedPoint.fromUnsigned(collateralPerPair); FixedPoint.Signed memory diff = FixedPoint.fromUnsigned(long.add(short)).sub(max); return abs(diff.div(max)); } ///@notice absolute value for FixedPoint library function abs(FixedPoint.Signed memory x) internal pure returns (FixedPoint.Unsigned memory) { if (x.isLessThan(0)) { return FixedPoint.fromSigned(FixedPoint.Signed(0).sub(x)); } else { return FixedPoint.fromSigned(x); } } ///@notice an EIP-712 signature for use with Uniswap/USDC permits struct Signature { uint8 v; bytes32 r; bytes32 s; } function hasSignature(Signature calldata s) pure internal returns (bool) { return s.v != 0 && s.r != 0 && s.s != 0; } /*** * @notice Redeem both long and short LP tokens for USDC. LP tokens must be unstaked first. * @param priceDeviation_ FixedPoint.Unsigned fraction: maximum % difference between long+short and collateralPerPair * @param lsp LongShortPair for the target dominance pair * @param longLPAmount wei of long LP tokens to redeem * @param shortLPAmount wei of long LP tokens to redeem * @param router Address of Uniswap, Quickswap, etc. router. * @param USDC address of this network's USDC: denominator of pools and collateral for token. * @param deadline timestamp beyond which tx will revert. * @param longSignature optional EIP-712 (v,r,s) signature * @param shortSignature optional EIP-712 (v,r,s) signature * @param withdrawMode action to take with redeemed synths: 0 nothing, 1 redeem 50:50, 2 settle after expiry */ function withdraw( FixedPoint.Unsigned calldata priceDeviation_, LongShortPair lsp, uint longLPAmount, uint shortLPAmount, IUniswapV2Router02 router, uint deadline, Signature calldata longSignature, Signature calldata shortSignature, WithdrawMode withdrawMode ) public { IERC20 long = IERC20(lsp.longToken()); IERC20 short = IERC20(lsp.shortToken()); { // LP tokens in scope { // factory in scope IUniswapV2Factory factory = IUniswapV2Factory(router.factory()); checkSlippage(long, short, priceDeviation_, lsp, factory); } IUniswapV2Pair longLP; IUniswapV2Pair shortLP; { IUniswapV2Factory factory = IUniswapV2Factory(router.factory()); IERC20 USDC = lsp.collateralToken(); // need to cut down stack longLP = IUniswapV2Pair(factory.getPair(address(long), address(USDC))); shortLP = IUniswapV2Pair(factory.getPair(address(short), address(USDC))); } if (hasSignature(longSignature)) { longLP.permit( msg.sender, address(this), longLPAmount, deadline, longSignature.v, longSignature.r, longSignature.s); } if (hasSignature(shortSignature)) { shortLP.permit( msg.sender, address(this), shortLPAmount, deadline, shortSignature.v, shortSignature.r, shortSignature.s); } shortLP.approve(address(router), shortLPAmount); longLP.approve(address(router), longLPAmount); IERC20(address(longLP)).safeTransferFrom(msg.sender, address(this), longLPAmount); IERC20(address(shortLP)).safeTransferFrom(msg.sender, address(this), shortLPAmount); } { IERC20 USDC = lsp.collateralToken(); address sender = withdrawMode == WithdrawMode.Basic ? msg.sender : address(this); router.removeLiquidity( address(long), address(USDC), longLPAmount, 0, 0, sender, deadline ); router.removeLiquidity( address(short), address(USDC), shortLPAmount, 0, 0, sender, deadline ); if (withdrawMode == WithdrawMode.Redeem) { uint synthToRedeem = long.balanceOf(address(this)) > short.balanceOf(address(this)) ? short.balanceOf(address(this)) : long.balanceOf(address(this)); lsp.redeem(synthToRedeem); USDC.safeTransfer(msg.sender, USDC.balanceOf(address(this))); long.safeTransfer(msg.sender, long.balanceOf(address(this))); short.safeTransfer(msg.sender, short.balanceOf(address(this))); } else if (withdrawMode == WithdrawMode.Settle) { lsp.settle(long.balanceOf(address(this)), short.balanceOf(address(this))); USDC.safeTransfer(msg.sender, USDC.balanceOf(address(this))); } } } /** * @notice Arb a pair's pools: use supplied USDC to mint+sell or buy+redeem. Return USDC + profits to sender. * @dev compute optimal arb amount off-chain * @param amount USDC to use for arbitrage * @param tokensToBuy Number of tokens to buy and redeem. If 0, mint and sell with supplied USDC * @param lsp LongShortPair for the target dominance pair * @param router Address of Uniswap, Quickswap, etc. router. * @param deadline Timestamp beyond which tx will revert. * @param usdcSignature optional signature */ function arbitrage( uint amount, uint tokensToBuy, LongShortPair lsp, IUniswapV2Router02 router, uint deadline, Signature calldata usdcSignature ) external { IUSDC USDC = IUSDC(address(lsp.collateralToken())); if (hasSignature(usdcSignature)) { USDC.permit(msg.sender, address(this), amount, deadline, usdcSignature.v, usdcSignature.r, usdcSignature.s); } USDC.safeTransferFrom(msg.sender, address(this), amount); _arbitrage(amount, tokensToBuy, lsp, router, deadline); USDC.safeTransfer(msg.sender, USDC.balanceOf(address(this))); } /** * @notice Arb a pair's pools: use supplied USDC to mint+sell or buy+redeem. * @dev compute optimal arb amount off-chain * @dev precondition: vault has USDC bal >= usdcToUse * @param usdcToUse USDC to use for arbitrage * @param tokensToBuy Number of tokens to buy and redeem. If 0, mint and sell with supplied USDC * @param lsp LongShortPair for the target dominance pair * @param router Address of Uniswap, Quickswap, etc. router. * @param deadline Timestamp beyond which tx will revert. */ function _arbitrage( uint usdcToUse, uint tokensToBuy, LongShortPair lsp, IUniswapV2Router02 router, uint deadline ) internal { require(usdcToUse > 0, "INVALID ARGUMENTS"); // must have some amount of USDC to work with IUSDC USDC = IUSDC(address(lsp.collateralToken())); IERC20 long = lsp.longToken(); IERC20 short = lsp.shortToken(); uint startUSDCbal = USDC.balanceOf(address(this)); if (tokensToBuy > 0) { // buy and redeem equal amounts of token with the supplied USDC USDC.approve(address(router), usdcToUse); address[] memory path = new address[](2); // can't cast static array to dynamic >:( path[0] = address(USDC); path[1] = address(long); router.swapTokensForExactTokens( tokensToBuy, usdcToUse, path, address(this), deadline ); path[1] = address(short); router.swapTokensForExactTokens( tokensToBuy, usdcToUse, path, address(this), deadline ); long.approve(address(lsp), tokensToBuy); short.approve(address(lsp), tokensToBuy); lsp.redeem(tokensToBuy); } else { // mint tokens with usdcToUse and sell them all USDC.approve(address(lsp), usdcToUse); uint tokensToMint = usdcToUse / (lsp.collateralPerPair() / FixedPoint.fromUnscaledUint(1).rawValue); lsp.create(tokensToMint); long.approve(address(router), tokensToMint); short.approve(address(router), tokensToMint); address[] memory path = new address[](2); path[1] = address(USDC); path[0] = address(long); router.swapExactTokensForTokens( tokensToMint, 0, path, address(this), deadline ); path[0] = address(short); router.swapExactTokensForTokens( tokensToMint, 0, path, address(this), deadline ); } // We could check price deviation, but that requires more complicated parameters and more gas. If you need to // arbitrage pools very precisely, increase gas for a fast transaction or write your own contract. uint USDCbal = USDC.balanceOf(address(this)); require(USDCbal > startUSDCbal, "UNPROFITABLE"); // arbing in the right direction makes money } /** * @notice Check the market value of a user's LSP liquidity, in USDC. */ function depositedFor( IUniswapV2Factory factory, LongShortPair lsp, Staking longStaking, Staking shortStaking, address user ) public view returns (uint) { IERC20 USDC = lsp.collateralToken(); IERC20 longPool = IERC20(factory.getPair(address(lsp.longToken()), address(USDC))); IERC20 shortPool = IERC20(factory.getPair(address(lsp.shortToken()), address(USDC))); uint longUSDC = USDC.balanceOf(address(longPool)); uint shortUSDC = USDC.balanceOf(address(shortPool)); FixedPoint.Unsigned memory longShare = FixedPoint.fromUnscaledUint(longPool.balanceOf(user)) .add(address(longStaking) != address(0) ? longStaking.totalStakedFor(user) : 0) .div(longPool.totalSupply()); FixedPoint.Unsigned memory shortShare = FixedPoint.fromUnscaledUint(shortPool.balanceOf(user)) .add(address(shortStaking) != address(0) ? shortStaking.totalStakedFor(user) : 0) .div(shortPool.totalSupply()); return longShare.mul(FixedPoint.Unsigned(longUSDC)) .add(shortShare.mul(FixedPoint.Unsigned(shortUSDC))) .mul(2) .rawValue; } function computeLPAmounts( IUniswapV2Router02 router, FixedPoint.Unsigned calldata priceDeviation_, LongShortPair lsp, uint amount ) internal view returns ( uint tokensToMint, uint mintUSDC, uint longValue, uint shortValue ) { IERC20 long = IERC20(lsp.longToken()); IERC20 short = IERC20(lsp.shortToken()); IUniswapV2Factory factory = IUniswapV2Factory(router.factory()); ( FixedPoint.Unsigned memory longPrice, FixedPoint.Unsigned memory shortPrice, FixedPoint.Unsigned memory collateralPerPair ) = checkSlippage(long, short, priceDeviation_, lsp, factory); tokensToMint = FixedPoint.Unsigned(amount) .div( collateralPerPair .add(longPrice) .add(shortPrice)).rawValue; mintUSDC = collateralPerPair.mul(FixedPoint.Unsigned(tokensToMint)).rawValue; longValue = longPrice.mul(FixedPoint.Unsigned(tokensToMint)).rawValue; shortValue = shortPrice.mul(FixedPoint.Unsigned(tokensToMint)).rawValue; } function checkSlippage( IERC20 long, IERC20 short, FixedPoint.Unsigned calldata priceDeviation_, LongShortPair lsp, IUniswapV2Factory factory ) internal view returns ( FixedPoint.Unsigned memory longPrice, FixedPoint.Unsigned memory shortPrice, FixedPoint.Unsigned memory collateralPerPair ) { IERC20 USDC = IERC20(lsp.collateralToken()); longPrice = getMarketPrice(long, USDC, factory); shortPrice = getMarketPrice(short, USDC, factory); collateralPerPair = FixedPoint.Unsigned(lsp.collateralPerPair()); require( priceDeviation(longPrice, shortPrice, collateralPerPair).isLessThanOrEqual(priceDeviation_), "SLIPPAGE"); } /** * @notice get USDC per synth market price. FixedPoint for fractional component * @return FixedPoint.Unsigned market price ($/synth) * @param synth token paired with USDC * @param USDC address of this network's USDC: denominator of pools and collateral for token. * @param factory query price for this DEX */ function getMarketPrice( IERC20 synth, IERC20 USDC, IUniswapV2Factory factory ) internal view returns (FixedPoint.Unsigned memory) { address pool = factory.getPair(address(synth), address(USDC)); FixedPoint.Unsigned memory USDCbal = FixedPoint.fromUnscaledUint(USDC.balanceOf(pool)); uint synthbal = synth.balanceOf(pool); require(synthbal > 0, "No synth pooled"); return USDCbal.div(synthbal); } /** * @notice The vault should never hold any tokens. This method allows anyone to withdraw a token's entire balance. * It should be used if tokens are mistakenly sent to the contract, or if a bug causes leftover balances. * @param token address of a ERC20 */ function rescue(IERC20 token) external { token.transfer(msg.sender, token.balanceOf(address(this))); } } // SPDX-License-Identifier: MIT pragma solidity 0.8.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** @notice Interface with USDC's permit method. From * https://github.com/centrehq/centre-tokens/blob/master/contracts/v2/FiatTokenV2.sol */ interface IUSDC is IERC20 { function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // SPDX-License-Identifier: MIT AND AGPL-3.0-only pragma solidity 0.8.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {FixedPoint} from "@uma/core/contracts/common/implementation/FixedPoint.sol"; import {IERC900} from "../interfaces/IERC900.sol"; import {Modifiers} from "../utils/Modifiers.sol"; /** * @title Domination Finance LP Staking contract * @notice Distributes $DOM tokens to dominance pair liquidity providers who stake their LP tokens. Once the "staking * period" ends, $DOM rewards are reserved for stakers in proportion to their share of the pool. If a user * unstakes before the end of the program, only part of the reserved rewards are granted. This partial reward is * quadratic over the program duration, and is scaled by an additional linear penalty during the penalty period. * Any reserved $DOM given up by early unstakes can be withdrawn by the contract owner. */ contract Staking is IERC900, Modifiers, Ownable, ReentrancyGuard { using FixedPoint for FixedPoint.Unsigned; using SafeERC20 for IERC20; /* Variables, Declarations and Constructor */ // total staked LP tokens at the end of the 7 day staking period uint256 private _totalStaked; // withdrawn or renounced rewards uint256 public unlockedRewards; struct Account { uint256 staked; } mapping(address => Account) private _balances; struct RewardOutput { FixedPoint.Unsigned rewardRatio; FixedPoint.Unsigned penaltyRatio; FixedPoint.Unsigned amount; } /** * @notice Create a Staking contract for a particular LP token, period, and $DOM allocation. * @dev Contract must be funded and permitted to transfer $DOM (if applicable) before users can stake. * @param lpToken address of LP token, i.e. BTC-ALTDOM-Dec-2022/USDC * @param domToken address of rewards token * @param owner recipient of leftover rewards * @param totalDOM maximum DOM to be distributed * @param stakingStart timestamp when users can stake * @param lspExpiration timestamp when users can claim their entire reserved reward */ constructor( address lpToken, address domToken, address owner, uint256 totalDOM, uint256 stakingStart, uint256 lspExpiration ) Ownable() ReentrancyGuard() { if (owner != _msgSender()) { transferOwnership(owner); } require(totalDOM > 0, ERROR_ZERO_AMOUNT); TOTAL_DOM = totalDOM; require(stakingStart > block.timestamp, ERROR_PAST_TIMESTAMP); STAKING_START_TIMESTAMP = stakingStart; require(lspExpiration - STAKING_START_TIMESTAMP > REWARD_PERIOD, ERROR_EXPIRES_TOO_SOON); LSP_EXPIRATION = lspExpiration; LP_TOKEN = IERC20(lpToken); DOM_TOKEN = IERC20(domToken); } /* State changing functions */ /** * @notice Stake LP tokens * @dev Must approve at least <amount> LP tokens before calling * @param amount LP tokens to stake **/ function stake(uint256 amount) external override duringStaking nonReentrant { address sender = _msgSender(); _stakeFor(sender, sender, amount); } /** * @notice Stake LP tokens on behalf of an address, which will receive the LP tokens and rewards when it unstake()s. * @dev Must approve at least <amount> LP tokens before calling * @param amount LP tokens to stake * @param beneficiary address which will be able to unstake **/ function stakeFor( address beneficiary, uint256 amount ) external override duringStaking nonReentrant { address sender = _msgSender(); _stakeFor(sender, beneficiary, amount); } /** * @notice Unstake previously-staked LP tokens and receive a $DOM reward, if applicable. Partial unstakes supported. * @param amount LP tokens to withdraw **/ function unstake(uint256 amount) external override nonReentrant { _unstake(_msgSender(), amount); } /** * @notice Withdraw $DOM beyond what is committed to staking rewards. * @dev Unstaking early "unlocks" rewards in excess of those given out. The remaining funds out of TOTAL_DOM have been promised to stakers. Contract balance could also be greater than unlocked + locked, in which case also withdraw the excess. Callable at any time without affecting future rewards, but will revert if contract is underfunded. Likely called soon after the end of the staking program, and some time later for any stragglers. */ function withdrawLeftover() external { uint256 locked = TOTAL_DOM - unlockedRewards; DOM_TOKEN.safeTransfer(owner(), DOM_TOKEN.balanceOf(address(this)) - locked); } /* View functions */ function stakingToken() external view override returns (address) { return address(LP_TOKEN); } function rewardToken() external view override returns (address) { return address(DOM_TOKEN); } function totalStaked() external view override returns (uint256) { return _totalStaked; } function totalStakedFor(address user) external view override returns (uint256) { return _balances[user].staked; } /** * @dev This contract doesn't support IERC900's history interface. Use the event log or an archive node. */ function supportsHistory() external pure override returns (bool) { return false; } function isStakingAllowed() external view returns (bool) { return _isStakingAllowed(); } function remainingDOM() external view returns (uint256) { return DOM_TOKEN.balanceOf(address(this)); } function rewardRatio() external view returns (uint256) { return _getRewardRatioAt(block.timestamp).rawValue; } function penaltyRatio() external view returns (uint256) { return _getPenaltyRatioAt(block.timestamp).rawValue; } function ratios() external view returns (uint256 reward, uint256 penalty) { reward = _getRewardRatioAt(block.timestamp).rawValue; penalty = _getPenaltyRatioAt(block.timestamp).rawValue; } function account(address user) external view returns ( uint256 _rewardRatio, uint256 _penaltyRatio, uint256 _staked, uint256 _rewards ) { RewardOutput memory output = _getUserRewards(block.timestamp, user); _rewardRatio = output.rewardRatio.rawValue; _penaltyRatio = output.penaltyRatio.rawValue; _rewards = output.amount.rawValue; _staked = _balances[user].staked; } /* Internal functions */ function _stakeFor(address from, address user, uint256 amount) internal { require(amount > 0, ERROR_ZERO_AMOUNT); require(user != address(0), ERROR_ZERO_ADDRESS); require(LP_TOKEN.allowance(from, address(this)) >= amount, ERROR_NOT_ENOUGH_ALLOWANCE); LP_TOKEN.safeTransferFrom(from, address(this), amount); _balances[user].staked += amount; _totalStaked += amount; emit Staked(from, amount, _balances[user].staked); } function _unstake(address user, uint256 amount) internal { require(amount > 0, ERROR_ZERO_AMOUNT); require(amount <= _balances[user].staked, ERROR_NOT_ENOUGH_STAKE); RewardOutput memory output = _getUserRewards(block.timestamp, user); uint256 maxPartialRewards = FixedPoint.Unsigned(amount) .div(FixedPoint.Unsigned(_totalStaked)) .mul(FixedPoint.Unsigned(TOTAL_DOM)) .rawValue; uint256 partialRewards = FixedPoint.Unsigned(amount) .div(FixedPoint.Unsigned(_balances[user].staked)) .mul(output.amount) .rawValue; _balances[user].staked -= amount; if (_isStakingAllowed()) { // during the staking period, withdraws don't waste any rewards _totalStaked -= amount; } // return unstaked LP tokens LP_TOKEN.safeTransfer(user, amount); unlockedRewards += maxPartialRewards; if (partialRewards > 0) { DOM_TOKEN.safeTransfer(user, partialRewards); } emit Unstaked(user, amount, _balances[user].staked); } function rewardsAt( uint256 timestamp, address user ) external view returns ( uint256 out_rewardRatio, uint256 out_penaltyRatio, uint256 out_amount ) { RewardOutput memory x = _getUserRewards(timestamp, user); out_rewardRatio = x.rewardRatio.rawValue; out_penaltyRatio = x.penaltyRatio.rawValue; out_amount = x.amount.rawValue; } function _getUserRewards( uint256 timestamp, address user ) internal view returns (RewardOutput memory) { return _computeRewards( timestamp, _balances[user].staked, _totalStaked, TOTAL_DOM); } function _computeRewards( uint256 p_timestamp, uint256 p_userStaked, uint256 p_totalStaked, uint256 p_totalRewards ) internal view returns (RewardOutput memory) { RewardOutput memory output; output.rewardRatio = _getRewardRatioAt(p_timestamp); output.penaltyRatio = _getPenaltyRatioAt(p_timestamp); if (p_totalStaked > 0) { output.amount = FixedPoint.Unsigned(p_totalRewards) .mul(FixedPoint.Unsigned(p_userStaked) .div(FixedPoint.Unsigned(p_totalStaked))) .mul(output.rewardRatio) .mul(FixedPoint.fromUnscaledUint(1).sub(output.penaltyRatio)) // share of user out of total staked ; } else { output.amount = FixedPoint.fromUnscaledUint(0); } return output; } function _getRewardRatioAt(uint256 timestamp) internal view returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory offset; if (timestamp > STAKING_START_TIMESTAMP) { offset = FixedPoint.fromUnscaledUint(timestamp).sub(STAKING_START_TIMESTAMP); } else { offset = FixedPoint.fromUnscaledUint(0); } FixedPoint.Unsigned memory lspLength = FixedPoint.fromUnscaledUint(LSP_EXPIRATION).sub(STAKING_START_TIMESTAMP); if (offset.isLessThan(STAKING_PERIOD)) { return FixedPoint.fromUnscaledUint(0); } else if (offset.isLessThan(lspLength)) { offset = offset.sub(STAKING_PERIOD); lspLength = lspLength.sub(STAKING_PERIOD); return offset.pow(2) .div(lspLength.pow(2)); } else { return FixedPoint.fromUnscaledUint(1); } } function _getPenaltyRatioAt(uint256 timestamp) internal view returns (FixedPoint.Unsigned memory) { FixedPoint.Unsigned memory offset; if (timestamp > STAKING_START_TIMESTAMP) { offset = FixedPoint.fromUnscaledUint(timestamp).sub(STAKING_START_TIMESTAMP); } else { offset = FixedPoint.fromUnscaledUint(0); } if (offset.isLessThan(STAKING_PERIOD)) { return FixedPoint.fromUnscaledUint(1); } else if (offset.isLessThan(REWARD_PERIOD)) { return FixedPoint.fromUnscaledUint(1) .sub( offset.sub(STAKING_PERIOD) .div(REWARD_PERIOD - STAKING_PERIOD)); } else { return FixedPoint.fromUnscaledUint(0); } } } // SPDX-License-Identifier: CC0-1.0 pragma solidity 0.8.6; /** * @title General Staking Interface * ERC900: https://eips.ethereum.org/EIPS/eip-900 */ interface IERC900 { event Staked(address indexed user, uint256 amount, uint256 total); event Unstaked(address indexed user, uint256 amount, uint256 total); /** * @dev Stake a certain amount of tokens * @param _amount Amount of tokens to be staked */ function stake(uint256 _amount) external; /** * @dev Stake a certain amount of tokens to another address * @param _user Address to stake tokens to * @param _amount Amount of tokens to be staked */ function stakeFor(address _user, uint256 _amount) external; /** * @dev Unstake a certain amount of tokens * @param _amount Amount of tokens to be unstaked */ function unstake(uint256 _amount) external; /** * @dev Tell the current total amount of tokens staked for an address * @param _addr Address to query * @return Current total amount of tokens staked for the address */ function totalStakedFor(address _addr) external view returns (uint256); /** * @dev Tell the current total amount of tokens staked from all addresses * @return Current total amount of tokens staked from all addresses */ function totalStaked() external view returns (uint256); /** * @dev Tell the address of the staking token * @return Address of the staking token */ function stakingToken() external view returns (address); /** * @dev Tell the address of the reward token * @return Address of the reward token */ function rewardToken() external view returns (address); /* * @dev Tell if the optional history functions are implemented * - check interface at IERC900HistoryExtension * * @return True if the optional history functions are implemented */ function supportsHistory() external pure returns (bool); } // SPDX-License-Identifier: MIT AND AGPL-3.0-only pragma solidity 0.8.6; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; abstract contract Constants { IERC20 internal LP_TOKEN; IERC20 internal DOM_TOKEN; uint256 public STAKING_START_TIMESTAMP; uint256 internal constant STAKING_PERIOD = 7 days; uint256 internal constant REWARD_PERIOD = 120 days; uint256 internal LSP_EXPIRATION; uint256 public TOTAL_DOM; } // SPDX-License-Identifier: MIT AND AGPL-3.0-only pragma solidity 0.8.6; abstract contract Errors { string internal constant ERROR_ZERO_AMOUNT = "ZERO_AMOUNT"; string internal constant ERROR_ZERO_ADDRESS = "ZERO_ADDRESS"; string internal constant ERROR_PAST_TIMESTAMP = "PAST_TIMESTAMP"; string internal constant ERROR_NOT_ENOUGH_DOM = "NOT_ENOUGH_DOM"; string internal constant ERROR_NOT_ENOUGH_ALLOWANCE = "NOT_ENOUGH_ALLOWANCE"; string internal constant ERROR_NOT_ENOUGH_STAKE = "NOT_ENOUGH_STAKED"; string internal constant ERROR_STAKING_NOT_STARTED = "STAKING_NOT_STARTED"; string internal constant ERROR_EXPIRES_TOO_SOON = "EXPIRES_TOO_SOON"; string internal constant ERROR_STAKING_PROHIBITED = "STAKING_PROHIBITED"; } // SPDX-License-Identifier: MIT AND AGPL-3.0-only pragma solidity 0.8.6; import {Constants} from "./Constants.sol"; import {Errors} from "./Errors.sol"; abstract contract Modifiers is Constants, Errors { function _isStakingAllowed() internal view returns (bool) { return block.timestamp >= STAKING_START_TIMESTAMP && block.timestamp < STAKING_START_TIMESTAMP + STAKING_PERIOD && DOM_TOKEN.balanceOf(address(this)) >= TOTAL_DOM; } // allow calling during deposit period i.e 0 to 7 days modifier duringStaking() { require(_isStakingAllowed(), ERROR_STAKING_PROHIBITED); _; } }
* @title Stores common interface names used throughout the DVM by registration in the Finder./
library OracleInterfaces { bytes32 public constant Oracle = "Oracle"; bytes32 public constant IdentifierWhitelist = "IdentifierWhitelist"; bytes32 public constant Store = "Store"; bytes32 public constant FinancialContractsAdmin = "FinancialContractsAdmin"; bytes32 public constant Registry = "Registry"; bytes32 public constant CollateralWhitelist = "CollateralWhitelist"; bytes32 public constant OptimisticOracle = "OptimisticOracle"; bytes32 public constant Bridge = "Bridge"; bytes32 public constant GenericHandler = "GenericHandler"; bytes32 public constant SkinnyOptimisticOracle = "SkinnyOptimisticOracle"; pragma solidity ^0.8.0; }
1,193,824
[ 1, 13125, 2975, 1560, 1257, 1399, 3059, 659, 326, 463, 7397, 635, 7914, 316, 326, 19307, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 28544, 10273, 288, 203, 565, 1731, 1578, 1071, 5381, 28544, 273, 315, 23601, 14432, 203, 565, 1731, 1578, 1071, 5381, 10333, 18927, 273, 315, 3004, 18927, 14432, 203, 565, 1731, 1578, 1071, 5381, 4994, 273, 315, 2257, 14432, 203, 565, 1731, 1578, 1071, 5381, 9458, 19292, 649, 20723, 4446, 273, 315, 6187, 19292, 649, 20723, 4446, 14432, 203, 565, 1731, 1578, 1071, 5381, 5438, 273, 315, 4243, 14432, 203, 565, 1731, 1578, 1071, 5381, 17596, 2045, 287, 18927, 273, 315, 13535, 2045, 287, 18927, 14432, 203, 565, 1731, 1578, 1071, 5381, 19615, 5846, 23601, 273, 315, 13930, 5846, 23601, 14432, 203, 565, 1731, 1578, 1071, 5381, 24219, 273, 315, 13691, 14432, 203, 565, 1731, 1578, 1071, 5381, 7928, 1503, 273, 315, 7014, 1503, 14432, 203, 565, 1731, 1578, 1071, 5381, 10362, 267, 18538, 13930, 5846, 23601, 273, 315, 26827, 18538, 13930, 5846, 23601, 14432, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/11155111/0x3Be6088eE6F02F5522E6bd80bAE6533874f9D92a/sources/project_/contracts/Property.sol
the new owner should change this again once they have a new listing broker by calling setListingBrokerForRoyalties() if no new broker, funds will go to the new owner
Royalties[1].beneficiary = payable(to);
3,821,549
[ 1, 5787, 394, 3410, 1410, 2549, 333, 3382, 3647, 2898, 1240, 279, 394, 11591, 8625, 635, 4440, 444, 19081, 11194, 1290, 54, 13372, 2390, 606, 1435, 309, 1158, 394, 8625, 16, 284, 19156, 903, 1960, 358, 326, 394, 3410, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 534, 13372, 2390, 606, 63, 21, 8009, 70, 4009, 74, 14463, 814, 273, 8843, 429, 12, 869, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.7.6; pragma abicoder v2; import { IConstantFlowAgreementV1 } from "@superfluid-finance/ethereum-contracts/contracts/interfaces/agreements/IConstantFlowAgreementV1.sol"; import "@superfluid-finance/ethereum-contracts/contracts/interfaces/misc/IResolver.sol"; import { ISuperfluid, ISuperToken, ISuperTokenFactory } from "@superfluid-finance/ethereum-contracts/contracts/interfaces/superfluid/ISuperfluid.sol"; import { ERC20WithTokenInfo } from "@superfluid-finance/ethereum-contracts/contracts/interfaces/tokens/ERC20WithTokenInfo.sol"; import { Initializable } from "@openzeppelin/contracts/proxy/Initializable.sol"; import "../interfaces/IBaseApp.sol"; /// @title BaseApp /// @notice BaseApp to interact with Superfluid protocol /// @dev contains the mimimal code for the SFMinion to interact with Superfluid protocol abstract contract BaseApp is Initializable, IBaseApp { ISuperfluid internal _host; // Superfluid host address IConstantFlowAgreementV1 internal _cfa; // Superfluid Constant Flow Agreement address IResolver internal _resolver; // Superfluid resolver string internal _version; // Superfluid version mapping (address => address) public superTokenRegistry; // token registry for non-official tokens /// @notice /// @dev /// @param _sfHost Superfluid host contract /// @param _sfCFA CFA agreement contract /// @param _sfResolver Superfluid Resolver contract /// @param _sfVersion Superfluid protocol version function __BaseApp_init_unchained(address _sfHost, address _sfCFA, address _sfResolver, string memory _sfVersion) internal initializer { _host = ISuperfluid(_sfHost); _cfa = IConstantFlowAgreementV1(_sfCFA); _resolver = IResolver(_sfResolver); _version = _sfVersion; } /// @notice /// @dev /// @param _token a token /// @return true function isSuperToken(ERC20WithTokenInfo _token) public override view returns (bool) { string memory tokenId = string(abi.encodePacked('supertokens', '.', _version, '.', _token.symbol())); return _resolver.get(tokenId) == address(_token); } /// @notice /// @dev /// @param _token an underlying token /// @return tokenAddress function getSuperToken(ERC20WithTokenInfo _token) public override view returns (address tokenAddress) { string memory tokenId = string(abi.encodePacked('supertokens', '.', _version, '.', _token.symbol(), 'x')); tokenAddress = _resolver.get(tokenId); if (tokenAddress == address(0)) { // Look on the App registry if there's already a "non-oficially registered" Supertoken tokenAddress = superTokenRegistry[address(_token)]; } } /// @notice /// @dev /// @return Superfluid contracts function superfluidConfig() external override view returns (ISuperfluid, IResolver, IConstantFlowAgreementV1, string memory) { return (_host, _resolver, _cfa, _version); } /// @notice /// @dev /// @param _token underlying token /// @return superToken newly created SuperToken function createSuperToken(ERC20WithTokenInfo _token) public override returns (ISuperToken superToken) { if (superTokenRegistry[address(_token)] != address(0)) { superToken = ISuperToken(superTokenRegistry[address(_token)]); } else { ISuperTokenFactory factory = _host.getSuperTokenFactory(); string memory name = string(abi.encodePacked('Super ', _token.name())); string memory symbol = string(abi.encodePacked(_token.symbol(), 'x')); superToken = factory.createERC20Wrapper(_token, ISuperTokenFactory.Upgradability.FULL_UPGRADABE, name, symbol); superTokenRegistry[address(_token)] = address(superToken); } } } /// @title App /// @notice App to interact with Superfluid protocol /// @dev non-upgradable contract App is BaseApp { constructor(address _sfHost, address _sfCFA, address _sfResolver, string memory _sfVersion) { BaseApp.__BaseApp_init_unchained(_sfHost, _sfCFA, _sfResolver, _sfVersion); } }
Superfluid Constant Flow Agreement address
IConstantFlowAgreementV1 internal _cfa;
5,414,424
[ 1, 8051, 2242, 1911, 10551, 9473, 5495, 10606, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 467, 6902, 5249, 17420, 58, 21, 2713, 389, 71, 507, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42/0x90644C62f60Df69c98BFAC467a9617C7D06BBEAA/sources/pruebas/crear.sol
IERC20 token; using SafeMath for uint256;
contract base{ crearTokenAAVE public prueba; ILendingPoolAddressesProvider provider = ILendingPoolAddressesProvider(address(0x88757f2f99175387aB4C6a4b3067c77A695b0349)); ILendingPool lending = ILendingPool(provider.getLendingPool()); constructor(){ prueba = crearTokenAAVE(0x600103d518cC5E8f3319D532eB4e5C268D32e604); } IERC20 public token = IERC20(adressToken); IERC20 public tokenWETH = IERC20(adressTokenWETH); function getReserve(address _asset) external view returns(DataTypes.ReserveData memory){ return lending.getReserveData(_asset); } function getReserve2(address _asset) internal view returns(DataTypes.ReserveData memory){ return lending.getReserveData(_asset); } function getReserveList()external view returns (address[] memory){ return lending.getReservesList(); } function crear() payable external { token.approve(provider.getLendingPool(), 10000000000 ether); for(uint i=0; i<15;i++){ prueba.mint(adressToken,100000 ether); } uint256 balance= balanceScontract(); function crear() payable external { token.approve(provider.getLendingPool(), 10000000000 ether); for(uint i=0; i<15;i++){ prueba.mint(adressToken,100000 ether); } uint256 balance= balanceScontract(); lending.deposit(adressToken, balance, baseAddress, 0); } function borrowETH() external payable { lending.borrow(adressTokenWETH,10000000000000000 , uint256(2), uint16(0),baseAddress); } function balanceScontract() public view returns(uint256){ return token.balanceOf(address(this)); } }
16,294,557
[ 1, 45, 654, 39, 3462, 1147, 31, 1450, 14060, 10477, 364, 2254, 5034, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1026, 95, 203, 203, 565, 1519, 297, 1345, 5284, 3412, 1071, 846, 344, 12124, 31, 203, 377, 203, 565, 467, 48, 2846, 2864, 7148, 2249, 2893, 273, 467, 48, 2846, 2864, 7148, 2249, 12, 2867, 12, 20, 92, 5482, 5877, 27, 74, 22, 74, 2733, 4033, 25, 7414, 27, 69, 38, 24, 39, 26, 69, 24, 70, 5082, 9599, 71, 4700, 37, 8148, 25, 70, 4630, 7616, 10019, 7010, 565, 467, 48, 2846, 2864, 328, 2846, 273, 467, 48, 2846, 2864, 12, 6778, 18, 588, 48, 2846, 2864, 10663, 203, 565, 3885, 1435, 95, 203, 3639, 846, 344, 12124, 273, 1519, 297, 1345, 5284, 3412, 12, 20, 92, 28133, 23494, 72, 25, 2643, 71, 39, 25, 41, 28, 74, 3707, 3657, 40, 25, 1578, 73, 38, 24, 73, 25, 39, 5558, 28, 40, 1578, 73, 26, 3028, 1769, 203, 540, 203, 540, 203, 565, 289, 203, 565, 467, 654, 39, 3462, 1071, 1147, 273, 467, 654, 39, 3462, 12, 361, 663, 1345, 1769, 203, 377, 203, 203, 203, 565, 467, 654, 39, 3462, 1071, 1147, 59, 1584, 44, 273, 467, 654, 39, 3462, 12, 361, 663, 1345, 59, 1584, 44, 1769, 203, 565, 445, 31792, 6527, 12, 2867, 389, 9406, 13, 3903, 1476, 1135, 12, 751, 2016, 18, 607, 6527, 751, 3778, 15329, 203, 3639, 327, 328, 2846, 18, 588, 607, 6527, 751, 24899, 9406, 1769, 203, 565, 289, 203, 203, 565, 445, 31792, 6527, 22, 12, 2867, 389, 9406, 13, 2713, 1476, 1135, 12, 751, 2016, 18, 607, 6527, 751, 3778, 15329, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-03-23 */ /** *Submitted for verification at Etherscan.io on 2021-03-01 */ /** *Submitted for verification at Etherscan.io on 2020-10-19 */ pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns(address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns(bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title Select * @dev Median Selection Library */ library Select { using SafeMath for uint256; /** * @dev Sorts the input array up to the denoted size, and returns the median. * @param array Input array to compute its median. * @param size Number of elements in array to compute the median for. * @return Median of array. */ function computeMedian(uint256[] array, uint256 size) internal pure returns (uint256) { require(size > 0 && array.length >= size); for (uint256 i = 1; i < size; i++) { for (uint256 j = i; j > 0 && array[j-1] > array[j]; j--) { uint256 tmp = array[j]; array[j] = array[j-1]; array[j-1] = tmp; } } if (size % 2 == 1) { return array[size / 2]; } else { return array[size / 2].add(array[size / 2 - 1]) / 2; } } } interface IOracle { function getData() external returns (uint256, bool); } /** * @title Median Oracle * * @notice Provides a value onchain that's aggregated from a whitelisted set of * providers. */ contract MedianOracle is Ownable, IOracle { using SafeMath for uint256; struct Report { uint256 timestamp; uint256 payload; } // Addresses of providers authorized to push reports. address[] public providers; // Address of the target asset. address public targetAsset; // Reports indexed by provider address. Report[0].timestamp > 0 // indicates provider existence. mapping (address => Report[2]) public providerReports; event ProviderAdded(address provider); event ProviderRemoved(address provider); event ReportTimestampOutOfRange(address provider); event ProviderReportPushed(address indexed provider, uint256 payload, uint256 timestamp); // The number of seconds after which the report is deemed expired. uint256 public reportExpirationTimeSec; // The number of seconds since reporting that has to pass before a report // is usable. uint256 public reportDelaySec; // The minimum number of providers with valid reports to consider the // aggregate report valid. uint256 public minimumProviders = 1; // Timestamp of 1 is used to mark uninitialized and invalidated data. // This is needed so that timestamp of 1 is always considered expired. uint256 private constant MAX_REPORT_EXPIRATION_TIME = 520 weeks; /** * @param reportExpirationTimeSec_ The number of seconds after which the * report is deemed expired. * @param reportDelaySec_ The number of seconds since reporting that has to * pass before a report is usable * @param minimumProviders_ The minimum number of providers with valid * reports to consider the aggregate report valid. */ constructor(uint256 reportExpirationTimeSec_, uint256 reportDelaySec_, uint256 minimumProviders_) public { require(reportExpirationTimeSec_ <= MAX_REPORT_EXPIRATION_TIME); require(minimumProviders_ > 0); reportExpirationTimeSec = reportExpirationTimeSec_; reportDelaySec = reportDelaySec_; minimumProviders = minimumProviders_; } /** * @notice Sets the report expiration period. * @param reportExpirationTimeSec_ The number of seconds after which the * report is deemed expired. */ function setReportExpirationTimeSec(uint256 reportExpirationTimeSec_) external onlyOwner { require(reportExpirationTimeSec_ <= MAX_REPORT_EXPIRATION_TIME); reportExpirationTimeSec = reportExpirationTimeSec_; } /** * @notice Sets the time period since reporting that has to pass before a * report is usable. * @param reportDelaySec_ The new delay period in seconds. */ function setReportDelaySec(uint256 reportDelaySec_) external onlyOwner { reportDelaySec = reportDelaySec_; } /** * @notice Sets the minimum number of providers with valid reports to * consider the aggregate report valid. * @param minimumProviders_ The new minimum number of providers. */ function setMinimumProviders(uint256 minimumProviders_) external onlyOwner { require(minimumProviders_ > 0); minimumProviders = minimumProviders_; } /** * @notice Sets the asset contract address to track the price. * @param targetAsset_ Address of the asset token. */ function setTargetAsset( address targetAsset_) external onlyOwner { targetAsset = targetAsset_; } /** * @notice Pushes a report for the calling provider. * @param payload is expected to be 18 decimal fixed point number. */ function pushReport(uint256 payload) external { address providerAddress = msg.sender; Report[2] storage reports = providerReports[providerAddress]; uint256[2] memory timestamps = [reports[0].timestamp, reports[1].timestamp]; require(timestamps[0] > 0); uint8 index_recent = timestamps[0] >= timestamps[1] ? 0 : 1; uint8 index_past = 1 - index_recent; // Check that the push is not too soon after the last one. require(timestamps[index_recent].add(reportDelaySec) <= now); reports[index_past].timestamp = now; reports[index_past].payload = payload; emit ProviderReportPushed(providerAddress, payload, now); } /** * @notice Invalidates the reports of the calling provider. */ function purgeReports() external { address providerAddress = msg.sender; require (providerReports[providerAddress][0].timestamp > 0); providerReports[providerAddress][0].timestamp=1; providerReports[providerAddress][1].timestamp=1; } /** * @notice Computes median of provider reports whose timestamps are in the * valid timestamp range. * @return AggregatedValue: Median of providers reported values. * valid: Boolean indicating an aggregated value was computed successfully. */ function getData() external returns (uint256, bool) { uint256 reportsCount = providers.length; uint256[] memory validReports = new uint256[](reportsCount); uint256 size = 0; uint256 minValidTimestamp = now.sub(reportExpirationTimeSec); uint256 maxValidTimestamp = now.sub(reportDelaySec); for (uint256 i = 0; i < reportsCount; i++) { address providerAddress = providers[i]; Report[2] memory reports = providerReports[providerAddress]; uint8 index_recent = reports[0].timestamp >= reports[1].timestamp ? 0 : 1; uint8 index_past = 1 - index_recent; uint256 reportTimestampRecent = reports[index_recent].timestamp; if (reportTimestampRecent > maxValidTimestamp) { // Recent report is too recent. uint256 reportTimestampPast = providerReports[providerAddress][index_past].timestamp; if (reportTimestampPast < minValidTimestamp) { // Past report is too old. emit ReportTimestampOutOfRange(providerAddress); } else if (reportTimestampPast > maxValidTimestamp) { // Past report is too recent. emit ReportTimestampOutOfRange(providerAddress); } else { // Using past report. validReports[size++] = providerReports[providerAddress][index_past].payload; } } else { // Recent report is not too recent. if (reportTimestampRecent < minValidTimestamp) { // Recent report is too old. emit ReportTimestampOutOfRange(providerAddress); } else { // Using recent report. validReports[size++] = providerReports[providerAddress][index_recent].payload; } } } if (size < minimumProviders) { return (0, false); } return (Select.computeMedian(validReports, size), true); } /** * @notice Authorizes a provider. * @param provider Address of the provider. */ function addProvider(address provider) external onlyOwner { require(providerReports[provider][0].timestamp == 0); providers.push(provider); providerReports[provider][0].timestamp = 1; emit ProviderAdded(provider); } /** * @notice Revokes provider authorization. * @param provider Address of the provider. */ function removeProvider(address provider) external onlyOwner { delete providerReports[provider]; for (uint256 i = 0; i < providers.length; i++) { if (providers[i] == provider) { if (i + 1 != providers.length) { providers[i] = providers[providers.length-1]; } providers.length--; emit ProviderRemoved(provider); break; } } } /** * @return The number of authorized providers. */ function providersSize() external view returns (uint256) { return providers.length; } }
Reports indexed by provider address. Report[0].timestamp > 0 indicates provider existence.
mapping (address => Report[2]) public providerReports;
2,249,585
[ 1, 18631, 8808, 635, 2893, 1758, 18, 8706, 63, 20, 8009, 5508, 405, 374, 8527, 2893, 15782, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 261, 2867, 516, 8706, 63, 22, 5717, 1071, 2893, 18631, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.5.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]. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ contract ReentrancyGuard { bool private _notEntered; constructor () internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/crowdsale/Crowdsale.sol pragma solidity ^0.5.0; /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conforms * the base architecture for crowdsales. It is *not* intended to be modified / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale is Context, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // The token being sold IERC20 private _token; // Address where funds are collected address payable private _wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 private _rate; // Amount of wei raised uint256 private _weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @param rate Number of token units a buyer gets per wei * @dev The rate is the conversion between wei and the smallest and indivisible * token unit. So, if you are using a rate of 1 with a ERC20Detailed token * with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK. * @param wallet Address where collected funds will be forwarded to * @param token Address of the token being sold */ constructor (uint256 rate, address payable wallet, IERC20 token) public { require(rate > 0, "Crowdsale: rate is 0"); require(wallet != address(0), "Crowdsale: wallet is the zero address"); require(address(token) != address(0), "Crowdsale: token is the zero address"); _rate = rate; _wallet = wallet; _token = token; } /** * @dev fallback function ***DO NOT OVERRIDE*** * Note that other contracts will transfer funds with a base gas stipend * of 2300, which is not enough to call buyTokens. Consider calling * buyTokens directly when purchasing tokens from a contract. */ function () external payable { buyTokens(_msgSender()); } /** * @return the token being sold. */ function token() public view returns (IERC20) { return _token; } /** * @return the address where funds are collected. */ function wallet() public view returns (address payable) { return _wallet; } /** * @return the number of token units a buyer gets per wei. */ function rate() public view returns (uint256) { return _rate; } /** * @return the amount of wei raised. */ function weiRaised() public view returns (uint256) { return _weiRaised; } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. * @param beneficiary Recipient of the token purchase */ function buyTokens(address beneficiary) public nonReentrant payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); } /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. * Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(beneficiary, weiAmount); * require(weiRaised().add(weiAmount) <= cap); * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address"); require(weiAmount != 0, "Crowdsale: weiAmount is 0"); this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid * conditions are not met. * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view { // solhint-disable-previous-line no-empty-blocks } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends * its tokens. * @param beneficiary Address performing the token purchase * @param tokenAmount Number of tokens to be emitted */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal { _token.safeTransfer(beneficiary, tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send * tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase(address beneficiary, uint256 tokenAmount) internal { _deliverTokens(beneficiary, tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, * etc.) * @param beneficiary Address receiving the tokens * @param weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal { // solhint-disable-previous-line no-empty-blocks } /** * @dev Override to extend the way in which ether is converted to tokens. * @param weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return weiAmount.mul(_rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { _wallet.transfer(msg.value); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/crowdsale/validation/TimedCrowdsale.sol pragma solidity ^0.5.0; /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 private _openingTime; uint256 private _closingTime; /** * Event for crowdsale extending * @param newClosingTime new closing time * @param prevClosingTime old closing time */ event TimedCrowdsaleExtended(uint256 prevClosingTime, uint256 newClosingTime); /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { require(isOpen(), "TimedCrowdsale: not open"); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param openingTime Crowdsale opening time * @param closingTime Crowdsale closing time */ constructor (uint256 openingTime, uint256 closingTime) public { // solhint-disable-next-line not-rely-on-time require(openingTime >= block.timestamp, "TimedCrowdsale: opening time is before current time"); // solhint-disable-next-line max-line-length require(closingTime > openingTime, "TimedCrowdsale: opening time is not before closing time"); _openingTime = openingTime; _closingTime = closingTime; } /** * @return the crowdsale opening time. */ function openingTime() public view returns (uint256) { return _openingTime; } /** * @return the crowdsale closing time. */ function closingTime() public view returns (uint256) { return _closingTime; } /** * @return true if the crowdsale is open, false otherwise. */ function isOpen() public view returns (bool) { // solhint-disable-next-line not-rely-on-time return block.timestamp >= _openingTime && block.timestamp <= _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solhint-disable-next-line not-rely-on-time return block.timestamp > _closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period. * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal onlyWhileOpen view { super._preValidatePurchase(beneficiary, weiAmount); } /** * @dev Extend crowdsale. * @param newClosingTime Crowdsale closing time */ function _extendTime(uint256 newClosingTime) internal { require(!hasClosed(), "TimedCrowdsale: already closed"); // solhint-disable-next-line max-line-length require(newClosingTime > _closingTime, "TimedCrowdsale: new closing time is before current closing time"); emit TimedCrowdsaleExtended(_closingTime, newClosingTime); _closingTime = newClosingTime; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/ownership/Secondary.sol pragma solidity ^0.5.0; /** * @dev A Secondary contract can only be used by its primary account (the one that created it). */ contract Secondary is Context { address private _primary; /** * @dev Emitted when the primary contract changes. */ event PrimaryTransferred( address recipient ); /** * @dev Sets the primary account to the one that is creating the Secondary contract. */ constructor () internal { address msgSender = _msgSender(); _primary = msgSender; emit PrimaryTransferred(msgSender); } /** * @dev Reverts if called from any account other than the primary. */ modifier onlyPrimary() { require(_msgSender() == _primary, "Secondary: caller is not the primary account"); _; } /** * @return the address of the primary. */ function primary() public view returns (address) { return _primary; } /** * @dev Transfers contract to a new primary. * @param recipient The address of new primary. */ function transferPrimary(address recipient) public onlyPrimary { require(recipient != address(0), "Secondary: new primary is the zero address"); _primary = recipient; emit PrimaryTransferred(recipient); } } // File: tokenVesting.sol pragma solidity ^0.5.0; /** * @title PostDeliveryCrowdsale * @dev Crowdsale that locks tokens from withdrawal until it ends. */ contract PostDeliveryCrowdsale is TimedCrowdsale { using SafeMath for uint256; uint contractCreationTime; uint monthTime = 2592000; uint public timeToWait; uint public initialEmission; uint public months; uint public lastFunctioncalled; mapping(address => uint256) private _balances; mapping(address => uint256) private _totalClaimed; __unstable__TokenVault private _vault; constructor(uint _initialEmission, uint _timeToWait, uint _months) public { require(_timeToWait>0, "TimeToWait is 0"); uint closingTime = closingTime(); contractCreationTime = closingTime; initialEmission = _initialEmission; timeToWait = _timeToWait ; months = _months; _vault = new __unstable__TokenVault(); } function currentRetractableTokens(address beneficiary) view public returns(uint){ require(hasClosed(), "PostDeliveryCrowdsale: not closed"); uint256 amount = _balances[beneficiary]; uint realAmount; if(amount<=0){ return 0; } uint since = block.timestamp - contractCreationTime; if(initialEmission==100){ return amount; } else if((since/monthTime)< timeToWait){ realAmount = ((initialEmission*(amount+_totalClaimed[beneficiary]))/100) - _totalClaimed[beneficiary]; return realAmount; } else { uint restEmission = 100 - initialEmission; realAmount = ((initialEmission*(amount+_totalClaimed[beneficiary]))/100) + (restEmission*(amount + _totalClaimed[beneficiary])*((since/monthTime) + 1 - timeToWait)/months/100) - _totalClaimed[beneficiary]; if(realAmount==0){ return 0; } if(realAmount>_balances[beneficiary]){ realAmount = _balances[beneficiary]; } return realAmount; } } /** * @dev Withdraw tokens only after crowdsale ends. * @param beneficiary Whose tokens will be withdrawn. */ function withdrawTokens(address beneficiary) public { require(hasClosed(), "PostDeliveryCrowdsale: not closed"); uint256 amount = _balances[beneficiary]; uint realAmount; require(amount > 0, "PostDeliveryCrowdsale: beneficiary is not due any tokens"); uint since = block.timestamp - contractCreationTime; if(initialEmission==100){ _balances[beneficiary] = 0; _vault.transfer(token(), beneficiary, amount); _totalClaimed[beneficiary] += amount; lastFunctioncalled = 1; } else if((since/monthTime)< timeToWait){ realAmount = ((initialEmission*amount)/100) - _totalClaimed[beneficiary]; require(realAmount>0,"Current Retractable Amount 0"); _balances[beneficiary] -= realAmount ; _vault.transfer(token(), beneficiary, realAmount); _totalClaimed[beneficiary] += realAmount; lastFunctioncalled =2; } else { uint restEmission = 100 - initialEmission; realAmount = ((initialEmission*(amount+_totalClaimed[beneficiary]))/100) + (restEmission*(amount + _totalClaimed[beneficiary])*((since/monthTime) + 1 - timeToWait)/months/100) - _totalClaimed[beneficiary]; require(realAmount>0,"Current Retractable Amount 0"); if(realAmount>_balances[beneficiary]){ _totalClaimed[beneficiary] += _balances[beneficiary]; realAmount = _balances[beneficiary]; lastFunctioncalled = 3; } _balances[beneficiary] -= realAmount ; _vault.transfer(token(), beneficiary, realAmount); _totalClaimed[beneficiary] += realAmount; lastFunctioncalled = 4; } } /** * @return the balance of an account. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev Overrides parent by storing due balances, and delivering tokens to the vault instead of the end user. This * ensures that the tokens will be available by the time they are withdrawn (which may not be the case if * `_deliverTokens` was called later). * @param beneficiary Token purchaser * @param tokenAmount Amount of tokens purchased */ function _processPurchase(address beneficiary, uint256 tokenAmount) internal { _balances[beneficiary] = _balances[beneficiary].add(tokenAmount); _deliverTokens(address(_vault), tokenAmount); } } /** * @title __unstable__TokenVault * @dev Similar to an Escrow for tokens, this contract allows its primary account to spend its tokens as it sees fit. * This contract is an internal helper for PostDeliveryCrowdsale, and should not be used outside of this context. */ // solhint-disable-next-line contract-name-camelcase contract __unstable__TokenVault is Secondary { function transfer(IERC20 token, address to, uint256 amount) public onlyPrimary { token.transfer(to, amount); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/crowdsale/distribution/FinalizableCrowdsale.sol pragma solidity ^0.5.0; /** * @title FinalizableCrowdsale * @dev Extension of TimedCrowdsale with a one-off finalization action, where one * can do extra work after finishing. */ contract FinalizableCrowdsale is TimedCrowdsale { using SafeMath for uint256; bool private _finalized; event CrowdsaleFinalized(); constructor () internal { _finalized = false; } /** * @return true if the crowdsale is finalized, false otherwise. */ function finalized() public view returns (bool) { return _finalized; } /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() public { require(!_finalized, "FinalizableCrowdsale: already finalized"); require(hasClosed(), "FinalizableCrowdsale: not closed"); _finalized = true; _finalization(); emit CrowdsaleFinalized(); } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super._finalization() to ensure the chain of finalization is * executed entirely. */ function _finalization() internal { // solhint-disable-previous-line no-empty-blocks } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/crowdsale/validation/CappedCrowdsale.sol pragma solidity ^0.5.0; /** * @title CappedCrowdsale * @dev Crowdsale with a limit for total contributions. */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 private _cap; /** * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. * @param cap Max amount of wei to be contributed */ constructor (uint256 cap) public { require(cap > 0, "CappedCrowdsale: cap is 0"); _cap = cap; } /** * @return the cap of the crowdsale. */ function cap() public view returns (uint256) { return _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised() >= _cap; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { super._preValidatePurchase(beneficiary, weiAmount); require(weiRaised().add(weiAmount) <= _cap, "CappedCrowdsale: cap exceeded"); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @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]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.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' // 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"); } } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: ICO.sol // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.5.0; // import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/crowdsale/distribution/PostDeliveryCrowdsale.sol"; // import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v2.5.0/contracts/crowdsale/distribution/PostDeliveryCrowdsale.sol"; interface UniswapRouter { function WETH() external pure returns (address); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); } contract IDO1 is Crowdsale, TimedCrowdsale, CappedCrowdsale, FinalizableCrowdsale, PostDeliveryCrowdsale{ address payable treasury = address(0xc020B4B710B5c2264a5a52931933Ff3753f54897); address payable fee2address = address(0xE609192618aD9aC825B981fFECf3Dfd5E92E3cFB); string public name; IERC20 projectToken; //UniswapRouter public UNIROUTER = UniswapRouter(0xD99D1c33F9fC3444f8101754aBC46c52416550D1); UniswapRouter public UNIROUTER = UniswapRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); uint firstPhaseDuration; uint durationDays; IERC20 public wDarkPylon = IERC20(0x9E6Ca603238Fc4d1F0c49e7E4c6bcb793b1af8Ed); //IERC20 public wDarkPylon = IERC20(0xDF58C9A37Dc1f20C310cc482f8ecA2Bab05D7e67); uint public minDPLN; uint public phaseEnd; uint public totalEnd; uint public weiCap; constructor( string memory _name, uint rate, address payable wallet, IERC20 _token, uint _startTimeEpoch, uint _firstPhaseDuration, uint _durationDays, uint _weiCap, uint _minDPLN, uint[] memory postd //change timedcrowdsale parameters ) Crowdsale(rate, wallet, _token) PostDeliveryCrowdsale(postd[0], postd[1], postd[2]) CappedCrowdsale(_weiCap) TimedCrowdsale(_startTimeEpoch,_startTimeEpoch+(_durationDays*24*60*60)) FinalizableCrowdsale() public { require(_durationDays>_firstPhaseDuration,"Duration < First Phase"); require(_minDPLN>=250000000000000000000, "minDPLN is less"); minDPLN = _minDPLN; name = _name; firstPhaseDuration = _firstPhaseDuration; durationDays = _durationDays; weiCap = _weiCap; // change phaseEnd and totalEnd phaseEnd = _startTimeEpoch + (firstPhaseDuration*24*60*60); totalEnd = _startTimeEpoch + (durationDays*24*60*60); projectToken = _token; } function buyTokensfromTokens(address beneficiary, address _token, uint _amount) public{ require(_amount>0, "Input Token Amount is 0"); IERC20 token = IERC20(_token); token.transferFrom(msg.sender,address(this),_amount); address[] memory path = new address[](2); path[0] = _token; path[1] = UNIROUTER.WETH(); token.approve(address(UNIROUTER),_amount); uint b1 = address(this).balance; UNIROUTER.swapExactTokensForETH(_amount, 0, path, address(this), block.timestamp+180); uint b2 = address(this).balance; uint finalAmount = b2.sub(b1); this.buyTokens.value(finalAmount)(beneficiary); } function _finalization() internal { uint projectBalanceLeft = projectToken.balanceOf(address(this)); projectToken.transfer(wallet(),projectBalanceLeft); super._finalization(); } function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address"); require(weiAmount != 0, "Crowdsale: weiAmount is 0"); uint wDLONBal = wDarkPylon.balanceOf(beneficiary); uint totalwDLON = wDarkPylon.totalSupply(); if(phaseEnd>block.timestamp){ require(wDLONBal >= minDPLN , "Min darkPYLON not available"); require( ((weiAmount*10000)/weiCap)<((wDLONBal*10000)/totalwDLON), "Stake Percentage in DARK PYLON is low" ); } require( wDLONBal>250000000000000000000 , "DLON less than 250"); this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 } function _forwardFunds() internal { wallet().transfer((msg.value*98)/100); treasury.transfer(msg.value/100); fee2address.transfer(msg.value/100); } function () payable external{ //call your function here / implement your actions } } // File: idoFactory.sol // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.5.0; contract idoFactory{ mapping (uint => address) public IDOaddresses; uint public addressID; event IDOcreated(string name, uint rate, IERC20 token, uint variant, address IDOaddress); constructor() public { } function getTotalIDOs() public view returns(uint){ return (addressID); } function releaseIDO( string memory name, uint variant, uint rate, address payable wallet, IERC20 token, uint _startTimeEpoch, uint _firstPhaseDuration, uint _durationDays, uint _weiCap, uint _initialEmission, uint _timeToWait, uint _months ) public{ require( variant>0 , 'Select Correct Version'); require( variant<5 , 'Select Correct Version'); if(variant==1){ uint[] memory postd = new uint[](3); postd[0] = _initialEmission; postd[1] = _timeToWait; postd[2] = _months; IDO1 new1 = new IDO1( name, rate, wallet, token, _startTimeEpoch, _firstPhaseDuration, _durationDays, _weiCap, 250000000000000000000, postd); addressID += 1; IDOaddresses[addressID] = address(new1); } if(variant==2){ uint[] memory postd = new uint[](3); postd[0] = _initialEmission; postd[1] = _timeToWait; postd[2] = _months; IDO1 new1 = new IDO1( name, rate, wallet, token, _startTimeEpoch, _firstPhaseDuration, _durationDays, _weiCap, 1000000000000000000000, postd); addressID += 1; IDOaddresses[addressID] = address(new1); } if(variant==3){ uint[] memory postd = new uint[](3); postd[0] = _initialEmission; postd[1] = _timeToWait; postd[2] = _months; IDO1 new1 = new IDO1( name, rate, wallet, token, _startTimeEpoch, _firstPhaseDuration, _durationDays, _weiCap, 5000000000000000000000, postd); addressID += 1; IDOaddresses[addressID] = address(new1); } if(variant==4){ uint[] memory postd = new uint[](3); postd[0] = _initialEmission; postd[1] = _timeToWait; postd[2] = _months; IDO1 new1 = new IDO1( name, rate, wallet, token, _startTimeEpoch, _firstPhaseDuration, _durationDays, _weiCap, 10000000000000000000000, postd); addressID += 1; IDOaddresses[addressID] = address(new1); } emit IDOcreated(name, rate, token, variant, IDOaddresses[addressID]); } }
call your function here / implement your actions
function () payable external{ }
636,201
[ 1, 1991, 3433, 445, 2674, 342, 2348, 3433, 4209, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 445, 1832, 8843, 429, 3903, 95, 203, 225, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]