├── test └── .gitkeep ├── audits ├── 5_6149884003794027306.pdf ├── PeckShield-Audit-Report-OptionsLM-v1.0.pdf └── PeckShield-Audit-Report-StableV1Pair-v1.0.pdf ├── migrations └── 1_initial_migration.js ├── contracts ├── Migrations.sol ├── GaugeProxy.sol ├── OptionsLM.sol └── rKP3R.sol ├── README.md └── truffle-config.js /test/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /audits/5_6149884003794027306.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/keep3r-network/OptionsLM/HEAD/audits/5_6149884003794027306.pdf -------------------------------------------------------------------------------- /audits/PeckShield-Audit-Report-OptionsLM-v1.0.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/keep3r-network/OptionsLM/HEAD/audits/PeckShield-Audit-Report-OptionsLM-v1.0.pdf -------------------------------------------------------------------------------- /audits/PeckShield-Audit-Report-StableV1Pair-v1.0.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/keep3r-network/OptionsLM/HEAD/audits/PeckShield-Audit-Report-StableV1Pair-v1.0.pdf -------------------------------------------------------------------------------- /migrations/1_initial_migration.js: -------------------------------------------------------------------------------- 1 | const Migrations = artifacts.require("Migrations"); 2 | 3 | module.exports = function (deployer) { 4 | deployer.deploy(Migrations); 5 | }; 6 | -------------------------------------------------------------------------------- /contracts/Migrations.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity >=0.4.22 <0.9.0; 3 | 4 | contract Migrations { 5 | address public owner = msg.sender; 6 | uint public last_completed_migration; 7 | 8 | modifier restricted() { 9 | require( 10 | msg.sender == owner, 11 | "This function is restricted to the contract's owner" 12 | ); 13 | _; 14 | } 15 | 16 | function setCompleted(uint completed) public restricted { 17 | last_completed_migration = completed; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # History 2 | 3 | Liquidity Mining / Rewards / Incentives, whatever you want to call them, are innately part of crypto. Even proof of work (mining) is providing something for rewards (in proof of work, providing security [or rather electricity] for crypto) 4 | The first (to my knowledge) to provide rewards for liquidity was synthetix.io, this started with the sETH/ETH pool, which eventually moved to the sUSD curve.fi pool. If you provided liquidity to these pools, you were rewarded with SNX (the native Synthetix token). 5 | The somewhat legendary StakingRewards contract, was originally developed in partnership with Anton from 1inch.exchange. This contract became the base for what is liquidity mining as we know it today. 6 | 7 | # Problem Statement 8 | 9 | As liquidity mining grew, some, non deal-breaking, flaws became apparent. I believe the following two to be the most destressing; 10 | 11 | * Liquidity locusts (or loyalty), also referred to as “stickiness” 12 | * Token loyalty, or opportunistic dumping 13 | 14 | Liquidity quickly disappears when incentives cease, and aggressive liquidity programs can often have a detriment on the token price, which, while I believe the latter to not necessarily be a bad thing (since it entirely depends on the tokenomics / purpose), from public perception, it is clear, when price goes down, a project is a scam. 15 | 16 | # Problem Example 17 | 18 | I believe, at its core, the problem is the “something for nothing” problem. If you receive something for nothing, you will simply bank your profits. Let’s take curve.fi as a practical example, if you provide liquidity in the form of DAI/USDC/USDT to the 3pool, you receive CRV rewards. For the sake of this example, lets assume the liquidity provider is a liquidity locust, so they are only interested in receiving CRV and immediately selling it for more DAI/USDC/USDT. 19 | 20 | The reason for this, is that they received “something” for practically “nothing”. Provide liquidity, get rewarded, that simple. 21 | 22 | # Quick Intro to Options 23 | 24 | Going to try to keep this simple, there are two options, a PUT (the right to sell), and a CALL (the right to buy). In this case, you can think of a PUT as a market sell, and a CALL as a market buy. So continuing with using CRV, for purpose of simplicity, lets say CRV is trading at $2. A CALL option with a strike priceof $2, would allow me to buy CRV at $2, a PUT option with a strike priceof $2, would allow me to sell CRV at $2. 25 | 26 | For the rest of this article, we will only focus on CALL, the right to buy. So an option has 3 basic properties; 27 | 28 | * What are you buying? (In our example CRV) 29 | * What is the strike price? (aka, how much are you paying for it? In our example $2 ~ or 2 DAI) 30 | * When is the expiry? (normally some future date, in our example, expiry was current timestamp/now) 31 | 32 | # Liquidity Mining as Options 33 | 34 | Keeping with our curve.fi example, if you provide liquidity and you claim CRV as rewards, this can be seen as exercising a CRV CALL option with strike price $0, and expiry now. When you start thinking about it in terms of CALL options, all of a sudden it gives the project a lot more power, per example, now a project could offer it as; 35 | 36 | * strike price = spot - 50% 37 | * expiry = current date + 1 month 38 | 39 | At its most basic level, we could simply say, expiry = now and strike price = spot - 50%, what would this mean? Let’s say the liquidity miner, mined 1000 CRV, instead of simply receiving the CRV CALL option at strike price $0 and expiry now (1000 tokens for free), now instead they would receive the right to purchase 1000 CRV at $1000. Even if they are a liquidity locust, they would still be incentivized to do this, since they still make $1000 profit (trading value 1000 CRV @ $2 =$2000 - $1000 purchase). 40 | 41 | The “profits” ($1000 in above example), can now be distributed to veCRV holders, or go to the foundation, treasury DAO, etc. These funds could even be used to market make and provide additional liquidity. 42 | 43 | Now, lets take it one step further, and add a future expiry, lets say 1 month, now for argument sake, everyone that was receiving liquidity was claiming and dumping, so 1 month alter the price is $1, but the CALL option price was also $1, so at this point, there is no reason for the “dumper” to claim the option anymore, since they wouldn’t make additional profit. So this further means that it set an additional price floor for the received tokens. As these tokens will simply not be claimed (can even be sent back to the DAO) 44 | 45 | # Conclusion 46 | 47 | Making a few simple modifications to the existing StakingRewards contract allows us to add the above functionality, while keeping the same UX and user experience. 48 | 49 | Prototype code available here 50 | 51 | By switching to Options Liquidity Mining instead of traditional Liquidity Mining it means; 52 | 53 | * Decreased liquidity locusts 54 | * Decrease selling pressure 55 | * Natural price floor (twap - discount % over epoch) 56 | * Additional fee revenue for DAO/token holders 57 | -------------------------------------------------------------------------------- /truffle-config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Use this file to configure your truffle project. It's seeded with some 3 | * common settings for different networks and features like migrations, 4 | * compilation and testing. Uncomment the ones you need or modify 5 | * them to suit your project as necessary. 6 | * 7 | * More information about configuration can be found at: 8 | * 9 | * trufflesuite.com/docs/advanced/configuration 10 | * 11 | * To deploy via Infura you'll need a wallet provider (like @truffle/hdwallet-provider) 12 | * to sign your transactions before they're sent to a remote public node. Infura accounts 13 | * are available for free at: infura.io/register. 14 | * 15 | * You'll also need a mnemonic - the twelve word phrase the wallet uses to generate 16 | * public/private key pairs. If you're publishing your code to GitHub make sure you load this 17 | * phrase from a file you've .gitignored so it doesn't accidentally become public. 18 | * 19 | */ 20 | 21 | // const HDWalletProvider = require('@truffle/hdwallet-provider'); 22 | // 23 | // const fs = require('fs'); 24 | // const mnemonic = fs.readFileSync(".secret").toString().trim(); 25 | 26 | module.exports = { 27 | /** 28 | * Networks define how you connect to your ethereum client and let you set the 29 | * defaults web3 uses to send transactions. If you don't specify one truffle 30 | * will spin up a development blockchain for you on port 9545 when you 31 | * run `develop` or `test`. You can ask a truffle command to use a specific 32 | * network from the command line, e.g 33 | * 34 | * $ truffle test --network 35 | */ 36 | 37 | networks: { 38 | // Useful for testing. The `development` name is special - truffle uses it by default 39 | // if it's defined here and no other network is specified at the command line. 40 | // You should run a client (like ganache-cli, geth or parity) in a separate terminal 41 | // tab if you use this network and you must also set the `host`, `port` and `network_id` 42 | // options below to some value. 43 | // 44 | // development: { 45 | // host: "127.0.0.1", // Localhost (default: none) 46 | // port: 8545, // Standard Ethereum port (default: none) 47 | // network_id: "*", // Any network (default: none) 48 | // }, 49 | // Another network with more advanced options... 50 | // advanced: { 51 | // port: 8777, // Custom port 52 | // network_id: 1342, // Custom network 53 | // gas: 8500000, // Gas sent with each transaction (default: ~6700000) 54 | // gasPrice: 20000000000, // 20 gwei (in wei) (default: 100 gwei) 55 | // from:
, // Account to send txs from (default: accounts[0]) 56 | // websocket: true // Enable EventEmitter interface for web3 (default: false) 57 | // }, 58 | // Useful for deploying to a public network. 59 | // NB: It's important to wrap the provider as a function. 60 | // ropsten: { 61 | // provider: () => new HDWalletProvider(mnemonic, `https://ropsten.infura.io/v3/YOUR-PROJECT-ID`), 62 | // network_id: 3, // Ropsten's id 63 | // gas: 5500000, // Ropsten has a lower block limit than mainnet 64 | // confirmations: 2, // # of confs to wait between deployments. (default: 0) 65 | // timeoutBlocks: 200, // # of blocks before a deployment times out (minimum/default: 50) 66 | // skipDryRun: true // Skip dry run before migrations? (default: false for public nets ) 67 | // }, 68 | // Useful for private networks 69 | // private: { 70 | // provider: () => new HDWalletProvider(mnemonic, `https://network.io`), 71 | // network_id: 2111, // This network is yours, in the cloud. 72 | // production: true // Treats this network as if it was a public net. (default: false) 73 | // } 74 | }, 75 | 76 | // Set default mocha options here, use special reporters etc. 77 | mocha: { 78 | // timeout: 100000 79 | }, 80 | 81 | // Configure your compilers 82 | compilers: { 83 | solc: { 84 | // version: "0.5.1", // Fetch exact version from solc-bin (default: truffle's version) 85 | // docker: true, // Use "0.5.1" you've installed locally with docker (default: false) 86 | // settings: { // See the solidity docs for advice about optimization and evmVersion 87 | // optimizer: { 88 | // enabled: false, 89 | // runs: 200 90 | // }, 91 | // evmVersion: "byzantium" 92 | // } 93 | } 94 | }, 95 | 96 | // Truffle DB is currently disabled by default; to enable it, change enabled: false to enabled: true 97 | // 98 | // Note: if you migrated your contracts prior to enabling this field in your Truffle project and want 99 | // those previously migrated contracts available in the .db directory, you will need to run the following: 100 | // $ truffle migrate --reset --compile-all 101 | 102 | db: { 103 | enabled: false 104 | } 105 | }; 106 | -------------------------------------------------------------------------------- /contracts/GaugeProxy.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.7; 3 | 4 | library Math { 5 | function max(uint a, uint b) internal pure returns (uint) { 6 | return a >= b ? a : b; 7 | } 8 | function min(uint a, uint b) internal pure returns (uint) { 9 | return a < b ? a : b; 10 | } 11 | } 12 | 13 | interface erc20 { 14 | function totalSupply() external view returns (uint256); 15 | function transfer(address recipient, uint amount) external returns (bool); 16 | function decimals() external view returns (uint8); 17 | function balanceOf(address) external view returns (uint); 18 | function transferFrom(address sender, address recipient, uint amount) external returns (bool); 19 | function approve(address spender, uint value) external returns (bool); 20 | } 21 | 22 | interface ve { 23 | function locked__end(address) external view returns (uint); 24 | function deposit_for(address, uint) external; 25 | } 26 | 27 | interface delegate { 28 | function get_adjusted_ve_balance(address, address) external view returns (uint); 29 | } 30 | 31 | interface Gauge { 32 | function deposit_reward_token(address, uint) external; 33 | } 34 | 35 | contract GaugeProxy { 36 | address constant _rkp3r = 0xEdB67Ee1B171c4eC66E6c10EC43EDBbA20FaE8e9; 37 | address constant _vkp3r = 0x2FC52C61fB0C03489649311989CE2689D93dC1a2; 38 | address constant ZERO_ADDRESS = 0x0000000000000000000000000000000000000000; 39 | 40 | uint public totalWeight; 41 | 42 | address public gov; 43 | address public nextgov; 44 | uint public commitgov; 45 | uint public constant delay = 1 days; 46 | 47 | address[] internal _tokens; 48 | mapping(address => address) public gauges; // token => gauge 49 | mapping(address => uint) public weights; // token => weight 50 | mapping(address => mapping(address => uint)) public votes; // msg.sender => votes 51 | mapping(address => address[]) public tokenVote;// msg.sender => token 52 | mapping(address => uint) public usedWeights; // msg.sender => total voting weight of user 53 | mapping(address => bool) public enabled; 54 | 55 | function tokens() external view returns (address[] memory) { 56 | return _tokens; 57 | } 58 | 59 | constructor() { 60 | gov = msg.sender; 61 | } 62 | 63 | modifier g() { 64 | require(msg.sender == gov); 65 | _; 66 | } 67 | 68 | function setGov(address _gov) external g { 69 | nextgov = _gov; 70 | commitgov = block.timestamp + delay; 71 | } 72 | 73 | function acceptGov() external { 74 | require(msg.sender == nextgov && commitgov < block.timestamp); 75 | gov = nextgov; 76 | } 77 | 78 | function reset() external { 79 | _reset(msg.sender); 80 | } 81 | 82 | function _reset(address _owner) internal { 83 | address[] storage _tokenVote = tokenVote[_owner]; 84 | uint _tokenVoteCnt = _tokenVote.length; 85 | 86 | for (uint i = 0; i < _tokenVoteCnt; i ++) { 87 | address _token = _tokenVote[i]; 88 | uint _votes = votes[_owner][_token]; 89 | 90 | if (_votes > 0) { 91 | totalWeight -= _votes; 92 | weights[_token] -= _votes; 93 | votes[_owner][_token] = 0; 94 | } 95 | } 96 | 97 | delete tokenVote[_owner]; 98 | } 99 | 100 | function poke(address _owner) public { 101 | address[] memory _tokenVote = tokenVote[_owner]; 102 | uint _tokenCnt = _tokenVote.length; 103 | uint[] memory _weights = new uint[](_tokenCnt); 104 | 105 | uint _prevUsedWeight = usedWeights[_owner]; 106 | uint _weight = delegate(_vkp3r).get_adjusted_ve_balance(_owner, ZERO_ADDRESS); 107 | 108 | for (uint i = 0; i < _tokenCnt; i ++) { 109 | uint _prevWeight = votes[_owner][_tokenVote[i]]; 110 | _weights[i] = _prevWeight * _weight / _prevUsedWeight; 111 | } 112 | 113 | _vote(_owner, _tokenVote, _weights); 114 | } 115 | 116 | function _vote(address _owner, address[] memory _tokenVote, uint[] memory _weights) internal { 117 | // _weights[i] = percentage * 100 118 | _reset(_owner); 119 | uint _tokenCnt = _tokenVote.length; 120 | uint _weight = delegate(_vkp3r).get_adjusted_ve_balance(_owner, ZERO_ADDRESS); 121 | uint _totalVoteWeight = 0; 122 | uint _usedWeight = 0; 123 | 124 | for (uint i = 0; i < _tokenCnt; i ++) { 125 | _totalVoteWeight += _weights[i]; 126 | } 127 | 128 | for (uint i = 0; i < _tokenCnt; i ++) { 129 | address _token = _tokenVote[i]; 130 | address _gauge = gauges[_token]; 131 | uint _tokenWeight = _weights[i] * _weight / _totalVoteWeight; 132 | 133 | if (_gauge != address(0x0)) { 134 | _usedWeight += _tokenWeight; 135 | totalWeight += _tokenWeight; 136 | weights[_token] += _tokenWeight; 137 | tokenVote[_owner].push(_token); 138 | votes[_owner][_token] = _tokenWeight; 139 | } 140 | } 141 | 142 | usedWeights[_owner] = _usedWeight; 143 | } 144 | 145 | function vote(address[] calldata _tokenVote, uint[] calldata _weights) external { 146 | require(_tokenVote.length == _weights.length); 147 | _vote(msg.sender, _tokenVote, _weights); 148 | } 149 | 150 | function addGauge(address _token, address _gauge) external g { 151 | require(gauges[_token] == address(0x0), "exists"); 152 | _safeApprove(_rkp3r, _gauge, type(uint).max); 153 | gauges[_token] = _gauge; 154 | enabled[_token] = true; 155 | _tokens.push(_token); 156 | } 157 | 158 | function disable(address _token) external g { 159 | enabled[_token] = false; 160 | } 161 | 162 | function enable(address _token) external g { 163 | enabled[_token] = true; 164 | } 165 | 166 | function length() external view returns (uint) { 167 | return _tokens.length; 168 | } 169 | 170 | function distribute() external g { 171 | uint _balance = erc20(_rkp3r).balanceOf(address(this)); 172 | if (_balance > 0 && totalWeight > 0) { 173 | uint _totalWeight = totalWeight; 174 | for (uint i = 0; i < _tokens.length; i++) { 175 | if (!enabled[_tokens[i]]) { 176 | _totalWeight -= weights[_tokens[i]]; 177 | } 178 | } 179 | for (uint x = 0; x < _tokens.length; x++) { 180 | if (enabled[_tokens[x]]) { 181 | uint _reward = _balance * weights[_tokens[x]] / _totalWeight; 182 | if (_reward > 0) { 183 | address _gauge = gauges[_tokens[x]]; 184 | Gauge(_gauge).deposit_reward_token(_rkp3r, _reward); 185 | } 186 | } 187 | } 188 | } 189 | } 190 | 191 | function _safeApprove(address token, address spender, uint256 value) internal { 192 | (bool success, bytes memory data) = 193 | token.call(abi.encodeWithSelector(erc20.approve.selector, spender, value)); 194 | require(success && (data.length == 0 || abi.decode(data, (bool)))); 195 | } 196 | } 197 | -------------------------------------------------------------------------------- /contracts/OptionsLM.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity 0.8.6; 3 | 4 | interface IERC165 { 5 | function supportsInterface(bytes4 interfaceId) external view returns (bool); 6 | } 7 | 8 | library Strings { 9 | function toString(uint value) internal pure returns (string memory) { 10 | if (value == 0) { 11 | return "0"; 12 | } 13 | uint temp = value; 14 | uint digits; 15 | while (temp != 0) { 16 | digits++; 17 | temp /= 10; 18 | } 19 | bytes memory buffer = new bytes(digits); 20 | uint index = digits - 1; 21 | temp = value; 22 | while (temp != 0) { 23 | buffer[index--] = bytes1(uint8(48 + (temp % 10))); 24 | temp /= 10; 25 | } 26 | return string(buffer); 27 | } 28 | } 29 | 30 | interface IERC721 is IERC165 { 31 | event Transfer(address indexed from, address indexed to, uint indexed tokenId); 32 | event Approval(address indexed owner, address indexed approved, uint indexed tokenId); 33 | event ApprovalForAll(address indexed owner, address indexed operator, bool approved); 34 | function balanceOf(address owner) external view returns (uint balance); 35 | function ownerOf(uint tokenId) external view returns (address owner); 36 | function safeTransferFrom(address from, address to, uint tokenId) external; 37 | function transferFrom(address from, address to, uint tokenId) external; 38 | function approve(address to, uint tokenId) external; 39 | function getApproved(uint tokenId) external view returns (address operator); 40 | function setApprovalForAll(address operator, bool _approved) external; 41 | function isApprovedForAll(address owner, address operator) external view returns (bool); 42 | function safeTransferFrom(address from, address to, uint tokenId, bytes calldata data) external; 43 | } 44 | 45 | interface IERC721Metadata is IERC721 { 46 | function name() external view returns (string memory); 47 | function symbol() external view returns (string memory); 48 | function tokenURI(uint tokenId) external view returns (string memory); 49 | } 50 | 51 | interface IERC721Enumerable is IERC721 { 52 | function totalSupply() external view returns (uint); 53 | function tokenOfOwnerByIndex(address owner, uint index) external view returns (uint tokenId); 54 | function tokenByIndex(uint index) external view returns (uint); 55 | } 56 | 57 | interface IERC721Receiver { 58 | function onERC721Received(address operator, address from, uint tokenId, bytes calldata data) 59 | external returns (bytes4); 60 | } 61 | 62 | contract ERC165 is IERC165 { 63 | bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; 64 | mapping(bytes4 => bool) private _supportedInterfaces; 65 | 66 | constructor () { 67 | _registerInterface(_INTERFACE_ID_ERC165); 68 | } 69 | function supportsInterface(bytes4 interfaceId) public view override returns (bool) { 70 | return _supportedInterfaces[interfaceId]; 71 | } 72 | function _registerInterface(bytes4 interfaceId) internal virtual { 73 | require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); 74 | _supportedInterfaces[interfaceId] = true; 75 | } 76 | } 77 | 78 | library EnumerableSet { 79 | struct Set { 80 | bytes32[] _values; 81 | mapping (bytes32 => uint) _indexes; 82 | } 83 | 84 | function _add(Set storage set, bytes32 value) private returns (bool) { 85 | if (!_contains(set, value)) { 86 | set._values.push(value); 87 | set._indexes[value] = set._values.length; 88 | return true; 89 | } else { 90 | return false; 91 | } 92 | } 93 | 94 | function _remove(Set storage set, bytes32 value) private returns (bool) { 95 | // We read and store the value's index to prevent multiple reads from the same storage slot 96 | uint valueIndex = set._indexes[value]; 97 | 98 | if (valueIndex != 0) { // Equivalent to contains(set, value) 99 | // To delete an element from the _values array in O(1), we swap the element to delete with the last one in 100 | // the array, and then remove the last element (sometimes called as 'swap and pop'). 101 | // This modifies the order of the array, as noted in {at}. 102 | 103 | uint toDeleteIndex = valueIndex - 1; 104 | uint lastIndex = set._values.length - 1; 105 | 106 | // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs 107 | // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. 108 | 109 | bytes32 lastvalue = set._values[lastIndex]; 110 | 111 | // Move the last value to the index where the value to delete is 112 | set._values[toDeleteIndex] = lastvalue; 113 | // Update the index for the moved value 114 | set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based 115 | 116 | // Delete the slot where the moved value was stored 117 | set._values.pop(); 118 | 119 | // Delete the index for the deleted slot 120 | delete set._indexes[value]; 121 | 122 | return true; 123 | } else { 124 | return false; 125 | } 126 | } 127 | 128 | function _contains(Set storage set, bytes32 value) private view returns (bool) { 129 | return set._indexes[value] != 0; 130 | } 131 | 132 | function _length(Set storage set) private view returns (uint) { 133 | return set._values.length; 134 | } 135 | 136 | function _at(Set storage set, uint index) private view returns (bytes32) { 137 | require(set._values.length > index, "EnumerableSet: index out of bounds"); 138 | return set._values[index]; 139 | } 140 | 141 | struct AddressSet { 142 | Set _inner; 143 | } 144 | 145 | function add(AddressSet storage set, address value) internal returns (bool) { 146 | return _add(set._inner, bytes32(uint(uint160(value)))); 147 | } 148 | 149 | function remove(AddressSet storage set, address value) internal returns (bool) { 150 | return _remove(set._inner, bytes32(uint(uint160(value)))); 151 | } 152 | 153 | function contains(AddressSet storage set, address value) internal view returns (bool) { 154 | return _contains(set._inner, bytes32(uint(uint160(value)))); 155 | } 156 | 157 | function length(AddressSet storage set) internal view returns (uint) { 158 | return _length(set._inner); 159 | } 160 | 161 | function at(AddressSet storage set, uint index) internal view returns (address) { 162 | return address(uint160(uint(_at(set._inner, index)))); 163 | } 164 | 165 | struct UintSet { 166 | Set _inner; 167 | } 168 | 169 | function add(UintSet storage set, uint value) internal returns (bool) { 170 | return _add(set._inner, bytes32(value)); 171 | } 172 | 173 | function remove(UintSet storage set, uint value) internal returns (bool) { 174 | return _remove(set._inner, bytes32(value)); 175 | } 176 | 177 | function contains(UintSet storage set, uint value) internal view returns (bool) { 178 | return _contains(set._inner, bytes32(value)); 179 | } 180 | 181 | function length(UintSet storage set) internal view returns (uint) { 182 | return _length(set._inner); 183 | } 184 | 185 | function at(UintSet storage set, uint index) internal view returns (uint) { 186 | return uint(_at(set._inner, index)); 187 | } 188 | } 189 | 190 | library EnumerableMap { 191 | struct MapEntry { 192 | bytes32 _key; 193 | bytes32 _value; 194 | } 195 | 196 | struct Map { 197 | MapEntry[] _entries; 198 | mapping (bytes32 => uint) _indexes; 199 | } 200 | 201 | function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { 202 | // We read and store the key's index to prevent multiple reads from the same storage slot 203 | uint keyIndex = map._indexes[key]; 204 | 205 | if (keyIndex == 0) { // Equivalent to !contains(map, key) 206 | map._entries.push(MapEntry({ _key: key, _value: value })); 207 | // The entry is stored at length-1, but we add 1 to all indexes 208 | // and use 0 as a sentinel value 209 | map._indexes[key] = map._entries.length; 210 | return true; 211 | } else { 212 | map._entries[keyIndex - 1]._value = value; 213 | return false; 214 | } 215 | } 216 | 217 | function _remove(Map storage map, bytes32 key) private returns (bool) { 218 | // We read and store the key's index to prevent multiple reads from the same storage slot 219 | uint keyIndex = map._indexes[key]; 220 | 221 | if (keyIndex != 0) { // Equivalent to contains(map, key) 222 | // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one 223 | // in the array, and then remove the last entry (sometimes called as 'swap and pop'). 224 | // This modifies the order of the array, as noted in {at}. 225 | 226 | uint toDeleteIndex = keyIndex - 1; 227 | uint lastIndex = map._entries.length - 1; 228 | 229 | // When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs 230 | // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. 231 | 232 | MapEntry storage lastEntry = map._entries[lastIndex]; 233 | 234 | // Move the last entry to the index where the entry to delete is 235 | map._entries[toDeleteIndex] = lastEntry; 236 | // Update the index for the moved entry 237 | map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based 238 | 239 | // Delete the slot where the moved entry was stored 240 | map._entries.pop(); 241 | 242 | // Delete the index for the deleted slot 243 | delete map._indexes[key]; 244 | 245 | return true; 246 | } else { 247 | return false; 248 | } 249 | } 250 | 251 | function _contains(Map storage map, bytes32 key) private view returns (bool) { 252 | return map._indexes[key] != 0; 253 | } 254 | 255 | function _length(Map storage map) private view returns (uint) { 256 | return map._entries.length; 257 | } 258 | 259 | function _at(Map storage map, uint index) private view returns (bytes32, bytes32) { 260 | require(map._entries.length > index, "EnumerableMap: index out of bounds"); 261 | 262 | MapEntry storage entry = map._entries[index]; 263 | return (entry._key, entry._value); 264 | } 265 | 266 | function _get(Map storage map, bytes32 key) private view returns (bytes32) { 267 | return _get(map, key, "EnumerableMap: nonexistent key"); 268 | } 269 | 270 | function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { 271 | uint keyIndex = map._indexes[key]; 272 | require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) 273 | return map._entries[keyIndex - 1]._value; // All indexes are 1-based 274 | } 275 | 276 | struct UintToAddressMap { 277 | Map _inner; 278 | } 279 | 280 | function set(UintToAddressMap storage map, uint key, address value) internal returns (bool) { 281 | return _set(map._inner, bytes32(key), bytes32(uint(uint160(value)))); 282 | } 283 | 284 | function remove(UintToAddressMap storage map, uint key) internal returns (bool) { 285 | return _remove(map._inner, bytes32(key)); 286 | } 287 | 288 | function contains(UintToAddressMap storage map, uint key) internal view returns (bool) { 289 | return _contains(map._inner, bytes32(key)); 290 | } 291 | 292 | function length(UintToAddressMap storage map) internal view returns (uint) { 293 | return _length(map._inner); 294 | } 295 | 296 | function at(UintToAddressMap storage map, uint index) internal view returns (uint, address) { 297 | (bytes32 key, bytes32 value) = _at(map._inner, index); 298 | return (uint(key), address(uint160(uint(value)))); 299 | } 300 | 301 | function get(UintToAddressMap storage map, uint key) internal view returns (address) { 302 | return address(uint160(uint(_get(map._inner, bytes32(key))))); 303 | } 304 | 305 | function get(UintToAddressMap storage map, uint key, string memory errorMessage) internal view returns (address) { 306 | return address(uint160(uint(_get(map._inner, bytes32(key), errorMessage)))); 307 | } 308 | } 309 | 310 | contract ERC721 is ERC165, IERC721, IERC721Metadata, IERC721Enumerable { 311 | using EnumerableSet for EnumerableSet.UintSet; 312 | using EnumerableMap for EnumerableMap.UintToAddressMap; 313 | using Strings for uint; 314 | 315 | bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; 316 | mapping (address => EnumerableSet.UintSet) private _holderTokens; 317 | EnumerableMap.UintToAddressMap private _tokenOwners; 318 | mapping (uint => address) private _tokenApprovals; 319 | mapping (address => mapping (address => bool)) private _operatorApprovals; 320 | string private _name; 321 | string private _symbol; 322 | mapping (uint => string) private _tokenURIs; 323 | string private _baseURI; 324 | bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; 325 | bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; 326 | bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; 327 | 328 | constructor (string memory __name, string memory __symbol) { 329 | _name = __name; 330 | _symbol = __symbol; 331 | 332 | // register the supported interfaces to conform to ERC721 via ERC165 333 | _registerInterface(_INTERFACE_ID_ERC721); 334 | _registerInterface(_INTERFACE_ID_ERC721_METADATA); 335 | _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); 336 | } 337 | 338 | function balanceOf(address owner) public view override returns (uint) { 339 | require(owner != address(0), "ERC721: balance query for the zero address"); 340 | 341 | return _holderTokens[owner].length(); 342 | } 343 | 344 | function ownerOf(uint tokenId) public view override returns (address) { 345 | return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); 346 | } 347 | 348 | function name() public view override returns (string memory) { 349 | return _name; 350 | } 351 | 352 | function symbol() public view override returns (string memory) { 353 | return _symbol; 354 | } 355 | 356 | function tokenURI(uint tokenId) public view override returns (string memory) { 357 | require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); 358 | 359 | string memory _tokenURI = _tokenURIs[tokenId]; 360 | 361 | // If there is no base URI, return the token URI. 362 | if (bytes(_baseURI).length == 0) { 363 | return _tokenURI; 364 | } 365 | // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). 366 | if (bytes(_tokenURI).length > 0) { 367 | return string(abi.encodePacked(_baseURI, _tokenURI)); 368 | } 369 | // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. 370 | return string(abi.encodePacked(_baseURI, tokenId.toString())); 371 | } 372 | 373 | function baseURI() public view returns (string memory) { 374 | return _baseURI; 375 | } 376 | 377 | function tokenOfOwnerByIndex(address owner, uint index) public view override returns (uint) { 378 | return _holderTokens[owner].at(index); 379 | } 380 | 381 | function totalSupply() public view override returns (uint) { 382 | // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds 383 | return _tokenOwners.length(); 384 | } 385 | 386 | function tokenByIndex(uint index) public view override returns (uint) { 387 | (uint tokenId, ) = _tokenOwners.at(index); 388 | return tokenId; 389 | } 390 | 391 | function approve(address to, uint tokenId) public virtual override { 392 | address owner = ownerOf(tokenId); 393 | require(to != owner, "ERC721: approval to current owner"); 394 | 395 | require(msg.sender == owner || isApprovedForAll(owner, msg.sender), 396 | "ERC721: approve caller is not owner nor approved for all" 397 | ); 398 | 399 | _approve(to, tokenId); 400 | } 401 | 402 | function getApproved(uint tokenId) public view override returns (address) { 403 | require(_exists(tokenId), "ERC721: approved query for nonexistent token"); 404 | 405 | return _tokenApprovals[tokenId]; 406 | } 407 | 408 | function setApprovalForAll(address operator, bool approved) public virtual override { 409 | require(operator != msg.sender, "ERC721: approve to caller"); 410 | 411 | _operatorApprovals[msg.sender][operator] = approved; 412 | emit ApprovalForAll(msg.sender, operator, approved); 413 | } 414 | 415 | function isApprovedForAll(address owner, address operator) public view override returns (bool) { 416 | return _operatorApprovals[owner][operator]; 417 | } 418 | 419 | function transferFrom(address from, address to, uint tokenId) public virtual override { 420 | //solhint-disable-next-line max-line-length 421 | require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); 422 | 423 | _transfer(from, to, tokenId); 424 | } 425 | 426 | function safeTransferFrom(address from, address to, uint tokenId) public virtual override { 427 | safeTransferFrom(from, to, tokenId, ""); 428 | } 429 | 430 | function safeTransferFrom(address from, address to, uint tokenId, bytes memory _data) public virtual override { 431 | require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); 432 | _safeTransfer(from, to, tokenId, _data); 433 | } 434 | 435 | function _safeTransfer(address from, address to, uint tokenId, bytes memory _data) internal virtual { 436 | _transfer(from, to, tokenId); 437 | require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); 438 | } 439 | 440 | function _exists(uint tokenId) internal view returns (bool) { 441 | return _tokenOwners.contains(tokenId); 442 | } 443 | 444 | function _isApprovedOrOwner(address spender, uint tokenId) internal view returns (bool) { 445 | require(_exists(tokenId), "ERC721: operator query for nonexistent token"); 446 | address owner = ownerOf(tokenId); 447 | return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); 448 | } 449 | 450 | function _safeMint(address to, uint tokenId) internal virtual { 451 | _safeMint(to, tokenId, ""); 452 | } 453 | 454 | function _safeMint(address to, uint tokenId, bytes memory _data) internal virtual { 455 | _mint(to, tokenId); 456 | require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); 457 | } 458 | 459 | function _mint(address to, uint tokenId) internal virtual { 460 | require(to != address(0), "ERC721: mint to the zero address"); 461 | require(!_exists(tokenId), "ERC721: token already minted"); 462 | 463 | _beforeTokenTransfer(address(0), to, tokenId); 464 | 465 | _holderTokens[to].add(tokenId); 466 | 467 | _tokenOwners.set(tokenId, to); 468 | 469 | emit Transfer(address(0), to, tokenId); 470 | } 471 | 472 | function _burn(uint tokenId) internal virtual { 473 | address owner = ownerOf(tokenId); 474 | 475 | _beforeTokenTransfer(owner, address(0), tokenId); 476 | 477 | // Clear approvals 478 | _approve(address(0), tokenId); 479 | 480 | // Clear metadata (if any) 481 | if (bytes(_tokenURIs[tokenId]).length != 0) { 482 | delete _tokenURIs[tokenId]; 483 | } 484 | 485 | _holderTokens[owner].remove(tokenId); 486 | 487 | _tokenOwners.remove(tokenId); 488 | 489 | emit Transfer(owner, address(0), tokenId); 490 | } 491 | 492 | function _transfer(address from, address to, uint tokenId) internal virtual { 493 | require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); 494 | require(to != address(0), "ERC721: transfer to the zero address"); 495 | 496 | _beforeTokenTransfer(from, to, tokenId); 497 | 498 | // Clear approvals from the previous owner 499 | _approve(address(0), tokenId); 500 | 501 | _holderTokens[from].remove(tokenId); 502 | _holderTokens[to].add(tokenId); 503 | 504 | _tokenOwners.set(tokenId, to); 505 | 506 | emit Transfer(from, to, tokenId); 507 | } 508 | 509 | function _setTokenURI(uint tokenId, string memory _tokenURI) internal virtual { 510 | require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); 511 | _tokenURIs[tokenId] = _tokenURI; 512 | } 513 | 514 | function _setBaseURI(string memory baseURI_) internal virtual { 515 | _baseURI = baseURI_; 516 | } 517 | 518 | function _checkOnERC721Received(address from, address to, uint tokenId, bytes memory _data) 519 | private returns (bool) 520 | { 521 | (bool success, bytes memory returndata) = to.call{value:0}(abi.encodeWithSelector( 522 | IERC721Receiver(to).onERC721Received.selector, 523 | msg.sender, 524 | from, 525 | tokenId, 526 | _data 527 | )); 528 | require(success, "ERC721: transfer to non ERC721Receiver implementer"); 529 | bytes4 retval = abi.decode(returndata, (bytes4)); 530 | return (retval == _ERC721_RECEIVED); 531 | } 532 | 533 | function _approve(address to, uint tokenId) private { 534 | _tokenApprovals[tokenId] = to; 535 | emit Approval(ownerOf(tokenId), to, tokenId); 536 | } 537 | 538 | function _beforeTokenTransfer(address from, address to, uint tokenId) internal virtual {} 539 | } 540 | 541 | interface erc20 { 542 | function transfer(address recipient, uint amount) external returns (bool); 543 | function balanceOf(address) external view returns (uint); 544 | function transferFrom(address sender, address recipient, uint amount) external returns (bool); 545 | } 546 | 547 | interface v3oracle { 548 | function assetToAsset(address from, uint amount, address to, uint twap_duration) external view returns (uint); 549 | } 550 | 551 | contract OptionsLM is ERC721 { 552 | address immutable public reward; 553 | address immutable public stake; 554 | address immutable public buyWith; 555 | address immutable public treasury; 556 | 557 | v3oracle constant oracle = v3oracle(0x0F1f5A87f99f0918e6C81F16E59F3518698221Ff); 558 | 559 | uint constant DURATION = 7 days; 560 | uint constant PRECISION = 10 ** 18; 561 | uint constant TWAP_PERIOD = 3600; 562 | uint constant OPTION_EXPIRY = 30 days; 563 | 564 | uint rewardRate; 565 | uint periodFinish; 566 | uint lastUpdateTime; 567 | uint rewardPerTokenStored; 568 | 569 | mapping(address => uint256) public userRewardPerTokenPaid; 570 | mapping(address => uint256) public rewards; 571 | 572 | struct option { 573 | uint amount; 574 | uint strike; 575 | uint expiry; 576 | bool exercised; 577 | } 578 | 579 | option[] public options; 580 | uint public nextIndex; 581 | 582 | uint _totalSupply; 583 | mapping(address => uint) public _balanceOf; 584 | 585 | event Deposit(address indexed from, uint amount); 586 | event Withdraw(address indexed to, uint amount); 587 | event Created(address indexed owner, uint amount, uint strike, uint expiry, uint id); 588 | event Redeem(address indexed from, address indexed owner, uint amount, uint strike, uint id); 589 | 590 | constructor( 591 | address _reward, 592 | address _stake, 593 | address _buyWith, 594 | address _treasury, 595 | string memory _name, 596 | string memory _symbol 597 | ) ERC721(_name, _symbol) { 598 | reward = _reward; 599 | stake = _stake; 600 | buyWith = _buyWith; 601 | treasury = _treasury; 602 | } 603 | 604 | function lastTimeRewardApplicable() public view returns (uint) { 605 | return block.timestamp < periodFinish ? block.timestamp : periodFinish; 606 | } 607 | 608 | function rewardPerToken() public view returns (uint) { 609 | if (_totalSupply == 0) { 610 | return rewardPerTokenStored; 611 | } 612 | return rewardPerTokenStored + ((lastTimeRewardApplicable() - lastUpdateTime) * rewardRate * PRECISION / _totalSupply); 613 | } 614 | 615 | function earned(address account) public view returns (uint) { 616 | return (_balanceOf[account] * (rewardPerToken() - userRewardPerTokenPaid[account]) / PRECISION) + rewards[account]; 617 | } 618 | 619 | function getRewardForDuration() external view returns (uint) { 620 | return rewardRate * DURATION; 621 | } 622 | 623 | function deposit(address recipient) external { 624 | _deposit(erc20(stake).balanceOf(msg.sender), recipient); 625 | } 626 | 627 | function deposit() external { 628 | _deposit(erc20(stake).balanceOf(msg.sender), msg.sender); 629 | } 630 | 631 | function deposit(uint amount) external { 632 | _deposit(amount, msg.sender); 633 | } 634 | 635 | function deposit(uint amount, address recipient) external { 636 | _deposit(amount, recipient); 637 | } 638 | 639 | function _deposit(uint amount, address to) internal update(to) { 640 | _totalSupply += amount; 641 | _balanceOf[to] += amount; 642 | _safeTransferFrom(stake, msg.sender, address(this), amount); 643 | emit Deposit(msg.sender, amount); 644 | } 645 | 646 | function withdraw() external { 647 | _withdraw(_balanceOf[msg.sender], msg.sender); 648 | } 649 | 650 | function withdraw(address recipient) external { 651 | _withdraw(_balanceOf[msg.sender], recipient); 652 | } 653 | 654 | function withdraw(uint amount, address recipient) external { 655 | _withdraw(amount, recipient); 656 | } 657 | 658 | function withdraw(uint amount) external { 659 | _withdraw(amount, msg.sender); 660 | } 661 | 662 | function _withdraw(uint amount, address to) internal update(msg.sender) { 663 | _totalSupply -= amount; 664 | _balanceOf[msg.sender] -= amount; 665 | _safeTransfer(stake, to, amount); 666 | emit Withdraw(msg.sender, amount); 667 | } 668 | 669 | function _claim(uint amount) internal { 670 | uint _strike = oracle.assetToAsset(reward, amount, buyWith, 3600); 671 | uint _expiry = block.timestamp + OPTION_EXPIRY; 672 | options.push(option(amount, _strike, _expiry, false)); 673 | _safeMint(msg.sender, nextIndex); 674 | emit Created(msg.sender, amount, _strike, _expiry, nextIndex); 675 | nextIndex++; 676 | } 677 | 678 | function redeem(uint id) external { 679 | require(_isApprovedOrOwner(msg.sender, id)); 680 | option storage _opt = options[id]; 681 | require(_opt.expiry >= block.timestamp && !_opt.exercised); 682 | _opt.exercised = true; 683 | _safeTransferFrom(buyWith, msg.sender, treasury, _opt.strike); 684 | _safeTransfer(reward, msg.sender, _opt.amount); 685 | emit Redeem(msg.sender, msg.sender, _opt.amount, _opt.strike, id); 686 | } 687 | 688 | function getReward() public update(msg.sender) { 689 | uint _reward = rewards[msg.sender]; 690 | if (_reward > 0) { 691 | rewards[msg.sender] = 0; 692 | _claim(_reward); 693 | } 694 | } 695 | 696 | function exit() external { 697 | _withdraw(_balanceOf[msg.sender], msg.sender); 698 | getReward(); 699 | } 700 | 701 | function notify(uint amount) external update(address(0)) { 702 | _safeTransferFrom(reward, msg.sender, address(this), amount); 703 | if (block.timestamp >= periodFinish) { 704 | rewardRate = amount / DURATION; 705 | } else { 706 | uint _remaining = periodFinish - block.timestamp; 707 | uint _leftover = _remaining * rewardRate; 708 | rewardRate = (amount + _leftover) / DURATION; 709 | } 710 | 711 | lastUpdateTime = block.timestamp; 712 | periodFinish = block.timestamp + DURATION; 713 | } 714 | 715 | modifier update(address account) { 716 | rewardPerTokenStored = rewardPerToken(); 717 | lastUpdateTime = lastTimeRewardApplicable(); 718 | if (account != address(0)) { 719 | rewards[account] = earned(account); 720 | userRewardPerTokenPaid[account] = rewardPerTokenStored; 721 | } 722 | _; 723 | } 724 | 725 | function _safeTransfer(address token, address to, uint256 value) internal { 726 | (bool success, bytes memory data) = 727 | token.call(abi.encodeWithSelector(erc20.transfer.selector, to, value)); 728 | require(success && (data.length == 0 || abi.decode(data, (bool)))); 729 | } 730 | 731 | function _safeTransferFrom(address token, address from, address to, uint256 value) internal { 732 | (bool success, bytes memory data) = 733 | token.call(abi.encodeWithSelector(erc20.transferFrom.selector, from, to, value)); 734 | require(success && (data.length == 0 || abi.decode(data, (bool)))); 735 | } 736 | } 737 | -------------------------------------------------------------------------------- /contracts/rKP3R.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | pragma solidity ^0.8.7; 3 | 4 | interface IERC165 { 5 | function supportsInterface(bytes4 interfaceId) external view returns (bool); 6 | } 7 | 8 | 9 | interface IERC721 is IERC165 { 10 | event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); 11 | event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); 12 | event ApprovalForAll(address indexed owner, address indexed operator, bool approved); 13 | function balanceOf(address owner) external view returns (uint256 balance); 14 | function ownerOf(uint256 tokenId) external view returns (address owner); 15 | function safeTransferFrom( 16 | address from, 17 | address to, 18 | uint256 tokenId 19 | ) external; 20 | function transferFrom( 21 | address from, 22 | address to, 23 | uint256 tokenId 24 | ) external; 25 | function approve(address to, uint256 tokenId) external; 26 | function getApproved(uint256 tokenId) external view returns (address operator); 27 | function setApprovalForAll(address operator, bool _approved) external; 28 | function isApprovedForAll(address owner, address operator) external view returns (bool); 29 | function safeTransferFrom( 30 | address from, 31 | address to, 32 | uint256 tokenId, 33 | bytes calldata data 34 | ) external; 35 | } 36 | 37 | library Strings { 38 | function toString(uint256 value) internal pure returns (string memory) { 39 | if (value == 0) { 40 | return "0"; 41 | } 42 | uint256 temp = value; 43 | uint256 digits; 44 | while (temp != 0) { 45 | digits++; 46 | temp /= 10; 47 | } 48 | bytes memory buffer = new bytes(digits); 49 | while (value != 0) { 50 | digits -= 1; 51 | buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); 52 | value /= 10; 53 | } 54 | return string(buffer); 55 | } 56 | } 57 | 58 | interface IERC721Receiver { 59 | function onERC721Received( 60 | address operator, 61 | address from, 62 | uint256 tokenId, 63 | bytes calldata data 64 | ) external returns (bytes4); 65 | } 66 | 67 | abstract contract ERC165 is IERC165 { 68 | function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { 69 | return interfaceId == type(IERC165).interfaceId; 70 | } 71 | } 72 | 73 | interface IERC721Metadata is IERC721 { 74 | function name() external view returns (string memory); 75 | function symbol() external view returns (string memory); 76 | function tokenURI(uint256 tokenId) external view returns (string memory); 77 | } 78 | 79 | contract ERC721 is ERC165, IERC721 { 80 | using Strings for uint256; 81 | 82 | mapping(uint256 => address) private _owners; 83 | mapping(address => uint256) private _balances; 84 | mapping(uint256 => address) private _tokenApprovals; 85 | mapping(address => mapping(address => bool)) private _operatorApprovals; 86 | 87 | function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { 88 | return 89 | interfaceId == type(IERC721).interfaceId || 90 | interfaceId == type(IERC721Metadata).interfaceId || 91 | super.supportsInterface(interfaceId); 92 | } 93 | 94 | function balanceOf(address owner) public view virtual override returns (uint256) { 95 | require(owner != address(0), "ERC721: balance query for the zero address"); 96 | return _balances[owner]; 97 | } 98 | 99 | function ownerOf(uint256 tokenId) public view virtual override returns (address) { 100 | address owner = _owners[tokenId]; 101 | require(owner != address(0), "ERC721: owner query for nonexistent token"); 102 | return owner; 103 | } 104 | 105 | function _baseURI() internal view virtual returns (string memory) { 106 | return ""; 107 | } 108 | 109 | function approve(address to, uint256 tokenId) public virtual override { 110 | address owner = ERC721.ownerOf(tokenId); 111 | require(to != owner, "ERC721: approval to current owner"); 112 | 113 | require( 114 | msg.sender == owner || isApprovedForAll(owner, msg.sender), 115 | "ERC721: approve caller is not owner nor approved for all" 116 | ); 117 | 118 | _approve(to, tokenId); 119 | } 120 | 121 | function getApproved(uint256 tokenId) public view virtual override returns (address) { 122 | require(_exists(tokenId), "ERC721: approved query for nonexistent token"); 123 | 124 | return _tokenApprovals[tokenId]; 125 | } 126 | 127 | function setApprovalForAll(address operator, bool approved) public virtual override { 128 | require(operator != msg.sender, "ERC721: approve to caller"); 129 | 130 | _operatorApprovals[msg.sender][operator] = approved; 131 | emit ApprovalForAll(msg.sender, operator, approved); 132 | } 133 | 134 | function _isContract(address account) internal view returns (bool) { 135 | uint256 size; 136 | assembly { 137 | size := extcodesize(account) 138 | } 139 | return size > 0; 140 | } 141 | 142 | function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { 143 | return _operatorApprovals[owner][operator]; 144 | } 145 | 146 | function transferFrom( 147 | address from, 148 | address to, 149 | uint256 tokenId 150 | ) public virtual override { 151 | //solhint-disable-next-line max-line-length 152 | require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); 153 | 154 | _transfer(from, to, tokenId); 155 | } 156 | 157 | function safeTransferFrom( 158 | address from, 159 | address to, 160 | uint256 tokenId 161 | ) public virtual override { 162 | safeTransferFrom(from, to, tokenId, ""); 163 | } 164 | 165 | /** 166 | * @dev See {IERC721-safeTransferFrom}. 167 | */ 168 | function safeTransferFrom( 169 | address from, 170 | address to, 171 | uint256 tokenId, 172 | bytes memory _data 173 | ) public virtual override { 174 | require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); 175 | _safeTransfer(from, to, tokenId, _data); 176 | } 177 | 178 | /** 179 | * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients 180 | * are aware of the ERC721 protocol to prevent tokens from being forever locked. 181 | * 182 | * `_data` is additional data, it has no specified format and it is sent in call to `to`. 183 | * 184 | * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. 185 | * implement alternative mechanisms to perform token transfer, such as signature-based. 186 | * 187 | * Requirements: 188 | * 189 | * - `from` cannot be the zero address. 190 | * - `to` cannot be the zero address. 191 | * - `tokenId` token must exist and be owned by `from`. 192 | * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. 193 | * 194 | * Emits a {Transfer} event. 195 | */ 196 | function _safeTransfer( 197 | address from, 198 | address to, 199 | uint256 tokenId, 200 | bytes memory _data 201 | ) internal virtual { 202 | _transfer(from, to, tokenId); 203 | require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); 204 | } 205 | 206 | /** 207 | * @dev Returns whether `tokenId` exists. 208 | * 209 | * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. 210 | * 211 | * Tokens start existing when they are minted (`_mint`), 212 | * and stop existing when they are burned (`_burn`). 213 | */ 214 | function _exists(uint256 tokenId) internal view virtual returns (bool) { 215 | return _owners[tokenId] != address(0); 216 | } 217 | 218 | /** 219 | * @dev Returns whether `spender` is allowed to manage `tokenId`. 220 | * 221 | * Requirements: 222 | * 223 | * - `tokenId` must exist. 224 | */ 225 | function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { 226 | require(_exists(tokenId), "ERC721: operator query for nonexistent token"); 227 | address owner = ERC721.ownerOf(tokenId); 228 | return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); 229 | } 230 | 231 | /** 232 | * @dev Safely mints `tokenId` and transfers it to `to`. 233 | * 234 | * Requirements: 235 | * 236 | * - `tokenId` must not exist. 237 | * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. 238 | * 239 | * Emits a {Transfer} event. 240 | */ 241 | function _safeMint(address to, uint256 tokenId) internal virtual { 242 | _safeMint(to, tokenId, ""); 243 | } 244 | 245 | /** 246 | * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is 247 | * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. 248 | */ 249 | function _safeMint( 250 | address to, 251 | uint256 tokenId, 252 | bytes memory _data 253 | ) internal virtual { 254 | _mint(to, tokenId); 255 | require( 256 | _checkOnERC721Received(address(0), to, tokenId, _data), 257 | "ERC721: transfer to non ERC721Receiver implementer" 258 | ); 259 | } 260 | 261 | /** 262 | * @dev Mints `tokenId` and transfers it to `to`. 263 | * 264 | * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible 265 | * 266 | * Requirements: 267 | * 268 | * - `tokenId` must not exist. 269 | * - `to` cannot be the zero address. 270 | * 271 | * Emits a {Transfer} event. 272 | */ 273 | function _mint(address to, uint256 tokenId) internal virtual { 274 | require(to != address(0), "ERC721: mint to the zero address"); 275 | require(!_exists(tokenId), "ERC721: token already minted"); 276 | 277 | _beforeTokenTransfer(address(0), to, tokenId); 278 | 279 | _balances[to] += 1; 280 | _owners[tokenId] = to; 281 | 282 | emit Transfer(address(0), to, tokenId); 283 | } 284 | 285 | /** 286 | * @dev Destroys `tokenId`. 287 | * The approval is cleared when the token is burned. 288 | * 289 | * Requirements: 290 | * 291 | * - `tokenId` must exist. 292 | * 293 | * Emits a {Transfer} event. 294 | */ 295 | function _burn(uint256 tokenId) internal virtual { 296 | address owner = ERC721.ownerOf(tokenId); 297 | 298 | _beforeTokenTransfer(owner, address(0), tokenId); 299 | 300 | // Clear approvals 301 | _approve(address(0), tokenId); 302 | 303 | _balances[owner] -= 1; 304 | delete _owners[tokenId]; 305 | 306 | emit Transfer(owner, address(0), tokenId); 307 | } 308 | 309 | /** 310 | * @dev Transfers `tokenId` from `from` to `to`. 311 | * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. 312 | * 313 | * Requirements: 314 | * 315 | * - `to` cannot be the zero address. 316 | * - `tokenId` token must be owned by `from`. 317 | * 318 | * Emits a {Transfer} event. 319 | */ 320 | function _transfer( 321 | address from, 322 | address to, 323 | uint256 tokenId 324 | ) internal virtual { 325 | require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); 326 | require(to != address(0), "ERC721: transfer to the zero address"); 327 | 328 | _beforeTokenTransfer(from, to, tokenId); 329 | 330 | // Clear approvals from the previous owner 331 | _approve(address(0), tokenId); 332 | 333 | _balances[from] -= 1; 334 | _balances[to] += 1; 335 | _owners[tokenId] = to; 336 | 337 | emit Transfer(from, to, tokenId); 338 | } 339 | 340 | /** 341 | * @dev Approve `to` to operate on `tokenId` 342 | * 343 | * Emits a {Approval} event. 344 | */ 345 | function _approve(address to, uint256 tokenId) internal virtual { 346 | _tokenApprovals[tokenId] = to; 347 | emit Approval(ERC721.ownerOf(tokenId), to, tokenId); 348 | } 349 | 350 | /** 351 | * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. 352 | * The call is not executed if the target address is not a contract. 353 | * 354 | * @param from address representing the previous owner of the given token ID 355 | * @param to target address that will receive the tokens 356 | * @param tokenId uint256 ID of the token to be transferred 357 | * @param _data bytes optional data to send along with the call 358 | * @return bool whether the call correctly returned the expected magic value 359 | */ 360 | function _checkOnERC721Received( 361 | address from, 362 | address to, 363 | uint256 tokenId, 364 | bytes memory _data 365 | ) private returns (bool) { 366 | if (_isContract(to)) { 367 | try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data) returns (bytes4 retval) { 368 | return retval == IERC721Receiver(to).onERC721Received.selector; 369 | } catch (bytes memory reason) { 370 | if (reason.length == 0) { 371 | revert("ERC721: transfer to non ERC721Receiver implementer"); 372 | } else { 373 | assembly { 374 | revert(add(32, reason), mload(reason)) 375 | } 376 | } 377 | } 378 | } else { 379 | return true; 380 | } 381 | } 382 | 383 | /** 384 | * @dev Hook that is called before any token transfer. This includes minting 385 | * and burning. 386 | * 387 | * Calling conditions: 388 | * 389 | * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be 390 | * transferred to `to`. 391 | * - When `from` is zero, `tokenId` will be minted for `to`. 392 | * - When `to` is zero, ``from``'s `tokenId` will be burned. 393 | * - `from` and `to` are never both zero. 394 | * 395 | * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. 396 | */ 397 | function _beforeTokenTransfer( 398 | address from, 399 | address to, 400 | uint256 tokenId 401 | ) internal virtual {} 402 | } 403 | 404 | 405 | 406 | 407 | 408 | 409 | 410 | /** 411 | * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension 412 | * @dev See https://eips.ethereum.org/EIPS/eip-721 413 | */ 414 | interface IERC721Enumerable is IERC721 { 415 | /** 416 | * @dev Returns the total amount of tokens stored by the contract. 417 | */ 418 | function totalSupply() external view returns (uint256); 419 | 420 | /** 421 | * @dev Returns a token ID owned by `owner` at a given `index` of its token list. 422 | * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. 423 | */ 424 | function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); 425 | 426 | /** 427 | * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. 428 | * Use along with {totalSupply} to enumerate all tokens. 429 | */ 430 | function tokenByIndex(uint256 index) external view returns (uint256); 431 | } 432 | 433 | 434 | /** 435 | * @dev This implements an optional extension of {ERC721} defined in the EIP that adds 436 | * enumerability of all the token ids in the contract as well as all token ids owned by each 437 | * account. 438 | */ 439 | abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { 440 | // Mapping from owner to list of owned token IDs 441 | mapping(address => mapping(uint256 => uint256)) private _ownedTokens; 442 | 443 | // Mapping from token ID to index of the owner tokens list 444 | mapping(uint256 => uint256) private _ownedTokensIndex; 445 | 446 | // Array with all token ids, used for enumeration 447 | uint256[] private _allTokens; 448 | 449 | // Mapping from token id to position in the allTokens array 450 | mapping(uint256 => uint256) private _allTokensIndex; 451 | 452 | /** 453 | * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. 454 | */ 455 | function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { 456 | require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); 457 | return _ownedTokens[owner][index]; 458 | } 459 | 460 | /** 461 | * @dev See {IERC721Enumerable-totalSupply}. 462 | */ 463 | function totalSupply() public view virtual override returns (uint256) { 464 | return _allTokens.length; 465 | } 466 | 467 | /** 468 | * @dev See {IERC721Enumerable-tokenByIndex}. 469 | */ 470 | function tokenByIndex(uint256 index) public view virtual override returns (uint256) { 471 | require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); 472 | return _allTokens[index]; 473 | } 474 | 475 | /** 476 | * @dev Hook that is called before any token transfer. This includes minting 477 | * and burning. 478 | * 479 | * Calling conditions: 480 | * 481 | * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be 482 | * transferred to `to`. 483 | * - When `from` is zero, `tokenId` will be minted for `to`. 484 | * - When `to` is zero, ``from``'s `tokenId` will be burned. 485 | * - `from` cannot be the zero address. 486 | * - `to` cannot be the zero address. 487 | * 488 | * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. 489 | */ 490 | function _beforeTokenTransfer( 491 | address from, 492 | address to, 493 | uint256 tokenId 494 | ) internal virtual override { 495 | super._beforeTokenTransfer(from, to, tokenId); 496 | 497 | if (from == address(0)) { 498 | _addTokenToAllTokensEnumeration(tokenId); 499 | } else if (from != to) { 500 | _removeTokenFromOwnerEnumeration(from, tokenId); 501 | } 502 | if (to == address(0)) { 503 | _removeTokenFromAllTokensEnumeration(tokenId); 504 | } else if (to != from) { 505 | _addTokenToOwnerEnumeration(to, tokenId); 506 | } 507 | } 508 | 509 | /** 510 | * @dev Private function to add a token to this extension's ownership-tracking data structures. 511 | * @param to address representing the new owner of the given token ID 512 | * @param tokenId uint256 ID of the token to be added to the tokens list of the given address 513 | */ 514 | function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { 515 | uint256 length = ERC721.balanceOf(to); 516 | _ownedTokens[to][length] = tokenId; 517 | _ownedTokensIndex[tokenId] = length; 518 | } 519 | 520 | /** 521 | * @dev Private function to add a token to this extension's token tracking data structures. 522 | * @param tokenId uint256 ID of the token to be added to the tokens list 523 | */ 524 | function _addTokenToAllTokensEnumeration(uint256 tokenId) private { 525 | _allTokensIndex[tokenId] = _allTokens.length; 526 | _allTokens.push(tokenId); 527 | } 528 | 529 | /** 530 | * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that 531 | * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for 532 | * gas optimizations e.g. when performing a transfer operation (avoiding double writes). 533 | * This has O(1) time complexity, but alters the order of the _ownedTokens array. 534 | * @param from address representing the previous owner of the given token ID 535 | * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address 536 | */ 537 | function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { 538 | // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and 539 | // then delete the last slot (swap and pop). 540 | 541 | uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; 542 | uint256 tokenIndex = _ownedTokensIndex[tokenId]; 543 | 544 | // When the token to delete is the last token, the swap operation is unnecessary 545 | if (tokenIndex != lastTokenIndex) { 546 | uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; 547 | 548 | _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token 549 | _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index 550 | } 551 | 552 | // This also deletes the contents at the last position of the array 553 | delete _ownedTokensIndex[tokenId]; 554 | delete _ownedTokens[from][lastTokenIndex]; 555 | } 556 | 557 | /** 558 | * @dev Private function to remove a token from this extension's token tracking data structures. 559 | * This has O(1) time complexity, but alters the order of the _allTokens array. 560 | * @param tokenId uint256 ID of the token to be removed from the tokens list 561 | */ 562 | function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { 563 | // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and 564 | // then delete the last slot (swap and pop). 565 | 566 | uint256 lastTokenIndex = _allTokens.length - 1; 567 | uint256 tokenIndex = _allTokensIndex[tokenId]; 568 | 569 | // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so 570 | // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding 571 | // an 'if' statement (like in _removeTokenFromOwnerEnumeration) 572 | uint256 lastTokenId = _allTokens[lastTokenIndex]; 573 | 574 | _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token 575 | _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index 576 | 577 | // This also deletes the contents at the last position of the array 578 | delete _allTokensIndex[tokenId]; 579 | _allTokens.pop(); 580 | } 581 | } 582 | 583 | library FullMath { 584 | function mulDiv( 585 | uint256 a, 586 | uint256 b, 587 | uint256 denominator 588 | ) internal pure returns (uint256 result) { 589 | uint256 prod0; // Least significant 256 bits of the product 590 | uint256 prod1; // Most significant 256 bits of the product 591 | assembly { 592 | let mm := mulmod(a, b, not(0)) 593 | prod0 := mul(a, b) 594 | prod1 := sub(sub(mm, prod0), lt(mm, prod0)) 595 | } 596 | 597 | if (prod1 == 0) { 598 | require(denominator > 0); 599 | assembly { 600 | result := div(prod0, denominator) 601 | } 602 | return result; 603 | } 604 | 605 | require(denominator > prod1); 606 | 607 | uint256 remainder; 608 | assembly { 609 | remainder := mulmod(a, b, denominator) 610 | } 611 | assembly { 612 | prod1 := sub(prod1, gt(remainder, prod0)) 613 | prod0 := sub(prod0, remainder) 614 | } 615 | int256 _denominator = int256(denominator); 616 | uint256 twos = uint256(-_denominator & _denominator); 617 | assembly { 618 | denominator := div(denominator, twos) 619 | } 620 | 621 | assembly { 622 | prod0 := div(prod0, twos) 623 | } 624 | 625 | assembly { 626 | twos := add(div(sub(0, twos), twos), 1) 627 | } 628 | prod0 |= prod1 * twos; 629 | 630 | uint256 inv = (3 * denominator) ^ 2; 631 | 632 | inv *= 2 - denominator * inv; // inverse mod 2**8 633 | inv *= 2 - denominator * inv; // inverse mod 2**16 634 | inv *= 2 - denominator * inv; // inverse mod 2**32 635 | inv *= 2 - denominator * inv; // inverse mod 2**64 636 | inv *= 2 - denominator * inv; // inverse mod 2**128 637 | inv *= 2 - denominator * inv; // inverse mod 2**256 638 | 639 | result = prod0 * inv; 640 | return result; 641 | } 642 | } 643 | 644 | library TickMath { 645 | int24 internal constant MIN_TICK = -887272; 646 | int24 internal constant MAX_TICK = -MIN_TICK; 647 | 648 | function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { 649 | uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); 650 | require(absTick <= uint256(int256(MAX_TICK)), 'T'); 651 | 652 | uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; 653 | if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; 654 | if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; 655 | if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; 656 | if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; 657 | if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; 658 | if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; 659 | if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; 660 | if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; 661 | if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; 662 | if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; 663 | if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; 664 | if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; 665 | if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; 666 | if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; 667 | if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; 668 | if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; 669 | if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; 670 | if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; 671 | if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; 672 | 673 | if (tick > 0) ratio = type(uint256).max / ratio; 674 | 675 | sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); 676 | } 677 | } 678 | 679 | interface IUniswapV3Pool { 680 | function observe(uint32[] calldata secondsAgos) 681 | external 682 | view 683 | returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); 684 | } 685 | 686 | /// @title Oracle library 687 | /// @notice Provides functions to integrate with V3 pool oracle 688 | library OracleLibrary { 689 | /// @notice Fetches time-weighted average tick using Uniswap V3 oracle 690 | /// @param pool Address of Uniswap V3 pool that we want to observe 691 | /// @param period Number of seconds in the past to start calculating time-weighted average 692 | /// @return timeWeightedAverageTick The time-weighted average tick from (block.timestamp - period) to block.timestamp 693 | function consult(address pool, uint32 period) internal view returns (int24 timeWeightedAverageTick) { 694 | require(period != 0, 'BP'); 695 | 696 | uint32[] memory secondAgos = new uint32[](2); 697 | secondAgos[0] = period; 698 | secondAgos[1] = 0; 699 | 700 | (int56[] memory tickCumulatives, ) = IUniswapV3Pool(pool).observe(secondAgos); 701 | int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0]; 702 | 703 | timeWeightedAverageTick = int24(tickCumulativesDelta / int(uint(period))); 704 | 705 | // Always round to negative infinity 706 | if (tickCumulativesDelta < 0 && (tickCumulativesDelta % int(uint(period)) != 0)) timeWeightedAverageTick--; 707 | } 708 | 709 | /// @notice Given a tick and a token amount, calculates the amount of token received in exchange 710 | /// @param tick Tick value used to calculate the quote 711 | /// @param baseAmount Amount of token to be converted 712 | /// @param baseToken Address of an ERC20 token contract used as the baseAmount denomination 713 | /// @param quoteToken Address of an ERC20 token contract used as the quoteAmount denomination 714 | /// @return quoteAmount Amount of quoteToken received for baseAmount of baseToken 715 | function getQuoteAtTick( 716 | int24 tick, 717 | uint128 baseAmount, 718 | address baseToken, 719 | address quoteToken 720 | ) internal pure returns (uint256 quoteAmount) { 721 | uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick); 722 | 723 | // Calculate quoteAmount with better precision if it doesn't overflow when multiplied by itself 724 | if (sqrtRatioX96 <= type(uint128).max) { 725 | uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96; 726 | quoteAmount = baseToken < quoteToken 727 | ? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192) 728 | : FullMath.mulDiv(1 << 192, baseAmount, ratioX192); 729 | } else { 730 | uint256 ratioX128 = FullMath.mulDiv(sqrtRatioX96, sqrtRatioX96, 1 << 64); 731 | quoteAmount = baseToken < quoteToken 732 | ? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128) 733 | : FullMath.mulDiv(1 << 128, baseAmount, ratioX128); 734 | } 735 | } 736 | } 737 | 738 | library PoolAddress { 739 | bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; 740 | 741 | struct PoolKey { 742 | address token0; 743 | address token1; 744 | uint24 fee; 745 | }function getPoolKey( 746 | address tokenA, 747 | address tokenB, 748 | uint24 fee 749 | ) internal pure returns (PoolKey memory) { 750 | if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); 751 | return PoolKey({token0: tokenA, token1: tokenB, fee: fee}); 752 | } 753 | 754 | function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) { 755 | require(key.token0 < key.token1); 756 | pool = address( 757 | uint160(uint256( 758 | keccak256( 759 | abi.encodePacked( 760 | hex'ff', 761 | factory, 762 | keccak256(abi.encode(key.token0, key.token1, key.fee)), 763 | POOL_INIT_CODE_HASH 764 | ) 765 | ) 766 | ) 767 | )); 768 | } 769 | } 770 | 771 | library SafeUint128 { 772 | function toUint128(uint256 y) internal pure returns (uint128 z) { 773 | require((z = uint128(y)) == y); 774 | } 775 | } 776 | 777 | interface erc20 { 778 | function transfer(address recipient, uint amount) external returns (bool); 779 | function balanceOf(address) external view returns (uint); 780 | function transferFrom(address sender, address recipient, uint amount) external returns (bool); 781 | } 782 | 783 | contract Keep3rOptions is ERC721Enumerable { 784 | string public constant name = "Keep3r Options"; 785 | string public constant symbol = "oKP3R"; 786 | address immutable rKP3R; 787 | 788 | constructor() { 789 | rKP3R = msg.sender; 790 | } 791 | 792 | function mint(address _user, uint _id) external returns (bool) { 793 | require(msg.sender == rKP3R); 794 | _safeMint(_user, _id); 795 | return true; 796 | } 797 | 798 | function burn(uint _id) external returns (bool) { 799 | require(msg.sender == rKP3R); 800 | _burn(_id); 801 | return true; 802 | } 803 | 804 | function isApprovedOrOwner(address _addr, uint _id) external view returns (bool) { 805 | return _isApprovedOrOwner(_addr, _id); 806 | } 807 | } 808 | 809 | contract RedeemableKeep3r { 810 | string public constant name = "Redeemable Keep3r"; 811 | string public constant symbol = "rKP3R"; 812 | uint8 public constant decimals = 18; 813 | 814 | address public gov; 815 | address public nextGov; 816 | uint public delayGov; 817 | 818 | uint public discount = 50; 819 | uint public nextDiscount; 820 | uint public delayDiscount; 821 | 822 | address public treasury; 823 | address public nextTreasury; 824 | uint public delayTreasury; 825 | 826 | struct option { 827 | uint amount; 828 | uint strike; 829 | uint expiry; 830 | bool exercised; 831 | } 832 | 833 | option[] public options; 834 | uint public nextIndex; 835 | 836 | address constant KP3R = address(0x1cEB5cB57C4D4E2b2433641b95Dd330A33185A44); 837 | address constant USDC = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); 838 | address constant UNIv3 = 0x1F98431c8aD98523631AE4a59f267346ea31F984; 839 | address constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; 840 | 841 | uint32 constant TWAP_PERIOD = 86400; 842 | uint32 constant TWAP_NOW = 60; 843 | uint32 constant OPTION_EXPIRY = 1 days; 844 | uint32 constant DELAY = 1 days; 845 | uint32 constant BASE = 100; 846 | Keep3rOptions immutable public oKP3R; 847 | 848 | event Created(address indexed owner, uint amount, uint strike, uint expiry, uint id); 849 | event Redeem(address indexed from, address indexed owner, uint amount, uint strike, uint id); 850 | event Refund(address indexed from, address indexed owner, uint amount, uint strike, uint id); 851 | 852 | constructor(address _treasury) { 853 | gov = msg.sender; 854 | treasury = _treasury; 855 | oKP3R = new Keep3rOptions(); 856 | } 857 | 858 | modifier g() { 859 | require(msg.sender == gov); 860 | _; 861 | } 862 | 863 | function setGov(address _gov) external g { 864 | nextGov = _gov; 865 | delayGov = block.timestamp + DELAY; 866 | } 867 | 868 | function acceptGov() external { 869 | require(msg.sender == nextGov && delayGov < block.timestamp); 870 | gov = nextGov; 871 | } 872 | 873 | function setDiscount(uint _discount) external g { 874 | nextDiscount = _discount; 875 | delayDiscount = block.timestamp + DELAY; 876 | } 877 | 878 | function commitDiscount() external g { 879 | require(delayDiscount < block.timestamp); 880 | discount = nextDiscount; 881 | } 882 | 883 | function setTreasury(address _treasury) external g { 884 | nextTreasury = _treasury; 885 | delayTreasury = block.timestamp + DELAY; 886 | } 887 | 888 | function commitTreasury() external g { 889 | require(delayTreasury < block.timestamp); 890 | treasury = nextTreasury; 891 | } 892 | 893 | /// @notice Total number of tokens in circulation 894 | uint public totalSupply = 0; 895 | 896 | mapping(address => mapping (address => uint)) public allowance; 897 | mapping(address => uint) public balanceOf; 898 | 899 | event Transfer(address indexed from, address indexed to, uint amount); 900 | event Approval(address indexed owner, address indexed spender, uint amount); 901 | 902 | function refund(uint[] memory _ids) external { 903 | for (uint i = 0; i < _ids.length; i++) { 904 | option storage _opt = options[_ids[i]]; 905 | if (_opt.expiry < block.timestamp && !_opt.exercised) { 906 | _opt.exercised = true; 907 | _safeTransfer(KP3R, treasury, _opt.amount); 908 | address _owner = oKP3R.ownerOf(_ids[i]); 909 | oKP3R.burn(_ids[i]); 910 | emit Refund(msg.sender, _owner, _opt.amount, _opt.strike, _ids[i]); 911 | } 912 | } 913 | } 914 | 915 | function _fetchTwap( 916 | address _tokenIn, 917 | address _tokenOut, 918 | uint24 _poolFee, 919 | uint32 _twapPeriod, 920 | uint _amountIn 921 | ) internal view returns (uint256 amountOut) { 922 | address pool = 923 | PoolAddress.computeAddress(UNIv3, PoolAddress.getPoolKey(_tokenIn, _tokenOut, _poolFee)); 924 | // Leave twapTick as a int256 to avoid solidity casting 925 | int256 twapTick = OracleLibrary.consult(pool, _twapPeriod); 926 | return 927 | OracleLibrary.getQuoteAtTick( 928 | int24(twapTick), // can assume safe being result from consult() 929 | SafeUint128.toUint128(_amountIn), 930 | _tokenIn, 931 | _tokenOut 932 | ); 933 | } 934 | 935 | function assetToAsset( 936 | address _tokenIn, 937 | uint _amountIn, 938 | address _tokenOut, 939 | uint32 _twapPeriod 940 | ) public view returns (uint ethAmountOut) { 941 | uint256 ethAmount = assetToEth(_tokenIn, _amountIn, _twapPeriod); 942 | return ethToAsset(ethAmount, _tokenOut, _twapPeriod); 943 | } 944 | 945 | function assetToEth( 946 | address _tokenIn, 947 | uint _amountIn, 948 | uint32 _twapPeriod 949 | ) public view returns (uint ethAmountOut) { 950 | return _fetchTwap(_tokenIn, WETH, 10000, _twapPeriod, _amountIn); 951 | } 952 | 953 | function ethToAsset( 954 | uint _ethAmountIn, 955 | address _tokenOut, 956 | uint32 _twapPeriod 957 | ) public view returns (uint256 amountOut) { 958 | return _fetchTwap(WETH, _tokenOut, 3000, _twapPeriod, _ethAmountIn); 959 | } 960 | 961 | function price() external view returns (uint) { 962 | return assetToAsset(KP3R, 1e18, USDC, TWAP_PERIOD); 963 | } 964 | 965 | function twap() external view returns (uint) { 966 | return assetToAsset(KP3R, 1e18, USDC, TWAP_NOW); 967 | } 968 | 969 | function calc(uint amount) public view returns (uint) { 970 | uint _strike = assetToAsset(KP3R, amount, USDC, TWAP_PERIOD); 971 | uint _price = assetToAsset(KP3R, amount, USDC, TWAP_NOW); 972 | _strike = _strike * discount / BASE; 973 | _price = _price * discount / BASE; 974 | return _strike > _price ? _strike : _price; 975 | } 976 | 977 | function deposit(uint _amount) external returns (bool) { 978 | _safeTransferFrom(KP3R, msg.sender, address(this), _amount); 979 | _mint(msg.sender, _amount); 980 | return true; 981 | } 982 | 983 | function claim() external returns (uint) { 984 | uint _amount = balanceOf[msg.sender]; 985 | _burn(msg.sender, _amount); 986 | return _claim(_amount); 987 | } 988 | 989 | function claim(uint amount) external returns (uint) { 990 | _burn(msg.sender, amount); 991 | return _claim(amount); 992 | } 993 | 994 | function _claim(uint amount) internal returns (uint) { 995 | uint _strike = calc(amount); 996 | uint _expiry = block.timestamp + OPTION_EXPIRY; 997 | options.push(option(amount, _strike, _expiry, false)); 998 | oKP3R.mint(msg.sender, nextIndex); 999 | emit Created(msg.sender, amount, _strike, _expiry, nextIndex); 1000 | return nextIndex++; 1001 | } 1002 | 1003 | function redeem(uint id) external { 1004 | require(oKP3R.isApprovedOrOwner(msg.sender, id)); 1005 | option storage _opt = options[id]; 1006 | require(_opt.expiry >= block.timestamp && !_opt.exercised); 1007 | _opt.exercised = true; 1008 | _safeTransferFrom(USDC, msg.sender, treasury, _opt.strike); 1009 | _safeTransfer(KP3R, msg.sender, _opt.amount); 1010 | oKP3R.burn(id); 1011 | emit Redeem(msg.sender, msg.sender, _opt.amount, _opt.strike, id); 1012 | } 1013 | 1014 | function _mint(address to, uint amount) internal { 1015 | // mint the amount 1016 | totalSupply += amount; 1017 | // transfer the amount to the recipient 1018 | balanceOf[to] += amount; 1019 | emit Transfer(address(0), to, amount); 1020 | } 1021 | 1022 | function _burn(address from, uint amount) internal { 1023 | // burn the amount 1024 | totalSupply -= amount; 1025 | // transfer the amount from the recipient 1026 | balanceOf[from] -= amount; 1027 | emit Transfer(from, address(0), amount); 1028 | } 1029 | 1030 | function approve(address spender, uint amount) external returns (bool) { 1031 | allowance[msg.sender][spender] = amount; 1032 | 1033 | emit Approval(msg.sender, spender, amount); 1034 | return true; 1035 | } 1036 | 1037 | function transfer(address dst, uint amount) external returns (bool) { 1038 | _transferTokens(msg.sender, dst, amount); 1039 | return true; 1040 | } 1041 | 1042 | function transferFrom(address src, address dst, uint amount) external returns (bool) { 1043 | address spender = msg.sender; 1044 | uint spenderAllowance = allowance[src][spender]; 1045 | 1046 | if (spender != src && spenderAllowance != type(uint).max) { 1047 | uint newAllowance = spenderAllowance - amount; 1048 | allowance[src][spender] = newAllowance; 1049 | 1050 | emit Approval(src, spender, newAllowance); 1051 | } 1052 | 1053 | _transferTokens(src, dst, amount); 1054 | return true; 1055 | } 1056 | 1057 | function _transferTokens(address src, address dst, uint amount) internal { 1058 | balanceOf[src] -= amount; 1059 | balanceOf[dst] += amount; 1060 | 1061 | emit Transfer(src, dst, amount); 1062 | } 1063 | 1064 | function _safeTransfer(address token, address to, uint256 value) internal { 1065 | (bool success, bytes memory data) = 1066 | token.call(abi.encodeWithSelector(erc20.transfer.selector, to, value)); 1067 | require(success && (data.length == 0 || abi.decode(data, (bool)))); 1068 | } 1069 | 1070 | function _safeTransferFrom(address token, address from, address to, uint256 value) internal { 1071 | (bool success, bytes memory data) = 1072 | token.call(abi.encodeWithSelector(erc20.transferFrom.selector, from, to, value)); 1073 | require(success && (data.length == 0 || abi.decode(data, (bool)))); 1074 | } 1075 | } 1076 | --------------------------------------------------------------------------------