├── CoreVault.sol ├── ENCORE.sol ├── FeeApprover.sol ├── FeeGenerator.sol ├── GovernorAlpha.sol ├── IEncoreVault.sol ├── IFeeApprover.sol ├── INBUNIERC20.sol ├── KOVAN.md ├── LICENSE ├── LP.sol ├── NBUNIERC20.sol ├── README.md ├── WETH9.sol └── uniswapv2 ├── LICENSE ├── README.md ├── UniswapV2ERC20.sol ├── UniswapV2Factory.sol ├── UniswapV2Pair.sol ├── UniswapV2Router02.sol ├── interfaces ├── IERC20.sol ├── IUniswapV2Callee.sol ├── IUniswapV2ERC20.sol ├── IUniswapV2Factory.sol ├── IUniswapV2Pair.sol ├── IUniswapV2Router01.sol ├── IUniswapV2Router02.sol └── IWETH.sol └── libraries ├── Math.sol ├── SafeMath.sol ├── TransferHelper.sol ├── UQ112x112.sol └── UniswapV2Library.sol /CoreVault.sol: -------------------------------------------------------------------------------- 1 | pragma solidity 0.6.12; 2 | 3 | 4 | import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; 5 | import "@openzeppelin/contracts-ethereum-package/contracts/utils/EnumerableSet.sol"; 6 | import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; 7 | import "./INBUNIERC20.sol"; 8 | 9 | library SafeMath { 10 | function add(uint256 a, uint256 b) internal pure returns (uint256) { 11 | uint256 c = a + b; 12 | require(c >= a, "SafeMath: addition overflow"); 13 | 14 | return c; 15 | } 16 | function sub(uint256 a, uint256 b) internal pure returns (uint256) { 17 | return sub(a, b, "SafeMath: subtraction overflow"); 18 | } 19 | function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { 20 | require(b <= a, errorMessage); 21 | uint256 c = a - b; 22 | 23 | return c; 24 | } 25 | function mul(uint256 a, uint256 b) internal pure returns (uint256) { 26 | if (a == 0) { 27 | return 0; 28 | } 29 | 30 | uint256 c = a * b; 31 | require(c / a == b, "SafeMath: multiplication overflow"); 32 | 33 | return c; 34 | } 35 | function div(uint256 a, uint256 b) internal pure returns (uint256) { 36 | return div(a, b, "SafeMath: division by zero"); 37 | } 38 | function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { 39 | require(b > 0, errorMessage); 40 | uint256 c = a / b; 41 | // assert(a == b * c + a % b); // There is no case in which this doesn't hold 42 | 43 | return c; 44 | } 45 | function mod(uint256 a, uint256 b) internal pure returns (uint256) { 46 | return mod(a, b, "SafeMath: modulo by zero"); 47 | } 48 | function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { 49 | require(b != 0, errorMessage); 50 | return a % b; 51 | } 52 | } 53 | 54 | // Encore Vault distributes fees equally amongst staked pools 55 | // Have fun reading it. Hopefully it's bug-free. God bless. 56 | contract EncoreVault is OwnableUpgradeSafe { 57 | using SafeMath for uint256; 58 | using SafeMath for uint; 59 | 60 | // Info of each user. 61 | struct UserInfo { 62 | uint256 amount; // How many tokens the user has provided. 63 | uint256 rewardDebt; // Reward debt. See explanation below. 64 | // 65 | // We do some fancy math here. Basically, any point in time, the amount of ENCOREs 66 | // entitled to a user but is pending to be distributed is: 67 | // 68 | // pending reward = (user.amount * pool.accEncorePerShare) - user.rewardDebt 69 | // 70 | // Whenever a user deposits or withdraws tokens to a pool. Here's what happens: 71 | // 1. The pool's `accEncorePerShare` (and `lastRewardBlock`) gets updated. 72 | // 2. User receives the pending reward sent to his/her address. 73 | // 3. User's `amount` gets updated. 74 | // 4. User's `rewardDebt` gets updated. 75 | 76 | } 77 | 78 | // Info of each pool. 79 | struct PoolInfo { 80 | IERC20 token; // Address of token contract. 81 | uint256 allocPoint; // How many allocation points assigned to this pool. ENCOREs to distribute per block. 82 | uint256 accEncorePerShare; // Accumulated ENCOREs per share, times 1e12. See below. 83 | bool withdrawable; // Is this pool withdrawable? 84 | bool depositable; // Is this pool depositable? 85 | mapping(address => mapping(address => uint256)) allowance; 86 | } 87 | 88 | // The ENCORE TOKEN! 89 | INBUNIERC20 public encore; 90 | // Dev address. 91 | address public devaddr; 92 | 93 | // Info of each pool. 94 | PoolInfo[] public poolInfo; 95 | // Info of each user that stakes tokens. 96 | mapping(uint256 => mapping(address => UserInfo)) public userInfo; 97 | // Total allocation poitns. Must be the sum of all allocation points in all pools. 98 | uint256 public totalAllocPoint; 99 | 100 | //// pending rewards awaiting anyone to massUpdate 101 | uint256 public pendingRewards; 102 | 103 | uint256 public contractStartBlock; 104 | uint256 public epochCalculationStartBlock; 105 | uint256 public cumulativeRewardsSinceStart; 106 | uint256 public rewardsInThisEpoch; 107 | uint public epoch; 108 | address public ENCOREETHLPBurnAddress; 109 | mapping(address=>bool) public voidWithdrawList; 110 | 111 | // Returns fees generated since start of this contract 112 | function averageFeesPerBlockSinceStart() external view returns (uint averagePerBlock) { 113 | averagePerBlock = cumulativeRewardsSinceStart.add(rewardsInThisEpoch).div(block.number.sub(contractStartBlock)); 114 | } 115 | 116 | // Returns averge fees in this epoch 117 | function averageFeesPerBlockEpoch() external view returns (uint256 averagePerBlock) { 118 | averagePerBlock = rewardsInThisEpoch.div(block.number.sub(epochCalculationStartBlock)); 119 | } 120 | 121 | // For easy graphing historical epoch rewards 122 | mapping(uint => uint256) public epochRewards; 123 | 124 | //Starts a new calculation epoch 125 | // Because averge since start will not be accurate 126 | function startNewEpoch() public { 127 | require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week 128 | epochRewards[epoch] = rewardsInThisEpoch; 129 | cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.add(rewardsInThisEpoch); 130 | rewardsInThisEpoch = 0; 131 | epochCalculationStartBlock = block.number; 132 | ++epoch; 133 | } 134 | 135 | event Deposit(address indexed user, uint256 indexed pid, uint256 amount); 136 | event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); 137 | event EmergencyWithdraw( 138 | address indexed user, 139 | uint256 indexed pid, 140 | uint256 amount 141 | ); 142 | event Approval(address indexed owner, address indexed spender, uint256 _pid, uint256 value); 143 | 144 | 145 | function initialize( 146 | INBUNIERC20 _encore, 147 | address _devaddr, 148 | address superAdmin 149 | ) public initializer { 150 | OwnableUpgradeSafe.__Ownable_init(); 151 | DEV_FEE = 1666; 152 | encore = _encore; 153 | devaddr = _devaddr; 154 | contractStartBlock = block.number; 155 | _superAdmin = superAdmin; 156 | } 157 | 158 | function poolLength() external view returns (uint256) { 159 | return poolInfo.length; 160 | } 161 | 162 | 163 | 164 | // Add a new token pool. Can only be called by the owner. 165 | // Note contract owner is meant to be a governance contract allowing ENCORE governance consensus 166 | function add( 167 | uint256 _allocPoint, 168 | IERC20 _token, 169 | bool _withUpdate, 170 | bool _withdrawable, 171 | bool _depositable 172 | ) public onlyOwner { 173 | if (_withUpdate) { 174 | massUpdatePools(); 175 | } 176 | 177 | uint256 length = poolInfo.length; 178 | for (uint256 pid = 0; pid < length; ++pid) { 179 | require(poolInfo[pid].token != _token,"Error pool already added"); 180 | } 181 | 182 | totalAllocPoint = totalAllocPoint.add(_allocPoint); 183 | 184 | 185 | poolInfo.push( 186 | PoolInfo({ 187 | token: _token, 188 | allocPoint: _allocPoint, 189 | accEncorePerShare: 0, 190 | withdrawable : _withdrawable, 191 | depositable : _depositable 192 | }) 193 | ); 194 | } 195 | 196 | // Update the given pool's ENCOREs allocation point. Can only be called by the owner. 197 | // Note contract owner is meant to be a governance contract allowing ENCORE governance consensus 198 | 199 | function set( 200 | uint256 _pid, 201 | uint256 _allocPoint, 202 | bool _withUpdate 203 | ) public onlyOwner { 204 | if (_withUpdate) { 205 | massUpdatePools(); 206 | } 207 | 208 | totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( 209 | _allocPoint 210 | ); 211 | poolInfo[_pid].allocPoint = _allocPoint; 212 | } 213 | 214 | // Update the given pool's ability to withdraw tokens 215 | // Note contract owner is meant to be a governance contract allowing ENCORE governance consensus 216 | function setPoolWithdrawable( 217 | uint256 _pid, 218 | bool _withdrawable 219 | ) public onlyOwner { 220 | poolInfo[_pid].withdrawable = _withdrawable; 221 | } 222 | 223 | function setPoolDepositable( 224 | uint256 _pid, 225 | bool _depositable 226 | ) public onlyOwner { 227 | poolInfo[_pid].depositable = _depositable; 228 | } 229 | 230 | 231 | // Note contract owner is meant to be a governance contract allowing ENCORE governance consensus 232 | uint16 public DEV_FEE; 233 | function setDevFee(uint16 _DEV_FEE) public onlyOwner { 234 | require(_DEV_FEE <= 2000, 'Dev fee clamped at 20%'); 235 | DEV_FEE = _DEV_FEE; 236 | } 237 | uint256 pending_DEV_rewards; 238 | 239 | // Update reward vairables for all pools. Be careful of gas spending! 240 | function massUpdatePools() public { 241 | uint256 length = poolInfo.length; 242 | uint allRewards; 243 | for (uint256 pid = 0; pid < length; ++pid) { 244 | allRewards = allRewards.add(updatePool(pid)); 245 | } 246 | 247 | pendingRewards = pendingRewards.sub(allRewards); 248 | } 249 | 250 | function editVoidWithdrawList(address _user, bool _voidfee) public onlyOwner { 251 | voidWithdrawList[_user] = _voidfee; 252 | } 253 | 254 | // ---- 255 | // Function that adds pending rewards, called by the ENCORE token. 256 | // ---- 257 | uint256 private encoreBalance; 258 | function addPendingRewards(uint256 _) public { 259 | uint256 newRewards = encore.balanceOf(address(this)).sub(encoreBalance); 260 | 261 | if(newRewards > 0) { 262 | encoreBalance = encore.balanceOf(address(this)); // If there is no change the balance didn't change 263 | pendingRewards = pendingRewards.add(newRewards); 264 | rewardsInThisEpoch = rewardsInThisEpoch.add(newRewards); 265 | } 266 | } 267 | 268 | // Update reward variables of the given pool to be up-to-date. 269 | function updatePool(uint256 _pid) public returns (uint256 encoreRewardWhole) { 270 | PoolInfo storage pool = poolInfo[_pid]; 271 | 272 | uint256 tokenSupply = pool.token.balanceOf(address(this)); 273 | if (tokenSupply == 0) { // avoids division by 0 errors 274 | return 0; 275 | } 276 | encoreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation 277 | .mul(pool.allocPoint) // getting the percent of total pending rewards this pool should get 278 | .div(totalAllocPoint); // we can do this because pools are only mass updated 279 | uint256 encoreRewardFee = encoreRewardWhole.mul(DEV_FEE).div(10000); 280 | uint256 encoreRewardToDistribute = encoreRewardWhole.sub(encoreRewardFee); 281 | 282 | pending_DEV_rewards = pending_DEV_rewards.add(encoreRewardFee); 283 | 284 | pool.accEncorePerShare = pool.accEncorePerShare.add( 285 | encoreRewardToDistribute.mul(1e12).div(tokenSupply) 286 | ); 287 | 288 | } 289 | 290 | function safeFixUnits(uint256 _pid) public { 291 | PoolInfo storage pool = poolInfo[_pid]; 292 | UserInfo storage user = userInfo[_pid][msg.sender]; 293 | user.rewardDebt = user.amount.mul(pool.accEncorePerShare).div(1e12); 294 | } 295 | 296 | // Deposit tokens to EncoreVault for ENCORE allocation. 297 | function deposit(uint256 _pid, uint256 _amount) public { 298 | 299 | PoolInfo storage pool = poolInfo[_pid]; 300 | UserInfo storage user = userInfo[_pid][msg.sender]; 301 | 302 | require(pool.depositable == true, "Depositing into this pool is disabled"); 303 | massUpdatePools(); 304 | 305 | // Transfer pending tokens 306 | // to user 307 | updateAndPayOutPending(_pid, msg.sender); 308 | 309 | 310 | //Transfer in the amounts from user 311 | // save gas 312 | if(_amount > 0) { 313 | pool.token.transferFrom(address(msg.sender), address(this), _amount); 314 | user.amount = user.amount.add(_amount); 315 | } 316 | 317 | user.rewardDebt = user.amount.mul(pool.accEncorePerShare).div(1e12); 318 | emit Deposit(msg.sender, _pid, _amount); 319 | } 320 | 321 | // Test coverage 322 | // [x] Does user get the deposited amounts? 323 | // [x] Does user that its deposited for update correcty? 324 | // [x] Does the depositor get their tokens decreased 325 | function depositFor(address depositFor, uint256 _pid, uint256 _amount) public { 326 | // requires no allowances 327 | PoolInfo storage pool = poolInfo[_pid]; 328 | UserInfo storage user = userInfo[_pid][depositFor]; 329 | 330 | massUpdatePools(); 331 | 332 | require(pool.depositable == true, "Depositing into this pool is disabled"); 333 | // Transfer pending tokens 334 | // to user 335 | updateAndPayOutPending(_pid, depositFor); // Update the balances of person that amount is being deposited for 336 | 337 | if(_amount > 0) { 338 | pool.token.transferFrom(address(msg.sender), address(this), _amount); 339 | user.amount = user.amount.add(_amount); // This is depositedFor address 340 | } 341 | 342 | user.rewardDebt = user.amount.mul(pool.accEncorePerShare).div(1e12); /// This is deposited for address 343 | emit Deposit(depositFor, _pid, _amount); 344 | 345 | } 346 | 347 | // Test coverage 348 | // [x] Does allowance update correctly? 349 | function setAllowanceForPoolToken(address spender, uint256 _pid, uint256 value) public { 350 | PoolInfo storage pool = poolInfo[_pid]; 351 | pool.allowance[msg.sender][spender] = value; 352 | emit Approval(msg.sender, spender, _pid, value); 353 | } 354 | 355 | function setENCOREETHLPBurnAddress(address _burn) public onlyOwner { 356 | ENCOREETHLPBurnAddress = _burn; 357 | } 358 | 359 | // Test coverage 360 | // [x] Does allowance decrease? 361 | // [x] Do oyu need allowance 362 | // [x] Withdraws to correct address 363 | function withdrawFrom(address owner, uint256 _pid, uint256 _amount) public{ 364 | 365 | PoolInfo storage pool = poolInfo[_pid]; 366 | require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance"); 367 | pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].sub(_amount); 368 | _withdraw(_pid, _amount, owner, msg.sender); 369 | 370 | } 371 | 372 | 373 | // Withdraw tokens from EncoreVault. 374 | function withdraw(uint256 _pid, uint256 _amount) public { 375 | 376 | _withdraw(_pid, _amount, msg.sender, msg.sender); 377 | 378 | } 379 | 380 | function claim(uint256 _pid) public { 381 | _withdraw(_pid, 0, msg.sender,msg.sender); 382 | } 383 | 384 | // Low level withdraw function 385 | function _withdraw(uint256 _pid, uint256 _amount, address from, address to) internal { 386 | PoolInfo storage pool = poolInfo[_pid]; 387 | UserInfo storage user = userInfo[_pid][from]; 388 | 389 | massUpdatePools(); 390 | updateAndPayOutPending(_pid, from); // Update balances of from this is not withdrawal but claiming ENCORE farmed 391 | 392 | 393 | if(_amount > 0) { 394 | require(pool.withdrawable, "Withdrawing from this pool is disabled"); 395 | user.amount = user.amount.sub(_amount, "Insufficient balance"); 396 | if(_pid == 0) { 397 | if(voidWithdrawList[to] || ENCOREETHLPBurnAddress == address(0)) { 398 | pool.token.transfer(address(to), _amount); 399 | } else { 400 | pool.token.transfer(address(to), _amount.mul(95).div(100)); 401 | pool.token.transfer(address(ENCOREETHLPBurnAddress), _amount.mul(5).div(100)); 402 | } 403 | } else { 404 | pool.token.transfer(address(to), _amount); 405 | } 406 | } 407 | user.rewardDebt = user.amount.mul(pool.accEncorePerShare).div(1e12); 408 | 409 | emit Withdraw(to, _pid, _amount); 410 | } 411 | bool public fixUnits = true; 412 | 413 | function setFixUnits(bool _bool) public onlyOwner { 414 | fixUnits = _bool; 415 | } 416 | function updateAndPayOutPending(uint256 _pid, address from) internal { 417 | 418 | if(fixUnits == true) {safeFixUnits(0);} 419 | uint256 pending = pendingENCORE(_pid, from); 420 | 421 | if(pending > 0) { 422 | safeEncoreTransfer(from, pending); 423 | } 424 | 425 | } 426 | 427 | function pendingENCORE(uint256 _pid, address _user) public view returns (uint256) { 428 | PoolInfo storage pool = poolInfo[_pid]; 429 | UserInfo storage user = userInfo[_pid][_user]; 430 | uint256 accEncorePerShare = pool.accEncorePerShare; 431 | 432 | return user.amount.mul(accEncorePerShare).div(1e12).sub(user.rewardDebt); 433 | } 434 | 435 | 436 | // function that lets owner/governance contract 437 | // approve allowance for any token inside this contract 438 | // This means all future UNI like airdrops are covered 439 | // And at the same time allows us to give allowance to strategy contracts. 440 | // Upcoming cYFI etc vaults strategy contracts will se this function to manage and farm yield on value locked 441 | function setStrategyContractOrDistributionContractAllowance(address tokenAddress, uint256 _amount, address contractAddress) public onlySuperAdmin { 442 | require(isContract(contractAddress), "Recipent is not a smart contract, BAD"); 443 | require(block.number > contractStartBlock.add(95_000), "Governance setup grace period not over"); // about 2weeks 444 | IERC20(tokenAddress).approve(contractAddress, _amount); 445 | } 446 | 447 | function isContract(address addr) public returns (bool) { 448 | uint size; 449 | assembly { size := extcodesize(addr) } 450 | return size > 0; 451 | } 452 | 453 | 454 | // Withdraw without caring about rewards. EMERGENCY ONLY. 455 | // !Caution this will remove all your pending rewards! 456 | function emergencyWithdraw(uint256 _pid) public { 457 | PoolInfo storage pool = poolInfo[_pid]; 458 | require(pool.withdrawable, "Withdrawing from this pool is disabled"); 459 | UserInfo storage user = userInfo[_pid][msg.sender]; 460 | pool.token.transfer(address(msg.sender), user.amount); 461 | emit EmergencyWithdraw(msg.sender, _pid, user.amount); 462 | user.amount = 0; 463 | user.rewardDebt = 0; 464 | // No mass update dont update pending rewards 465 | } 466 | 467 | // Safe encore transfer function, just in case if rounding error causes pool to not have enough ENCOREs. 468 | function safeEncoreTransfer(address _to, uint256 _amount) internal { 469 | if(_amount == 0) return; 470 | 471 | uint256 encoreBal = encore.balanceOf(address(this)); 472 | encore.transfer(_to, _amount); 473 | encoreBalance = encore.balanceOf(address(this)); 474 | 475 | if(pending_DEV_rewards > 0) { 476 | uint256 devSend = pending_DEV_rewards; // Avoid recursive loop 477 | pending_DEV_rewards = 0; 478 | safeEncoreTransfer(devaddr, devSend); 479 | } 480 | 481 | } 482 | 483 | function stakedTokens(uint256 _pid, address _user) public view returns (uint256) { 484 | UserInfo storage user = userInfo[_pid][_user]; 485 | return user.amount; 486 | } 487 | 488 | // Update dev address by the previous dev. 489 | function setDevFeeReciever(address _devaddr) public onlyOwner { 490 | devaddr = _devaddr; 491 | } 492 | 493 | 494 | 495 | address private _superAdmin; 496 | 497 | event SuperAdminTransfered(address indexed previousOwner, address indexed newOwner); 498 | 499 | 500 | 501 | /** 502 | * @dev Returns the address of the current super admin 503 | */ 504 | function superAdmin() public view returns (address) { 505 | return _superAdmin; 506 | } 507 | 508 | /** 509 | * @dev Throws if called by any account other than the superAdmin 510 | */ 511 | modifier onlySuperAdmin() { 512 | require(_superAdmin == _msgSender(), "Super admin : caller is not super admin."); 513 | _; 514 | } 515 | 516 | // Assisns super admint to address 0, making it unreachable forever 517 | function burnSuperAdmin() public virtual onlySuperAdmin { 518 | emit SuperAdminTransfered(_superAdmin, address(0)); 519 | _superAdmin = address(0); 520 | } 521 | 522 | // Super admin can transfer its powers to another address 523 | function newSuperAdmin(address newOwner) public virtual onlySuperAdmin { 524 | require(newOwner != address(0), "Ownable: new owner is the zero address"); 525 | emit SuperAdminTransfered(_superAdmin, newOwner); 526 | _superAdmin = newOwner; 527 | } 528 | } 529 | -------------------------------------------------------------------------------- /ENCORE.sol: -------------------------------------------------------------------------------- 1 | pragma solidity 0.6.12; 2 | 3 | 4 | import "./NBUNIERC20.sol"; 5 | import "@openzeppelin/contracts/access/Ownable.sol"; 6 | 7 | 8 | 9 | // EncoreToken with Governance. 10 | contract ENCORE is NBUNIERC20 { 11 | 12 | 13 | /** 14 | * @dev Sets the values for {name} and {symbol}, initializes {decimals} with 15 | * a default value of 18. 16 | * 17 | * To select a different value for {decimals}, use {_setupDecimals}. 18 | * 19 | * All three of these values are immutable: they can only be set once during 20 | * construction. 21 | */ 22 | constructor(address router, address factory) public { 23 | 24 | initialSetup(router, factory); 25 | // _name = name; 26 | // _symbol = symbol; 27 | // _decimals = 18; 28 | // _totalSupply = initialSupply; 29 | // _balances[address(this)] = initialSupply; 30 | // contractStartTimestamp = block.timestamp; 31 | // // UNISWAP 32 | // IUniswapV2Router02(router != address(0) ? router : 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); // For testing 33 | // IUniswapV2Factory(factory != address(0) ? factory : 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); // For testing 34 | } 35 | 36 | // Copied and modified from YAM code: 37 | // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol 38 | // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol 39 | // Which is copied and modified from COMPOUND: 40 | // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol 41 | 42 | mapping (address => address) internal _delegates; 43 | 44 | /// @notice A checkpoint for marking number of votes from a given block 45 | struct Checkpoint { 46 | uint32 fromBlock; 47 | uint256 votes; 48 | } 49 | 50 | 51 | /// @notice A record of votes checkpoints for each account, by index 52 | mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; 53 | 54 | /// @notice The number of checkpoints for each account 55 | mapping (address => uint32) public numCheckpoints; 56 | 57 | /// @notice The EIP-712 typehash for the contract's domain 58 | bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); 59 | 60 | /// @notice The EIP-712 typehash for the delegation struct used by the contract 61 | bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); 62 | 63 | /// @notice A record of states for signing / validating signatures 64 | mapping (address => uint) public nonces; 65 | 66 | /// @notice An event thats emitted when an account changes its delegate 67 | event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); 68 | 69 | /// @notice An event thats emitted when a delegate account's vote balance changes 70 | event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); 71 | 72 | /** 73 | * @notice Delegate votes from `msg.sender` to `delegatee` 74 | * @param delegator The address to get delegatee for 75 | */ 76 | function delegates(address delegator) 77 | external 78 | view 79 | returns (address) 80 | { 81 | return _delegates[delegator]; 82 | } 83 | 84 | /** 85 | * @notice Delegate votes from `msg.sender` to `delegatee` 86 | * @param delegatee The address to delegate votes to 87 | */ 88 | function delegate(address delegatee) external { 89 | return _delegate(msg.sender, delegatee); 90 | } 91 | 92 | /** 93 | * @notice Delegates votes from signatory to `delegatee` 94 | * @param delegatee The address to delegate votes to 95 | * @param nonce The contract state required to match the signature 96 | * @param expiry The time at which to expire the signature 97 | * @param v The recovery byte of the signature 98 | * @param r Half of the ECDSA signature pair 99 | * @param s Half of the ECDSA signature pair 100 | */ 101 | function delegateBySig( 102 | address delegatee, 103 | uint nonce, 104 | uint expiry, 105 | uint8 v, 106 | bytes32 r, 107 | bytes32 s 108 | ) 109 | external 110 | { 111 | bytes32 domainSeparator = keccak256( 112 | abi.encode( 113 | DOMAIN_TYPEHASH, 114 | keccak256(bytes(name())), 115 | getChainId(), 116 | address(this) 117 | ) 118 | ); 119 | 120 | bytes32 structHash = keccak256( 121 | abi.encode( 122 | DELEGATION_TYPEHASH, 123 | delegatee, 124 | nonce, 125 | expiry 126 | ) 127 | ); 128 | 129 | bytes32 digest = keccak256( 130 | abi.encodePacked( 131 | "\x19\x01", 132 | domainSeparator, 133 | structHash 134 | ) 135 | ); 136 | 137 | address signatory = ecrecover(digest, v, r, s); 138 | require(signatory != address(0), "ENCORE::delegateBySig: invalid signature"); 139 | require(nonce == nonces[signatory]++, "ENCORE::delegateBySig: invalid nonce"); 140 | require(now <= expiry, "ENCORE::delegateBySig: signature expired"); 141 | return _delegate(signatory, delegatee); 142 | } 143 | 144 | /** 145 | * @notice Gets the current votes balance for `account` 146 | * @param account The address to get votes balance 147 | * @return The number of current votes for `account` 148 | */ 149 | function getCurrentVotes(address account) 150 | external 151 | view 152 | returns (uint256) 153 | { 154 | uint32 nCheckpoints = numCheckpoints[account]; 155 | return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; 156 | } 157 | 158 | /** 159 | * @notice Determine the prior number of votes for an account as of a block number 160 | * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. 161 | * @param account The address of the account to check 162 | * @param blockNumber The block number to get the vote balance at 163 | * @return The number of votes the account had as of the given block 164 | */ 165 | function getPriorVotes(address account, uint blockNumber) 166 | external 167 | view 168 | returns (uint256) 169 | { 170 | require(blockNumber < block.number, "ENCORE::getPriorVotes: not yet determined"); 171 | 172 | uint32 nCheckpoints = numCheckpoints[account]; 173 | if (nCheckpoints == 0) { 174 | return 0; 175 | } 176 | 177 | // First check most recent balance 178 | if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { 179 | return checkpoints[account][nCheckpoints - 1].votes; 180 | } 181 | 182 | // Next check implicit zero balance 183 | if (checkpoints[account][0].fromBlock > blockNumber) { 184 | return 0; 185 | } 186 | 187 | uint32 lower = 0; 188 | uint32 upper = nCheckpoints - 1; 189 | while (upper > lower) { 190 | uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow 191 | Checkpoint memory cp = checkpoints[account][center]; 192 | if (cp.fromBlock == blockNumber) { 193 | return cp.votes; 194 | } else if (cp.fromBlock < blockNumber) { 195 | lower = center; 196 | } else { 197 | upper = center - 1; 198 | } 199 | } 200 | return checkpoints[account][lower].votes; 201 | } 202 | 203 | function _delegate(address delegator, address delegatee) 204 | internal 205 | { 206 | address currentDelegate = _delegates[delegator]; 207 | uint256 delegatorBalance = balanceOf(delegator); // balance of underlying ENCORE tokens (not scaled); 208 | _delegates[delegator] = delegatee; 209 | 210 | emit DelegateChanged(delegator, currentDelegate, delegatee); 211 | 212 | _moveDelegates(currentDelegate, delegatee, delegatorBalance); 213 | } 214 | 215 | function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { 216 | if (srcRep != dstRep && amount > 0) { 217 | if (srcRep != address(0)) { 218 | // decrease old representative 219 | uint32 srcRepNum = numCheckpoints[srcRep]; 220 | uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; 221 | uint256 srcRepNew = srcRepOld.sub(amount); 222 | _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); 223 | } 224 | 225 | if (dstRep != address(0)) { 226 | // increase new representative 227 | uint32 dstRepNum = numCheckpoints[dstRep]; 228 | uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; 229 | uint256 dstRepNew = dstRepOld.add(amount); 230 | _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); 231 | } 232 | } 233 | } 234 | 235 | function _writeCheckpoint( 236 | address delegatee, 237 | uint32 nCheckpoints, 238 | uint256 oldVotes, 239 | uint256 newVotes 240 | ) 241 | internal 242 | { 243 | uint32 blockNumber = safe32(block.number, "ENCORE::_writeCheckpoint: block number exceeds 32 bits"); 244 | 245 | if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { 246 | checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; 247 | } else { 248 | checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); 249 | numCheckpoints[delegatee] = nCheckpoints + 1; 250 | } 251 | 252 | emit DelegateVotesChanged(delegatee, oldVotes, newVotes); 253 | } 254 | 255 | function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { 256 | require(n < 2**32, errorMessage); 257 | return uint32(n); 258 | } 259 | 260 | function getChainId() internal pure returns (uint) { 261 | uint256 chainId; 262 | assembly { chainId := chainid() } 263 | return chainId; 264 | } 265 | } 266 | -------------------------------------------------------------------------------- /FeeApprover.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.6.0; 4 | import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; 5 | import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; 6 | import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; // for WETH 7 | import "@nomiclabs/buidler/console.sol"; 8 | import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol'; 9 | import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol"; 10 | 11 | contract FeeApprover is OwnableUpgradeSafe { 12 | using SafeMath for uint256; 13 | 14 | function initialize( 15 | address _ENCOREAddress, 16 | address _WETHAddress, 17 | address _uniswapFactory 18 | ) public initializer { 19 | OwnableUpgradeSafe.__Ownable_init(); 20 | encoreTokenAddress = _ENCOREAddress; 21 | WETHAddress = _WETHAddress; 22 | tokenETHPair = IUniswapV2Factory(_uniswapFactory).getPair(WETHAddress,encoreTokenAddress); 23 | feePercentX100 = 12; 24 | paused = true; 25 | sync(); 26 | //minFinney = 5000; 27 | } 28 | 29 | 30 | address tokenETHPair; 31 | address tokenLINKPair; 32 | IUniswapV2Factory public uniswapFactory; 33 | address internal WETHAddress; 34 | address encoreTokenAddress; 35 | address encoreVaultAddress; 36 | uint8 public feePercentX100; // max 255 = 25.5% artificial clamp 37 | uint256 public lastTotalSupplyOfLPTokens; 38 | bool paused; 39 | uint256 private lastSupplyOfEncoreInPair; 40 | uint256 private lastSupplyOfWETHInPair; 41 | address LGE; 42 | mapping (address => bool) public voidSenderList; 43 | mapping (address => bool) public voidReceiverList; 44 | mapping (address => bool) public discountFeeList; 45 | mapping (address => bool) public blockedReceiverList; 46 | 47 | function setPaused(bool _pause) public onlyOwner { 48 | paused = _pause; 49 | sync(); 50 | } 51 | 52 | function setFeeMultiplier(uint8 _feeMultiplier) public onlyOwner { 53 | feePercentX100 = _feeMultiplier; 54 | } 55 | 56 | function setEncoreVaultAddress(address _encoreVaultAddress) public onlyOwner { 57 | encoreVaultAddress = _encoreVaultAddress; 58 | voidSenderList[encoreVaultAddress] = true; 59 | } 60 | 61 | function editVoidSenderList(address _address, bool noFee) public onlyOwner{ 62 | voidSenderList[_address] = noFee; 63 | } 64 | 65 | function editDiscountFeeList(address _address, bool discFee) public onlyOwner{ 66 | discountFeeList[_address] = discFee; 67 | } 68 | 69 | function editBlockedReceiverList(address _address, bool _block) public onlyOwner{ 70 | blockedReceiverList[_address] = _block; 71 | } 72 | 73 | // uint minFinney; // 2x for $ liq amount 74 | // function setMinimumLiquidityToTriggerStop(uint finneyAmnt) public onlyOwner{ // 1000 = 1eth 75 | // minFinney = finneyAmnt; 76 | // } 77 | 78 | // function sync() public returns (bool lastIsMint, bool lpTokenBurn) { 79 | 80 | // // This will update the state of lastIsMint, when called publically 81 | // // So we have to sync it before to the last LP token value. 82 | // uint256 _LPSupplyOfPairTotal = IERC20(tokenUniswapPair).totalSupply(); 83 | // lpTokenBurn = lastTotalSupplyOfLPTokens > _LPSupplyOfPairTotal; 84 | // lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; 85 | 86 | // uint256 _balanceWETH = IERC20(WETHAddress).balanceOf(tokenUniswapPair); 87 | // uint256 _balanceENCORE = IERC20(encoreTokenAddress).balanceOf(tokenUniswapPair); 88 | 89 | // // Do not block after small liq additions 90 | // // you can only withdraw 350$ now with front running 91 | // // And cant front run buys with liq add ( adversary drain ) 92 | 93 | // lastIsMint = _balanceENCORE > lastSupplyOfEncoreInPair && _balanceWETH > lastSupplyOfWETHInPair.add(minFinney.mul(1 finney)); 94 | 95 | // lastSupplyOfEncoreInPair = _balanceENCORE; 96 | // lastSupplyOfWETHInPair = _balanceWETH; 97 | // } 98 | uint256 internal _LPSupplyOfPairTotal; 99 | function sync() public { 100 | _LPSupplyOfPairTotal = IERC20(tokenETHPair).totalSupply(); 101 | } 102 | 103 | function calculateAmountsAfterFee( 104 | address sender, 105 | address recipient, // unusued maybe use din future 106 | uint256 amount 107 | ) public returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) 108 | { 109 | require(paused == false, "FEE APPROVER: Transfers Paused"); 110 | sync(); 111 | 112 | 113 | // console.log("sender is " , sender); 114 | // console.log("recipient is is " , recipient, 'pair is :', tokenUniswapPair); 115 | 116 | // console.log("Old LP supply", lastTotalSupplyOfLPTokens); 117 | // console.log("Current LP supply", _LPSupplyOfPairTotal); 118 | 119 | if(sender == tokenETHPair) { 120 | require(lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal, "Liquidity withdrawals forbidden"); 121 | //require(lastIsMint == false, "Liquidity withdrawals forbidden"); 122 | //require(lpTokenBurn == false, "Liquidity withdrawals forbidden"); 123 | } 124 | 125 | require(blockedReceiverList[recipient] == false, "Blocked Recipient"); 126 | 127 | if(sender == encoreVaultAddress || voidSenderList[sender]) { // Dont have a fee when encorevault is sending, or infinite loop 128 | console.log("Sending without fee"); 129 | transferToFeeDistributorAmount = 0; 130 | transferToAmount = amount; 131 | } 132 | else { 133 | if(discountFeeList[sender]) { // half fee if offered fee discount 134 | console.log("Discount fee transfer"); 135 | transferToFeeDistributorAmount = amount.mul(feePercentX100).div(2000); 136 | transferToAmount = amount.sub(transferToFeeDistributorAmount); 137 | } else { 138 | console.log("Normal fee transfer"); 139 | transferToFeeDistributorAmount = amount.mul(feePercentX100).div(1000); 140 | transferToAmount = amount.sub(transferToFeeDistributorAmount); 141 | } 142 | } 143 | lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal; 144 | } 145 | 146 | 147 | } 148 | -------------------------------------------------------------------------------- /FeeGenerator.sol: -------------------------------------------------------------------------------- 1 | pragma solidity 0.6.12; 2 | 3 | import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; 4 | 5 | 6 | // Contract that sends tokens it gets to itself 7 | // Making it generate fees with fee on transfer tokens 8 | contract FeeGenerator { 9 | 10 | function transferToSelf(address tokenAddress, uint256 loopCount) public { 11 | for (uint256 counter = 0; counter < loopCount; ++counter) { 12 | IERC20(tokenAddress).transfer(address(this), IERC20(tokenAddress).balanceOf(address(this))); 13 | } 14 | } 15 | 16 | } -------------------------------------------------------------------------------- /GovernorAlpha.sol: -------------------------------------------------------------------------------- 1 | // COPIED FROM https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/GovernorAlpha.sol 2 | // Copyright 2020 Compound Labs, Inc. 3 | // Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 4 | // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 5 | // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 6 | // 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 7 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 8 | // 9 | // Ctrl+f for XXX to see all the modifications. 10 | // uint96s are changed to uint256s for simplicity and safety. 11 | 12 | // XXX: pragma solidity ^0.5.16; 13 | pragma solidity 0.6.12; 14 | pragma experimental ABIEncoderV2; 15 | 16 | import "./CORE.sol"; 17 | 18 | contract GovernorAlpha { 19 | /// @notice The name of this contract 20 | string public constant name = "EnCore Governor Alpha"; 21 | 22 | /// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed 23 | // XXX: function quorumVotes() public pure returns (uint) { return 400000e18; } // 400,000 = 4% of Comp 24 | function quorumVotes() public view returns (uint) { return encore.totalSupply() / 25; } // 4% of Supply 25 | 26 | /// @notice The number of votes required in order for a voter to become a proposer 27 | // function proposalThreshold() public pure returns (uint) { return 100000e18; } // 100,000 = 1% of Comp 28 | function proposalThreshold() public view returns (uint) { return encore.totalSupply() / 100; } // 1% of Supply 29 | 30 | /// @notice The maximum number of actions that can be included in a proposal 31 | function proposalMaxOperations() public pure returns (uint) { return 10; } // 10 actions 32 | 33 | /// @notice The delay before voting on a proposal may take place, once proposed 34 | function votingDelay() public pure returns (uint) { return 1; } // 1 block 35 | 36 | /// @notice The duration of voting on a proposal, in blocks 37 | function votingPeriod() public pure returns (uint) { return 17280; } // ~3 days in blocks (assuming 15s blocks) 38 | 39 | /// @notice The address of the Compound Protocol Timelock 40 | TimelockInterface public timelock; 41 | 42 | /// @notice The address of the Compound governance token 43 | // XXX: CompInterface public comp; 44 | ENCORE public encore; 45 | 46 | /// @notice The address of the Governor Guardian 47 | address public guardian; 48 | 49 | /// @notice The total number of proposals 50 | uint public proposalCount; 51 | 52 | struct Proposal { 53 | /// @notice Unique id for looking up a proposal 54 | uint id; 55 | 56 | /// @notice Creator of the proposal 57 | address proposer; 58 | 59 | /// @notice The timestamp that the proposal will be available for execution, set once the vote succeeds 60 | uint eta; 61 | 62 | /// @notice the ordered list of target addresses for calls to be made 63 | address[] targets; 64 | 65 | /// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made 66 | uint[] values; 67 | 68 | /// @notice The ordered list of function signatures to be called 69 | string[] signatures; 70 | 71 | /// @notice The ordered list of calldata to be passed to each call 72 | bytes[] calldatas; 73 | 74 | /// @notice The block at which voting begins: holders must delegate their votes prior to this block 75 | uint startBlock; 76 | 77 | /// @notice The block at which voting ends: votes must be cast prior to this block 78 | uint endBlock; 79 | 80 | /// @notice Current number of votes in favor of this proposal 81 | uint forVotes; 82 | 83 | /// @notice Current number of votes in opposition to this proposal 84 | uint againstVotes; 85 | 86 | /// @notice Flag marking whether the proposal has been canceled 87 | bool canceled; 88 | 89 | /// @notice Flag marking whether the proposal has been executed 90 | bool executed; 91 | 92 | /// @notice Receipts of ballots for the entire set of voters 93 | mapping (address => Receipt) receipts; 94 | } 95 | 96 | /// @notice Ballot receipt record for a voter 97 | struct Receipt { 98 | /// @notice Whether or not a vote has been cast 99 | bool hasVoted; 100 | 101 | /// @notice Whether or not the voter supports the proposal 102 | bool support; 103 | 104 | /// @notice The number of votes the voter had, which were cast 105 | uint256 votes; 106 | } 107 | 108 | /// @notice Possible states that a proposal may be in 109 | enum ProposalState { 110 | Pending, 111 | Active, 112 | Canceled, 113 | Defeated, 114 | Succeeded, 115 | Queued, 116 | Expired, 117 | Executed 118 | } 119 | 120 | /// @notice The official record of all proposals ever proposed 121 | mapping (uint => Proposal) public proposals; 122 | 123 | /// @notice The latest proposal for each proposer 124 | mapping (address => uint) public latestProposalIds; 125 | 126 | /// @notice The EIP-712 typehash for the contract's domain 127 | bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); 128 | 129 | /// @notice The EIP-712 typehash for the ballot struct used by the contract 130 | bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,bool support)"); 131 | 132 | /// @notice An event emitted when a new proposal is created 133 | event ProposalCreated(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description); 134 | 135 | /// @notice An event emitted when a vote has been cast on a proposal 136 | event VoteCast(address voter, uint proposalId, bool support, uint votes); 137 | 138 | /// @notice An event emitted when a proposal has been canceled 139 | event ProposalCanceled(uint id); 140 | 141 | /// @notice An event emitted when a proposal has been queued in the Timelock 142 | event ProposalQueued(uint id, uint eta); 143 | 144 | /// @notice An event emitted when a proposal has been executed in the Timelock 145 | event ProposalExecuted(uint id); 146 | 147 | constructor(address timelock_, address encore_, address guardian_) public { 148 | timelock = TimelockInterface(timelock_); 149 | encore = ENCORE(encore_); 150 | guardian = guardian_; 151 | } 152 | 153 | function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) { 154 | require(encore.getPriorVotes(msg.sender, sub256(block.number, 1)) > proposalThreshold(), "GovernorAlpha::propose: proposer votes below proposal threshold"); 155 | require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorAlpha::propose: proposal function information arity mismatch"); 156 | require(targets.length != 0, "GovernorAlpha::propose: must provide actions"); 157 | require(targets.length <= proposalMaxOperations(), "GovernorAlpha::propose: too many actions"); 158 | 159 | uint latestProposalId = latestProposalIds[msg.sender]; 160 | if (latestProposalId != 0) { 161 | ProposalState proposersLatestProposalState = state(latestProposalId); 162 | require(proposersLatestProposalState != ProposalState.Active, "GovernorAlpha::propose: one live proposal per proposer, found an already active proposal"); 163 | require(proposersLatestProposalState != ProposalState.Pending, "GovernorAlpha::propose: one live proposal per proposer, found an already pending proposal"); 164 | } 165 | 166 | uint startBlock = add256(block.number, votingDelay()); 167 | uint endBlock = add256(startBlock, votingPeriod()); 168 | 169 | proposalCount++; 170 | Proposal memory newProposal = Proposal({ 171 | id: proposalCount, 172 | proposer: msg.sender, 173 | eta: 0, 174 | targets: targets, 175 | values: values, 176 | signatures: signatures, 177 | calldatas: calldatas, 178 | startBlock: startBlock, 179 | endBlock: endBlock, 180 | forVotes: 0, 181 | againstVotes: 0, 182 | canceled: false, 183 | executed: false 184 | }); 185 | 186 | proposals[newProposal.id] = newProposal; 187 | latestProposalIds[newProposal.proposer] = newProposal.id; 188 | 189 | emit ProposalCreated(newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description); 190 | return newProposal.id; 191 | } 192 | 193 | function queue(uint proposalId) public { 194 | require(state(proposalId) == ProposalState.Succeeded, "GovernorAlpha::queue: proposal can only be queued if it is succeeded"); 195 | Proposal storage proposal = proposals[proposalId]; 196 | uint eta = add256(block.timestamp, timelock.delay()); 197 | for (uint i = 0; i < proposal.targets.length; i++) { 198 | _queueOrRevert(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta); 199 | } 200 | proposal.eta = eta; 201 | emit ProposalQueued(proposalId, eta); 202 | } 203 | 204 | function _queueOrRevert(address target, uint value, string memory signature, bytes memory data, uint eta) internal { 205 | require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorAlpha::_queueOrRevert: proposal action already queued at eta"); 206 | timelock.queueTransaction(target, value, signature, data, eta); 207 | } 208 | 209 | function execute(uint proposalId) public payable { 210 | require(state(proposalId) == ProposalState.Queued, "GovernorAlpha::execute: proposal can only be executed if it is queued"); 211 | Proposal storage proposal = proposals[proposalId]; 212 | proposal.executed = true; 213 | for (uint i = 0; i < proposal.targets.length; i++) { 214 | timelock.executeTransaction.value(proposal.values[i])(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); 215 | } 216 | emit ProposalExecuted(proposalId); 217 | } 218 | 219 | function cancel(uint proposalId) public { 220 | ProposalState state = state(proposalId); 221 | require(state != ProposalState.Executed, "GovernorAlpha::cancel: cannot cancel executed proposal"); 222 | 223 | Proposal storage proposal = proposals[proposalId]; 224 | require(msg.sender == guardian || encore.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold(), "GovernorAlpha::cancel: proposer above threshold"); 225 | 226 | proposal.canceled = true; 227 | for (uint i = 0; i < proposal.targets.length; i++) { 228 | timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta); 229 | } 230 | 231 | emit ProposalCanceled(proposalId); 232 | } 233 | 234 | function getActions(uint proposalId) public view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) { 235 | Proposal storage p = proposals[proposalId]; 236 | return (p.targets, p.values, p.signatures, p.calldatas); 237 | } 238 | 239 | function getReceipt(uint proposalId, address voter) public view returns (Receipt memory) { 240 | return proposals[proposalId].receipts[voter]; 241 | } 242 | 243 | function state(uint proposalId) public view returns (ProposalState) { 244 | require(proposalCount >= proposalId && proposalId > 0, "GovernorAlpha::state: invalid proposal id"); 245 | Proposal storage proposal = proposals[proposalId]; 246 | if (proposal.canceled) { 247 | return ProposalState.Canceled; 248 | } else if (block.number <= proposal.startBlock) { 249 | return ProposalState.Pending; 250 | } else if (block.number <= proposal.endBlock) { 251 | return ProposalState.Active; 252 | } else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes()) { 253 | return ProposalState.Defeated; 254 | } else if (proposal.eta == 0) { 255 | return ProposalState.Succeeded; 256 | } else if (proposal.executed) { 257 | return ProposalState.Executed; 258 | } else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) { 259 | return ProposalState.Expired; 260 | } else { 261 | return ProposalState.Queued; 262 | } 263 | } 264 | 265 | function castVote(uint proposalId, bool support) public { 266 | return _castVote(msg.sender, proposalId, support); 267 | } 268 | 269 | function castVoteBySig(uint proposalId, bool support, uint8 v, bytes32 r, bytes32 s) public { 270 | bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); 271 | bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support)); 272 | bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); 273 | address signatory = ecrecover(digest, v, r, s); 274 | require(signatory != address(0), "GovernorAlpha::castVoteBySig: invalid signature"); 275 | return _castVote(signatory, proposalId, support); 276 | } 277 | 278 | function _castVote(address voter, uint proposalId, bool support) internal { 279 | require(state(proposalId) == ProposalState.Active, "GovernorAlpha::_castVote: voting is closed"); 280 | Proposal storage proposal = proposals[proposalId]; 281 | Receipt storage receipt = proposal.receipts[voter]; 282 | require(receipt.hasVoted == false, "GovernorAlpha::_castVote: voter already voted"); 283 | uint256 votes = encore.getPriorVotes(voter, proposal.startBlock); 284 | 285 | if (support) { 286 | proposal.forVotes = add256(proposal.forVotes, votes); 287 | } else { 288 | proposal.againstVotes = add256(proposal.againstVotes, votes); 289 | } 290 | 291 | receipt.hasVoted = true; 292 | receipt.support = support; 293 | receipt.votes = votes; 294 | 295 | emit VoteCast(voter, proposalId, support, votes); 296 | } 297 | 298 | function __acceptAdmin() public { 299 | require(msg.sender == guardian, "GovernorAlpha::__acceptAdmin: sender must be gov guardian"); 300 | timelock.acceptAdmin(); 301 | } 302 | 303 | function __abdicate() public { 304 | require(msg.sender == guardian, "GovernorAlpha::__abdicate: sender must be gov guardian"); 305 | guardian = address(0); 306 | } 307 | 308 | function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public { 309 | require(msg.sender == guardian, "GovernorAlpha::__queueSetTimelockPendingAdmin: sender must be gov guardian"); 310 | timelock.queueTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta); 311 | } 312 | 313 | function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public { 314 | require(msg.sender == guardian, "GovernorAlpha::__executeSetTimelockPendingAdmin: sender must be gov guardian"); 315 | timelock.executeTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta); 316 | } 317 | 318 | function add256(uint256 a, uint256 b) internal pure returns (uint) { 319 | uint c = a + b; 320 | require(c >= a, "addition overflow"); 321 | return c; 322 | } 323 | 324 | function sub256(uint256 a, uint256 b) internal pure returns (uint) { 325 | require(b <= a, "subtraction underflow"); 326 | return a - b; 327 | } 328 | 329 | function getChainId() internal pure returns (uint) { 330 | uint chainId; 331 | assembly { chainId := chainid() } 332 | return chainId; 333 | } 334 | } 335 | 336 | interface TimelockInterface { 337 | function delay() external view returns (uint); 338 | function GRACE_PERIOD() external view returns (uint); 339 | function acceptAdmin() external; 340 | function queuedTransactions(bytes32 hash) external view returns (bool); 341 | function queueTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external returns (bytes32); 342 | function cancelTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external; 343 | function executeTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external payable returns (bytes memory); 344 | } 345 | -------------------------------------------------------------------------------- /IEncoreVault.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.6.0; 2 | 3 | 4 | interface IEncoreVault { 5 | function addPendingRewards(uint _amount) external; 6 | function stakedLPTokens(uint256 _pid, address _user) external view returns (uint256); 7 | } 8 | -------------------------------------------------------------------------------- /IFeeApprover.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.6.0; 4 | 5 | 6 | interface IFeeApprover { 7 | 8 | function check( 9 | address sender, 10 | address recipient, 11 | uint256 amount 12 | ) external returns (bool); 13 | 14 | function setFeeMultiplier(uint _feeMultiplier) external; 15 | function feePercentX100() external view returns (uint); 16 | 17 | function setTokenUniswapPair(address _tokenUniswapPair) external; 18 | 19 | function setEncoreTokenAddress(address _encoreTokenAddress) external; 20 | function sync() external; 21 | function calculateAmountsAfterFee( 22 | address sender, 23 | address recipient, 24 | uint256 amount 25 | ) external returns (uint256 transferToAmount, uint256 transferToFeeBearerAmount); 26 | 27 | function setPaused() external; 28 | 29 | 30 | } 31 | -------------------------------------------------------------------------------- /INBUNIERC20.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.6.0; 4 | 5 | /** 6 | * @dev Interface of the ERC20 standard as defined in the EIP. 7 | */ 8 | interface INBUNIERC20 { 9 | /** 10 | * @dev Returns the amount of tokens in existence. 11 | */ 12 | function totalSupply() external view returns (uint256); 13 | 14 | /** 15 | * @dev Returns the amount of tokens owned by `account`. 16 | */ 17 | function balanceOf(address account) external view returns (uint256); 18 | 19 | /** 20 | * @dev Moves `amount` tokens from the caller's account to `recipient`. 21 | * 22 | * Returns a boolean value indicating whether the operation succeeded. 23 | * 24 | * Emits a {Transfer} event. 25 | */ 26 | function transfer(address recipient, uint256 amount) external returns (bool); 27 | 28 | /** 29 | * @dev Returns the remaining number of tokens that `spender` will be 30 | * allowed to spend on behalf of `owner` through {transferFrom}. This is 31 | * zero by default. 32 | * 33 | * This value changes when {approve} or {transferFrom} are called. 34 | */ 35 | function allowance(address owner, address spender) external view returns (uint256); 36 | 37 | /** 38 | * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. 39 | * 40 | * Returns a boolean value indicating whether the operation succeeded. 41 | * 42 | * IMPORTANT: Beware that changing an allowance with this method brings the risk 43 | * that someone may use both the old and the new allowance by unfortunate 44 | * transaction ordering. One possible solution to mitigate this race 45 | * condition is to first reduce the spender's allowance to 0 and set the 46 | * desired value afterwards: 47 | * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 48 | * 49 | * Emits an {Approval} event. 50 | */ 51 | function approve(address spender, uint256 amount) external returns (bool); 52 | 53 | /** 54 | * @dev Moves `amount` tokens from `sender` to `recipient` using the 55 | * allowance mechanism. `amount` is then deducted from the caller's 56 | * allowance. 57 | * 58 | * Returns a boolean value indicating whether the operation succeeded. 59 | * 60 | * Emits a {Transfer} event. 61 | */ 62 | function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); 63 | 64 | /** 65 | * @dev Emitted when `value` tokens are moved from one account (`from`) to 66 | * another (`to`). 67 | * 68 | * Note that `value` may be zero. 69 | */ 70 | event Transfer(address indexed from, address indexed to, uint256 value); 71 | 72 | /** 73 | * @dev Emitted when the allowance of a `spender` for an `owner` is set by 74 | * a call to {approve}. `value` is the new allowance. 75 | */ 76 | event Approval(address indexed owner, address indexed spender, uint256 value); 77 | 78 | 79 | event Log(string log); 80 | 81 | } 82 | -------------------------------------------------------------------------------- /KOVAN.md: -------------------------------------------------------------------------------- 1 | ENCORE Address: 0xAF6dEc8C491EeDF3C30399a02f91a60730A7c545 2 | 3 | Fee Approver (proxy): 0x0c19068793b0F1fD846d91bB918C8459b0628d8A 4 | 5 | Staking Vault (proxy): 0x3e693e03C9A3414a8A2882017822A61E084Ef6d3 6 | 7 | Token Lock (ENCORE): 0xEF2BC86ADBa62562a2341D8CDE6BCb076d686291 8 | 9 | Token Lock (LP): 0xc17EdCb3fa2fEEb3646A25334Ce8b1EE8f3E172A 10 | 11 | Fee Splitter: 0x90E121b90A4687c299c7b618deaffEbE18c44133 12 | 13 | Proxy Admin: 0x065B9D2941Ddacb7a0C9Ef504f312887EE7d9723 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /LP.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: None 2 | 3 | pragma solidity ^0.6.12; 4 | 5 | import "@openzeppelin/contracts/GSN/Context.sol"; 6 | import "@openzeppelin/contracts/math/SafeMath.sol"; 7 | import "@openzeppelin/contracts/utils/Address.sol"; 8 | import "./uniswapv2/interfaces/IUniswapV2Factory.sol"; // interface factorys 9 | import "./uniswapv2/interfaces/IUniswapV2Router02.sol"; // interface factorys 10 | import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; 11 | import "@openzeppelin/contracts/access/Ownable.sol"; 12 | import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; 13 | 14 | contract LPEvent is Context, Ownable { 15 | 16 | address internal _encoreAddress; 17 | address[] internal _path; 18 | 19 | constructor(address _token ,address _encore) public { 20 | _encoreAddress = _encore; 21 | initialSetup(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, _token); 22 | IUniswapV2Router02 router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); 23 | _path.push(address(_encoreAddress));_path.push(router.WETH());_path.push(address(tokenAddress)); 24 | } 25 | using SafeMath for uint256; 26 | using Address for address; 27 | using SafeMath for uint; 28 | 29 | IUniswapV2Router02 public uniswapRouterV2; 30 | IUniswapV2Factory public uniswapFactory; 31 | 32 | address public tokenUniswapPair; 33 | uint256 public contractStartTimestamp; 34 | uint256 public totalENCORE; 35 | mapping (address => uint) public contributed; 36 | address public tokenAddress; 37 | 38 | event LPTokenClaimed(address dst, uint value); 39 | event LiquidityAddition(address indexed dst, uint value); 40 | 41 | function initialSetup(address router, address factory, address _token) internal { 42 | contractStartTimestamp = block.timestamp; 43 | uniswapRouterV2 = IUniswapV2Router02(router != address(0) ? router : 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); 44 | uniswapFactory = IUniswapV2Factory(factory != address(0) ? factory : 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); 45 | createUniswapPairMainnet(_token, _encoreAddress); 46 | tokenAddress = _token; 47 | } 48 | 49 | function createUniswapPairMainnet(address _token, address _encore) public returns (address) { 50 | require(tokenUniswapPair == address(0), "Token: pool already created"); 51 | // tokenUniswapPair = uniswapFactory.createPair( 52 | // address(_encore), 53 | // address(_token) 54 | // ); 55 | tokenUniswapPair = address(0x64F2d5E35742858Df71e04385052BD7423623392); 56 | return tokenUniswapPair; 57 | } 58 | 59 | function getSecondsLeftInLiquidityGenerationEvent() public view returns (uint256) { 60 | require(liquidityGenerationOngoing(), "Event over"); 61 | return contractStartTimestamp.add(3 days).sub(block.timestamp); 62 | } 63 | 64 | function liquidityGenerationOngoing() public view returns (bool) { 65 | return contractStartTimestamp.add(3 days) > block.timestamp; 66 | } 67 | 68 | function emergencyDrain24hAfterLiquidityGenerationEventIsDone() public onlyOwner { 69 | require(contractStartTimestamp.add(4 days) < block.timestamp, "Liquidity generation grace period still ongoing"); // About 24h after liquidity generation happens 70 | IERC20 encore = IERC20(_encoreAddress); 71 | IERC20 token = IERC20(tokenAddress); 72 | encore.transfer(msg.sender, encore.balanceOf(address(this))); 73 | token.transfer(msg.sender, encore.balanceOf(address(this))); 74 | } 75 | 76 | function deposit(uint256 _amountENCORE, bool agreesToTermsOutlinedInLiquidityGenerationParticipationAgreement) public { 77 | require(liquidityGenerationOngoing(), "Liquidity Generation Event over"); 78 | require(agreesToTermsOutlinedInLiquidityGenerationParticipationAgreement, "No agreement provided"); 79 | IERC20 encore = IERC20(_encoreAddress); 80 | IERC20 token = IERC20(tokenAddress); 81 | require(encore.balanceOf(address(this)) < 1000e18, "Cap reached"); 82 | require(encore.balanceOf(address(this)).add(_amountENCORE) <= 1000e18, "Deposit exceeds cap"); 83 | encore.transferFrom(address(msg.sender), address(this), _amountENCORE); 84 | token.transferFrom(address(msg.sender), address(this), _amountENCORE.mul(50)); 85 | contributed[msg.sender] += _amountENCORE; 86 | totalENCORE.add(_amountENCORE); 87 | emit LiquidityAddition(msg.sender, _amountENCORE); 88 | } 89 | 90 | bool public LPGenerationCompleted; 91 | uint256 public totalLPTokensMinted; 92 | uint256 public totalContributed; 93 | uint256 public LPperUnit; 94 | function addLiquidityToUniswapENCORExTOKENPair() public { 95 | require(LPGenerationCompleted == false, "Liquidity generation already finished"); 96 | IERC20 token = IERC20(tokenAddress); 97 | IERC20 encore = IERC20(_encoreAddress); 98 | if(liquidityGenerationOngoing()) { 99 | require(encore.balanceOf(address(this)) >= 1000e18, "LPE: Event not over, cap not reached"); 100 | } 101 | totalContributed = encore.balanceOf(address(this)); 102 | IUniswapV2Pair pair = IUniswapV2Pair(tokenUniswapPair); 103 | encore.transfer(address(pair), encore.balanceOf(address(this))); 104 | token.transfer(address(pair), token.balanceOf(address(this))); 105 | pair.mint(address(this)); 106 | totalLPTokensMinted = pair.balanceOf(address(this)); 107 | require(totalLPTokensMinted != 0 , "LP creation failed"); 108 | LPperUnit = totalLPTokensMinted.mul(1e18).div(totalContributed); // 1e18x for change 109 | require(LPperUnit != 0 , "LP creation failed"); 110 | LPGenerationCompleted = true; 111 | 112 | } 113 | 114 | function claimLPTokens() public { 115 | require(LPGenerationCompleted, "Event not over yet"); 116 | require(contributed[msg.sender] > 0 , "Nothing to claim, move along"); 117 | IUniswapV2Pair pair = IUniswapV2Pair(tokenUniswapPair); 118 | uint256 amountLPToTransfer = contributed[msg.sender].mul(LPperUnit).div(1e18); 119 | pair.transfer(msg.sender, amountLPToTransfer); // stored as 1e18x value for change 120 | contributed[msg.sender] = 0; 121 | emit LPTokenClaimed(msg.sender, amountLPToTransfer); 122 | } 123 | } -------------------------------------------------------------------------------- /NBUNIERC20.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: MIT 2 | 3 | pragma solidity ^0.6.0; 4 | 5 | import "@openzeppelin/contracts/GSN/Context.sol"; 6 | import "./INBUNIERC20.sol"; 7 | import "@openzeppelin/contracts/math/SafeMath.sol"; 8 | import "@openzeppelin/contracts/utils/Address.sol"; 9 | import "./IFeeApprover.sol"; 10 | import "./IEncoreVault.sol"; 11 | import "@nomiclabs/buidler/console.sol"; 12 | 13 | import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // for WETH 14 | import "./uniswapv2/interfaces/IUniswapV2Factory.sol"; // interface factorys 15 | import "./uniswapv2/interfaces/IUniswapV2Router02.sol"; // interface factorys 16 | import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; 17 | import "./uniswapv2/interfaces/IWETH.sol"; 18 | 19 | import "@openzeppelin/contracts/access/Ownable.sol"; 20 | 21 | // import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; 22 | 23 | /** 24 | * @dev Implementation of the {IERC20} interface. 25 | * 26 | * This implementation is agnostic to the way tokens are created. This means 27 | * that a supply mechanism has to be added in a derived contract using {_mint}. 28 | * For a generic mechanism see {ERC20PresetMinterPauser}. 29 | * 30 | * TIP: For a detailed writeup see our guide 31 | * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How 32 | * to implement supply mechanisms]. 33 | * 34 | * We have followed general OpenZeppelin guidelines: functions revert instead 35 | * of returning `false` on failure. This behavior is nonetheless conventional 36 | * and does not conflict with the expectations of ERC20 applications. 37 | * 38 | * Additionally, an {Approval} event is emitted on calls to {transferFrom}. 39 | * This allows applications to reconstruct the allowance for all accounts just 40 | * by listening to said events. Other implementations of the EIP may not emit 41 | * these events, as it isn't required by the specification. 42 | * 43 | * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} 44 | * functions have been added to mitigate the well-known issues around setting 45 | * allowances. See {IERC20-approve}. 46 | */ 47 | contract NBUNIERC20 is Context, INBUNIERC20, Ownable { 48 | using SafeMath for uint256; 49 | using Address for address; 50 | 51 | mapping(address => uint256) private _balances; 52 | 53 | mapping(address => mapping(address => uint256)) private _allowances; 54 | 55 | event LiquidityAddition(address indexed dst, uint value); 56 | event LPTokenClaimed(address dst, uint value); 57 | 58 | uint256 private _totalSupply; 59 | 60 | string private _name; 61 | string private _symbol; 62 | uint8 private _decimals; 63 | uint256 public constant initialSupply = 10000e18; // 10k 64 | uint256 public contractStartTimestamp; 65 | 66 | 67 | /** 68 | * @dev Returns the name of the token. 69 | */ 70 | function name() public view returns (string memory) { 71 | return _name; 72 | } 73 | 74 | function initialSetup(address router, address factory) internal { 75 | _name = "EnCore"; 76 | _symbol = "ENCORE"; 77 | _decimals = 18; 78 | _mint(address(this), initialSupply); 79 | contractStartTimestamp = block.timestamp; 80 | uniswapRouterV2 = IUniswapV2Router02(router != address(0) ? router : 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // For testing 81 | uniswapFactory = IUniswapV2Factory(factory != address(0) ? factory : 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); // For testing 82 | createUniswapPairMainnet(); 83 | } 84 | 85 | /** 86 | * @dev Returns the symbol of the token, usually a shorter version of the 87 | * name. 88 | */ 89 | function symbol() public view returns (string memory) { 90 | return _symbol; 91 | } 92 | 93 | /** 94 | * @dev Returns the number of decimals used to get its user representation. 95 | * For example, if `decimals` equals `2`, a balance of `505` tokens should 96 | * be displayed to a user as `5,05` (`505 / 10 ** 2`). 97 | * 98 | * Tokens usually opt for a value of 18, imitating the relationship between 99 | * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is 100 | * called. 101 | * 102 | * NOTE: This information is only used for _display_ purposes: it in 103 | * no way affects any of the arithmetic of the contract, including 104 | * {IERC20-balanceOf} and {IERC20-transfer}. 105 | */ 106 | function decimals() public view returns (uint8) { 107 | return _decimals; 108 | } 109 | 110 | /** 111 | * @dev See {IERC20-totalSupply}. 112 | */ 113 | function totalSupply() public override view returns (uint256) { 114 | return _totalSupply; 115 | } 116 | 117 | /** 118 | * @dev See {IERC20-balanceOf}. 119 | */ 120 | // function balanceOf(address account) public override returns (uint256) { 121 | // return _balances[account]; 122 | // } 123 | function balanceOf(address _owner) public override view returns (uint256) { 124 | return _balances[_owner]; 125 | } 126 | 127 | 128 | IUniswapV2Router02 public uniswapRouterV2; 129 | IUniswapV2Factory public uniswapFactory; 130 | 131 | 132 | address public tokenUniswapPair; 133 | 134 | function createUniswapPairMainnet() public returns (address) { 135 | require(tokenUniswapPair == address(0), "Token: pool already created"); 136 | tokenUniswapPair = uniswapFactory.createPair( 137 | address(uniswapRouterV2.WETH()), 138 | address(this) 139 | ); 140 | return tokenUniswapPair; 141 | } 142 | 143 | 144 | //// Liquidity generation logic 145 | /// Steps - All tokens tat will ever exist go to this contract 146 | /// This contract accepts ETH as payable 147 | /// ETH is mapped to people 148 | /// When liquidity generationevent is over veryone can call 149 | /// the mint LP function 150 | // which will put all the ETH and tokens inside the uniswap contract 151 | /// without any involvement 152 | /// This LP will go into this contract 153 | /// And will be able to proportionally be withdrawn baed on ETH put in 154 | /// A emergency drain function allows the contract owner to drain all ETH and tokens from this contract 155 | /// After the liquidity generation event happened. In case something goes wrong, to send ETH back 156 | 157 | 158 | string public liquidityGenerationParticipationAgreement = "I agree that the developers and affiliated parties of the EnCore team are not responsible for your funds"; 159 | 160 | function getSecondsLeftInLiquidityGenerationEvent() public view returns (uint256) { 161 | require(liquidityGenerationOngoing(), "Event over"); 162 | console.log("5 days since start is", contractStartTimestamp.add(5 days), "Time now is", block.timestamp); 163 | return contractStartTimestamp.add(5 days).sub(block.timestamp); 164 | } 165 | 166 | function liquidityGenerationOngoing() public view returns (bool) { 167 | console.log("5 days since start is", contractStartTimestamp.add(5 days), "Time now is", block.timestamp); 168 | console.log("liquidity generation ongoing", contractStartTimestamp.add(5 days) < block.timestamp); 169 | return contractStartTimestamp.add(5 minutes) > block.timestamp; 170 | } 171 | 172 | // Emergency drain in case of a bug 173 | // Adds all funds to owner to refund people 174 | // Designed to be as simple as possible 175 | function emergencyDrain24hAfterLiquidityGenerationEventIsDone() public onlyOwner { 176 | require(contractStartTimestamp.add(6 days) < block.timestamp, "Liquidity generation grace period still ongoing"); // About 24h after liquidity generation happens 177 | (bool success, ) = msg.sender.call.value(address(this).balance)(""); 178 | require(success, "Transfer failed."); 179 | _balances[msg.sender] = _balances[address(this)]; 180 | _balances[address(this)] = 0; 181 | } 182 | 183 | uint256 public totalLPTokensMinted; 184 | uint256 public totalETHContributed; 185 | uint256 public LPperETHUnit; 186 | 187 | 188 | bool public LPGenerationCompleted; 189 | // Sends all avaibile balances and mints LP tokens 190 | // Possible ways this could break addressed 191 | // 1) Multiple calls and resetting amounts - addressed with boolean 192 | // 2) Failed WETH wrapping/unwrapping addressed with checks 193 | // 3) Failure to create LP tokens, addressed with checks 194 | // 4) Unacceptable division errors . Addressed with multiplications by 1e18 195 | // 5) Pair not set - impossible since its set in constructor 196 | function addLiquidityToUniswapENCORExWETHPair() public { 197 | require(liquidityGenerationOngoing() == false, "Liquidity generation onging"); 198 | require(LPGenerationCompleted == false, "Liquidity generation already finished"); 199 | totalETHContributed = address(this).balance; 200 | IUniswapV2Pair pair = IUniswapV2Pair(tokenUniswapPair); 201 | console.log("Balance of this", totalETHContributed / 1e18); 202 | //Wrap eth 203 | address WETH = uniswapRouterV2.WETH(); 204 | IWETH(WETH).deposit{value : totalETHContributed}(); 205 | require(address(this).balance == 0 , "Transfer Failed"); 206 | IWETH(WETH).transfer(address(pair),totalETHContributed); 207 | emit Transfer(address(this), address(pair), _balances[address(this)]); 208 | _balances[address(pair)] = _balances[address(this)]; 209 | _balances[address(this)] = 0; 210 | pair.mint(address(this)); 211 | totalLPTokensMinted = pair.balanceOf(address(this)); 212 | console.log("Total tokens minted",totalLPTokensMinted); 213 | require(totalLPTokensMinted != 0 , "LP creation failed"); 214 | LPperETHUnit = totalLPTokensMinted.mul(1e18).div(totalETHContributed); // 1e18x for change 215 | console.log("Total per LP token", LPperETHUnit); 216 | require(LPperETHUnit != 0 , "LP creation failed"); 217 | LPGenerationCompleted = true; 218 | 219 | } 220 | 221 | 222 | mapping (address => uint) public ethContributed; 223 | // Possible ways this could break addressed 224 | // 1) No ageement to terms - added require 225 | // 2) Adding liquidity after generaion is over - added require 226 | // 3) Overflow from uint - impossible there isnt that much ETH aviable 227 | // 4) Depositing 0 - not an issue it will just add 0 to tally 228 | function addLiquidity(bool agreesToTermsOutlinedInLiquidityGenerationParticipationAgreement) public payable { 229 | require(liquidityGenerationOngoing(), "Liquidity Generation Event over"); 230 | require(agreesToTermsOutlinedInLiquidityGenerationParticipationAgreement, "No agreement provided"); 231 | ethContributed[msg.sender] += msg.value; // Overflow protection from safemath is not neded here 232 | totalETHContributed = totalETHContributed.add(msg.value); // for front end display during LGE. This resets with definietly correct balance while calling pair. 233 | emit LiquidityAddition(msg.sender, msg.value); 234 | } 235 | 236 | // Possible ways this could break addressed 237 | // 1) Accessing before event is over and resetting eth contributed -- added require 238 | // 2) No uniswap pair - impossible at this moment because of the LPGenerationCompleted bool 239 | // 3) LP per unit is 0 - impossible checked at generation function 240 | function claimLPTokens() public { 241 | require(LPGenerationCompleted, "Event not over yet"); 242 | require(ethContributed[msg.sender] > 0 , "Nothing to claim, move along"); 243 | IUniswapV2Pair pair = IUniswapV2Pair(tokenUniswapPair); 244 | uint256 amountLPToTransfer = ethContributed[msg.sender].mul(LPperETHUnit).div(1e18); 245 | pair.transfer(msg.sender, amountLPToTransfer); // stored as 1e18x value for change 246 | ethContributed[msg.sender] = 0; 247 | emit LPTokenClaimed(msg.sender, amountLPToTransfer); 248 | } 249 | 250 | 251 | /** 252 | * @dev See {IERC20-transfer}. 253 | * 254 | * Requirements: 255 | * 256 | * - `recipient` cannot be the zero address. 257 | * - the caller must have a balance of at least `amount`. 258 | */ 259 | function transfer(address recipient, uint256 amount) public virtual override returns (bool) 260 | { 261 | _transfer(_msgSender(), recipient, amount); 262 | return true; 263 | } 264 | 265 | /** 266 | * @dev See {IERC20-allowance}. 267 | */ 268 | function allowance(address owner, address spender) 269 | public 270 | virtual 271 | override 272 | view 273 | returns (uint256) 274 | { 275 | return _allowances[owner][spender]; 276 | } 277 | 278 | /** 279 | * @dev See {IERC20-approve}. 280 | * 281 | * Requirements: 282 | * 283 | * - `spender` cannot be the zero address. 284 | */ 285 | function approve(address spender, uint256 amount) 286 | public 287 | virtual 288 | override 289 | returns (bool) 290 | { 291 | _approve(_msgSender(), spender, amount); 292 | return true; 293 | } 294 | 295 | /** 296 | * @dev See {IERC20-transferFrom}. 297 | * 298 | * Emits an {Approval} event indicating the updated allowance. This is not 299 | * required by the EIP. See the note at the beginning of {ERC20}; 300 | * 301 | * Requirements: 302 | * - `sender` and `recipient` cannot be the zero address. 303 | * - `sender` must have a balance of at least `amount`. 304 | * - the caller must have allowance for ``sender``'s tokens of at least 305 | * `amount`. 306 | */ 307 | function transferFrom( 308 | address sender, 309 | address recipient, 310 | uint256 amount 311 | ) public virtual override returns (bool) { 312 | _transfer(sender, recipient, amount); 313 | _approve( 314 | sender, 315 | _msgSender(), 316 | _allowances[sender][_msgSender()].sub( 317 | amount, 318 | "ERC20: transfer amount exceeds allowance" 319 | ) 320 | ); 321 | return true; 322 | } 323 | 324 | /** 325 | * @dev Atomically increases the allowance granted to `spender` by the caller. 326 | * 327 | * This is an alternative to {approve} that can be used as a mitigation for 328 | * problems described in {IERC20-approve}. 329 | * 330 | * Emits an {Approval} event indicating the updated allowance. 331 | * 332 | * Requirements: 333 | * 334 | * - `spender` cannot be the zero address. 335 | */ 336 | function increaseAllowance(address spender, uint256 addedValue) 337 | public 338 | virtual 339 | returns (bool) 340 | { 341 | _approve( 342 | _msgSender(), 343 | spender, 344 | _allowances[_msgSender()][spender].add(addedValue) 345 | ); 346 | return true; 347 | } 348 | 349 | /** 350 | * @dev Atomically decreases the allowance granted to `spender` by the caller. 351 | * 352 | * This is an alternative to {approve} that can be used as a mitigation for 353 | * problems described in {IERC20-approve}. 354 | * 355 | * Emits an {Approval} event indicating the updated allowance. 356 | * 357 | * Requirements: 358 | * 359 | * - `spender` cannot be the zero address. 360 | * - `spender` must have allowance for the caller of at least 361 | * `subtractedValue`. 362 | */ 363 | function decreaseAllowance(address spender, uint256 subtractedValue) 364 | public 365 | virtual 366 | returns (bool) 367 | { 368 | _approve( 369 | _msgSender(), 370 | spender, 371 | _allowances[_msgSender()][spender].sub( 372 | subtractedValue, 373 | "ERC20: decreased allowance below zero" 374 | ) 375 | ); 376 | return true; 377 | } 378 | 379 | function setShouldTransferChecker(address _transferCheckerAddress) 380 | public 381 | onlyOwner 382 | { 383 | transferCheckerAddress = _transferCheckerAddress; 384 | } 385 | 386 | address public transferCheckerAddress; 387 | 388 | function setFeeDistributor(address _feeDistributor) 389 | public 390 | onlyOwner 391 | { 392 | feeDistributor = _feeDistributor; 393 | } 394 | 395 | address public feeDistributor; 396 | 397 | 398 | 399 | 400 | /** 401 | * @dev Moves tokens `amount` from `sender` to `recipient`. 402 | * 403 | * This is internal function is equivalent to {transfer}, and can be used to 404 | * e.g. implement automatic token fees, slashing mechanisms, etc. 405 | * 406 | * Emits a {Transfer} event. 407 | * 408 | * Requirements: 409 | * 410 | * - `sender` cannot be the zero address. 411 | * - `recipient` cannot be the zero address. 412 | * - `sender` must have a balance of at least `amount`. 413 | */ 414 | function _transfer( 415 | address sender, 416 | address recipient, 417 | uint256 amount 418 | ) internal virtual { 419 | require(sender != address(0), "ERC20: transfer from the zero address"); 420 | require(recipient != address(0), "ERC20: transfer to the zero address"); 421 | 422 | 423 | 424 | _beforeTokenTransfer(sender, recipient, amount); 425 | 426 | _balances[sender] = _balances[sender].sub( 427 | amount, 428 | "ERC20: transfer amount exceeds balance" 429 | ); 430 | 431 | (uint256 transferToAmount, uint256 transferToFeeDistributorAmount) = IFeeApprover(transferCheckerAddress).calculateAmountsAfterFee(sender, recipient, amount); 432 | 433 | 434 | // Addressing a broken checker contract 435 | require(transferToAmount.add(transferToFeeDistributorAmount) == amount, "Math broke, does gravity still work?"); 436 | 437 | _balances[recipient] = _balances[recipient].add(transferToAmount); 438 | emit Transfer(sender, recipient, transferToAmount); 439 | 440 | if(transferToFeeDistributorAmount > 0 && feeDistributor != address(0)){ 441 | _balances[feeDistributor] = _balances[feeDistributor].add(transferToFeeDistributorAmount); 442 | emit Transfer(sender, feeDistributor, transferToFeeDistributorAmount); 443 | if(feeDistributor != address(0)){ 444 | IEncoreVault(feeDistributor).addPendingRewards(transferToFeeDistributorAmount); 445 | } 446 | } 447 | } 448 | 449 | /** @dev Creates `amount` tokens and assigns them to `account`, increasing 450 | * the total supply. 451 | * 452 | * Emits a {Transfer} event with `from` set to the zero address. 453 | * 454 | * Requirements 455 | * 456 | * - `to` cannot be the zero address. 457 | */ 458 | 459 | function _mint(address account, uint256 amount) internal virtual { 460 | require(account != address(0), "ERC20: mint to the zero address"); 461 | 462 | _beforeTokenTransfer(address(0), account, amount); 463 | 464 | _totalSupply = _totalSupply.add(amount); 465 | _balances[account] = _balances[account].add(amount); 466 | emit Transfer(address(0), account, amount); 467 | } 468 | 469 | /** 470 | * @dev Destroys `amount` tokens from `account`, reducing the 471 | * total supply. 472 | * 473 | * Emits a {Transfer} event with `to` set to the zero address. 474 | * 475 | * Requirements 476 | * 477 | * - `account` cannot be the zero address. 478 | * - `account` must have at least `amount` tokens. 479 | */ 480 | function _burn(address account, uint256 amount) internal virtual { 481 | require(account != address(0), "ERC20: burn from the zero address"); 482 | 483 | _beforeTokenTransfer(account, address(0), amount); 484 | 485 | _balances[account] = _balances[account].sub( 486 | amount, 487 | "ERC20: burn amount exceeds balance" 488 | ); 489 | _totalSupply = _totalSupply.sub(amount); 490 | emit Transfer(account, address(0), amount); 491 | } 492 | 493 | /** 494 | * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. 495 | * 496 | * This is internal function is equivalent to `approve`, and can be used to 497 | * e.g. set automatic allowances for certain subsystems, etc. 498 | * 499 | * Emits an {Approval} event. 500 | * 501 | * Requirements: 502 | * 503 | * - `owner` cannot be the zero address. 504 | * - `spender` cannot be the zero address. 505 | */ 506 | function _approve( 507 | address owner, 508 | address spender, 509 | uint256 amount 510 | ) internal virtual { 511 | require(owner != address(0), "ERC20: approve from the zero address"); 512 | require(spender != address(0), "ERC20: approve to the zero address"); 513 | 514 | _allowances[owner][spender] = amount; 515 | emit Approval(owner, spender, amount); 516 | } 517 | 518 | /** 519 | * @dev Sets {decimals} to a value other than the default one of 18. 520 | * 521 | * WARNING: This function should only be called from the constructor. Most 522 | * applications that interact with token contracts will not expect 523 | * {decimals} to ever change, and may work incorrectly if it does. 524 | */ 525 | function _setupDecimals(uint8 decimals_) internal { 526 | _decimals = decimals_; 527 | } 528 | 529 | /** 530 | * @dev Hook that is called before any transfer of tokens. This includes 531 | * minting and burning. 532 | * 533 | * Calling conditions: 534 | * 535 | * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens 536 | * will be to transferred to `to`. 537 | * - when `from` is zero, `amount` tokens will be minted for `to`. 538 | * - when `to` is zero, `amount` of ``from``'s tokens will be burned. 539 | * - `from` and `to` are never both zero. 540 | * 541 | * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. 542 | */ 543 | function _beforeTokenTransfer( 544 | address from, 545 | address to, 546 | uint256 amount 547 | ) internal virtual {} 548 | } 549 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # EnCore Vault v1 2 | A decentralized yield farming protocol with limited supply (Inspired by CORE (cvault.finance)) 3 | 4 | EnCore vault is a decentralized protocol built on Ethereum that allows holders of certain coins to be rewarded with $ENCORE. Unlike other DeFi liquidity generation protocols, EnCore has a finite limit, keeping the value of the coin. (10k $ENCORE limit) 5 | 6 | 7 | # Contracts 8 | ENCORE Token: 0xe0E4839E0c7b2773c58764F9Ec3B9622d01A0428 9 | 10 | ENCORE/LINK LPE: 0xc6B04AE5cAD09a117Ba80293a6d958D74505244b (EOL) 11 | 12 | Staking Vault (Proxy): 0xdeF7BdF8eCb450c1D93C5dB7C8DBcE5894CCDaa9 13 | 14 | Fee Approver (Proxy): 0xF3c3ff0ea59d15e82b9620Ed7406fa3f6A261f98 15 | 16 | Staking Vault (Implementation): 0xB1166FFE5dCe7a0ca54AEd88713AF2a0d5DeCE68, 0x4E84668Ff607eF8BE9579d67dca4dc06002eb649 17 | 18 | Fee Approver (Implementation): 0x4E5FB14E7E7cC254aEeC9DB6f737682032E9660D 19 | 20 | Proxy Admin: 0x1964784ba40c9fD5EED1070c1C38cd5D1d5F9f55 21 | 22 | Timelock Holder: 0x2a997EaD7478885a66e6961ac0837800A07492Fc 23 | 24 | Timelock Vault: 0xC2Cb86437355f36d42Fb8D979ab28b9816ac0545 25 | 26 | # Utility Contracts 27 | Fee Splitter: 0xC8eCBE1CF67Edba355a4B5EEA7b1E1414239e205 28 | 29 | Token Lock (burn): 0x93C9170f40D2Ec954544bBfFAFbf7f2aaE8A7061 30 | 31 | # UniSwap 32 | 33 | ETH/ENCORE PAIR: 0x2e0721E6C951710725997928DcAAa05DaaFa031B 34 | 35 | LINK/ENCORE PAIR: 0x64f2d5e35742858df71e04385052bd7423623392 (EOL) 36 | -------------------------------------------------------------------------------- /uniswapv2/LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /uniswapv2/README.md: -------------------------------------------------------------------------------- 1 | # Uniswap V2 Area 2 | 3 | Code from [Uniswap V2](https://github.com/Uniswap/uniswap-v2-core/tree/27f6354bae6685612c182c3bc7577e61bc8717e3/contracts) with the following modifications. 4 | 5 | 1. Change contract version to 0.6.12 and do the necessary patching. 6 | 2. Add `migrator` member in `UniswapV2Factory` which can be set by `feeToSetter`. 7 | 3. Allow `migrator` to specify the amount of `liquidity` during the first mint. Disallow first mint if migrator is set. 8 | 9 | To see all diffs: 10 | 11 | ``` 12 | $ git diff 4c4bf551417e3df09a25aa0dbb6941cccbbac11a . 13 | ``` -------------------------------------------------------------------------------- /uniswapv2/UniswapV2ERC20.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.6.12; 2 | 3 | import './libraries/SafeMath.sol'; 4 | import "@nomiclabs/buidler/console.sol"; 5 | 6 | contract UniswapV2ERC20 { 7 | using SafeMathUniswap for uint; 8 | 9 | string public constant name = ' LP Token'; 10 | string public constant symbol = 'LP'; 11 | uint8 public constant decimals = 18; 12 | uint public totalSupply; 13 | mapping(address => uint) public balanceOf; 14 | mapping(address => mapping(address => uint)) public allowance; 15 | 16 | bytes32 public DOMAIN_SEPARATOR; 17 | // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); 18 | bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; 19 | mapping(address => uint) public nonces; 20 | 21 | event Approval(address indexed owner, address indexed spender, uint value); 22 | event Transfer(address indexed from, address indexed to, uint value); 23 | 24 | constructor() public { 25 | uint chainId; 26 | assembly { 27 | chainId := chainid() 28 | } 29 | DOMAIN_SEPARATOR = keccak256( 30 | abi.encode( 31 | keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), 32 | keccak256(bytes(name)), 33 | keccak256(bytes('1')), 34 | chainId, 35 | address(this) 36 | ) 37 | ); 38 | } 39 | 40 | function _mint(address to, uint value) internal { 41 | totalSupply = totalSupply.add(value); 42 | balanceOf[to] = balanceOf[to].add(value); 43 | emit Transfer(address(0), to, value); 44 | } 45 | 46 | function _burn(address from, uint value) internal { 47 | console.log("Addusting total supply of LP"); 48 | balanceOf[from] = balanceOf[from].sub(value); 49 | totalSupply = totalSupply.sub(value); 50 | emit Transfer(from, address(0), value); 51 | } 52 | 53 | function _approve(address owner, address spender, uint value) private { 54 | allowance[owner][spender] = value; 55 | emit Approval(owner, spender, value); 56 | } 57 | 58 | function _transfer(address from, address to, uint value) private { 59 | balanceOf[from] = balanceOf[from].sub(value); 60 | balanceOf[to] = balanceOf[to].add(value); 61 | emit Transfer(from, to, value); 62 | } 63 | 64 | function approve(address spender, uint value) external returns (bool) { 65 | _approve(msg.sender, spender, value); 66 | return true; 67 | } 68 | 69 | function transfer(address to, uint value) external returns (bool) { 70 | _transfer(msg.sender, to, value); 71 | return true; 72 | } 73 | 74 | function transferFrom(address from, address to, uint value) external returns (bool) { 75 | if (allowance[from][msg.sender] != uint(-1)) { 76 | allowance[from][msg.sender] = allowance[from][msg.sender].sub(value); 77 | } 78 | _transfer(from, to, value); 79 | return true; 80 | } 81 | 82 | function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external { 83 | require(deadline >= block.timestamp, 'UniswapV2: EXPIRED'); 84 | bytes32 digest = keccak256( 85 | abi.encodePacked( 86 | '\x19\x01', 87 | DOMAIN_SEPARATOR, 88 | keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) 89 | ) 90 | ); 91 | address recoveredAddress = ecrecover(digest, v, r, s); 92 | require(recoveredAddress != address(0) && recoveredAddress == owner, 'UniswapV2: INVALID_SIGNATURE'); 93 | _approve(owner, spender, value); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /uniswapv2/UniswapV2Factory.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.6.12; 2 | 3 | import './interfaces/IUniswapV2Factory.sol'; 4 | import './UniswapV2Pair.sol'; 5 | 6 | contract UniswapV2Factory is IUniswapV2Factory { 7 | address public override feeTo; 8 | address public override feeToSetter; 9 | address public override migrator; 10 | 11 | mapping(address => mapping(address => address)) public override getPair; 12 | address[] public override allPairs; 13 | 14 | event PairCreated(address indexed token0, address indexed token1, address pair, uint); 15 | 16 | constructor(address _feeToSetter) public { 17 | feeToSetter = _feeToSetter; 18 | } 19 | 20 | function allPairsLength() external override view returns (uint) { 21 | return allPairs.length; 22 | } 23 | 24 | function pairCodeHash() external pure returns (bytes32) { 25 | return keccak256(type(UniswapV2Pair).creationCode); 26 | } 27 | 28 | function createPair(address tokenA, address tokenB) external override returns (address pair) { 29 | require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES'); 30 | (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); 31 | require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS'); 32 | require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient 33 | bytes memory bytecode = type(UniswapV2Pair).creationCode; 34 | bytes32 salt = keccak256(abi.encodePacked(token0, token1)); 35 | assembly { 36 | pair := create2(0, add(bytecode, 32), mload(bytecode), salt) 37 | } 38 | UniswapV2Pair(pair).initialize(token0, token1); 39 | getPair[token0][token1] = pair; 40 | getPair[token1][token0] = pair; // populate mapping in the reverse direction 41 | allPairs.push(pair); 42 | emit PairCreated(token0, token1, pair, allPairs.length); 43 | } 44 | 45 | function setFeeTo(address _feeTo) external override { 46 | require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN'); 47 | feeTo = _feeTo; 48 | } 49 | 50 | function setMigrator(address _migrator) external override { 51 | require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN'); 52 | migrator = _migrator; 53 | } 54 | 55 | function setFeeToSetter(address _feeToSetter) external override { 56 | require(msg.sender == feeToSetter, 'UniswapV2: FORBIDDEN'); 57 | feeToSetter = _feeToSetter; 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /uniswapv2/UniswapV2Pair.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.6.12; 2 | 3 | import './UniswapV2ERC20.sol'; 4 | import './libraries/Math.sol'; 5 | import './libraries/UQ112x112.sol'; 6 | import './interfaces/IERC20.sol'; 7 | import './interfaces/IUniswapV2Factory.sol'; 8 | import './interfaces/IUniswapV2Callee.sol'; 9 | import "@nomiclabs/buidler/console.sol"; 10 | 11 | 12 | interface IMigrator { 13 | // Return the desired amount of liquidity token that the migrator wants. 14 | function desiredLiquidity() external view returns (uint256); 15 | } 16 | 17 | contract UniswapV2Pair is UniswapV2ERC20 { 18 | using SafeMathUniswap for uint; 19 | using UQ112x112 for uint224; 20 | 21 | uint public constant MINIMUM_LIQUIDITY = 10**3; 22 | bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)'))); 23 | 24 | address public factory; 25 | address public token0; 26 | address public token1; 27 | 28 | uint112 private reserve0; // uses single storage slot, accessible via getReserves 29 | uint112 private reserve1; // uses single storage slot, accessible via getReserves 30 | uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves 31 | 32 | uint public price0CumulativeLast; 33 | uint public price1CumulativeLast; 34 | uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event 35 | 36 | uint private unlocked = 1; 37 | modifier lock() { 38 | require(unlocked == 1, 'UniswapV2: LOCKED'); 39 | unlocked = 0; 40 | _; 41 | unlocked = 1; 42 | } 43 | 44 | function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) { 45 | _reserve0 = reserve0; 46 | _reserve1 = reserve1; 47 | _blockTimestampLast = blockTimestampLast; 48 | } 49 | 50 | function _safeTransfer(address token, address to, uint value) private { 51 | (bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value)); 52 | require(success && (data.length == 0 || abi.decode(data, (bool))), 'UniswapV2: TRANSFER_FAILED'); 53 | } 54 | 55 | event Mint(address indexed sender, uint amount0, uint amount1); 56 | event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); 57 | event Swap( 58 | address indexed sender, 59 | uint amount0In, 60 | uint amount1In, 61 | uint amount0Out, 62 | uint amount1Out, 63 | address indexed to 64 | ); 65 | event Sync(uint112 reserve0, uint112 reserve1); 66 | 67 | constructor() public { 68 | factory = msg.sender; 69 | } 70 | 71 | // called once by the factory at time of deployment 72 | function initialize(address _token0, address _token1) external { 73 | require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check 74 | token0 = _token0; 75 | token1 = _token1; 76 | } 77 | 78 | // update reserves and, on the first call per block, price accumulators 79 | function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private { 80 | require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'UniswapV2: OVERFLOW'); 81 | uint32 blockTimestamp = uint32(block.timestamp % 2**32); 82 | uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired 83 | if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { 84 | // * never overflows, and + overflow is desired 85 | price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; 86 | price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed; 87 | } 88 | reserve0 = uint112(balance0); 89 | reserve1 = uint112(balance1); 90 | blockTimestampLast = blockTimestamp; 91 | emit Sync(reserve0, reserve1); 92 | } 93 | 94 | // if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k) 95 | function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) { 96 | address feeTo = IUniswapV2Factory(factory).feeTo(); 97 | feeOn = feeTo != address(0); 98 | uint _kLast = kLast; // gas savings 99 | if (feeOn) { 100 | if (_kLast != 0) { 101 | uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1)); 102 | uint rootKLast = Math.sqrt(_kLast); 103 | if (rootK > rootKLast) { 104 | uint numerator = totalSupply.mul(rootK.sub(rootKLast)); 105 | uint denominator = rootK.mul(5).add(rootKLast); 106 | uint liquidity = numerator / denominator; 107 | if (liquidity > 0) _mint(feeTo, liquidity); 108 | } 109 | } 110 | } else if (_kLast != 0) { 111 | kLast = 0; 112 | } 113 | } 114 | 115 | // this low-level function should be called from a contract which performs important safety checks 116 | function mint(address to) external lock returns (uint liquidity) { 117 | (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings 118 | uint balance0 = IERC20Uniswap(token0).balanceOf(address(this)); 119 | uint balance1 = IERC20Uniswap(token1).balanceOf(address(this)); 120 | uint amount0 = balance0.sub(_reserve0); 121 | uint amount1 = balance1.sub(_reserve1); 122 | 123 | bool feeOn = _mintFee(_reserve0, _reserve1); 124 | uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee 125 | if (_totalSupply == 0) { 126 | address migrator = IUniswapV2Factory(factory).migrator(); 127 | if (msg.sender == migrator) { 128 | liquidity = IMigrator(migrator).desiredLiquidity(); 129 | require(liquidity > 0 && liquidity != uint256(-1), "Bad desired liquidity"); 130 | } else { 131 | require(migrator == address(0), "Must not have migrator"); 132 | liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); 133 | _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens 134 | } 135 | } else { 136 | liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1); 137 | } 138 | require(liquidity > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_MINTED'); 139 | _mint(to, liquidity); 140 | 141 | _update(balance0, balance1, _reserve0, _reserve1); 142 | if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date 143 | emit Mint(msg.sender, amount0, amount1); 144 | } 145 | 146 | // this low-level function should be called from a contract which performs important safety checks 147 | function burn(address to) external lock returns (uint amount0, uint amount1) { 148 | (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings 149 | address _token0 = token0; // gas savings 150 | address _token1 = token1; // gas savings 151 | uint balance0 = IERC20Uniswap(_token0).balanceOf(address(this)); 152 | uint balance1 = IERC20Uniswap(_token1).balanceOf(address(this)); 153 | uint liquidity = balanceOf[address(this)]; 154 | 155 | bool feeOn = _mintFee(_reserve0, _reserve1); 156 | uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee 157 | amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution 158 | amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution 159 | require(amount0 > 0 && amount1 > 0, 'UniswapV2: INSUFFICIENT_LIQUIDITY_BURNED'); 160 | _burn(address(this), liquidity); 161 | _safeTransfer(_token0, to, amount0); 162 | _safeTransfer(_token1, to, amount1); 163 | 164 | balance0 = IERC20Uniswap(_token0).balanceOf(address(this)); 165 | balance1 = IERC20Uniswap(_token1).balanceOf(address(this)); 166 | 167 | _update(balance0, balance1, _reserve0, _reserve1); 168 | if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date 169 | emit Burn(msg.sender, amount0, amount1, to); 170 | } 171 | 172 | // this low-level function should be called from a contract which performs important safety checks 173 | function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock { 174 | require(amount0Out > 0 || amount1Out > 0, 'UniswapV2: INSUFFICIENT_OUTPUT_AMOUNT'); 175 | (uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings 176 | require(amount0Out < _reserve0 && amount1Out < _reserve1, 'UniswapV2: INSUFFICIENT_LIQUIDITY'); 177 | 178 | uint balance0; 179 | uint balance1; 180 | { // scope for _token{0,1}, avoids stack too deep errors 181 | address _token0 = token0; 182 | address _token1 = token1; 183 | require(to != _token0 && to != _token1, 'UniswapV2: INVALID_TO'); 184 | if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens 185 | if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens 186 | if (data.length > 0) IUniswapV2Callee(to).uniswapV2Call(msg.sender, amount0Out, amount1Out, data); 187 | balance0 = IERC20Uniswap(_token0).balanceOf(address(this)); 188 | balance1 = IERC20Uniswap(_token1).balanceOf(address(this)); 189 | } 190 | uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0; 191 | uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0; 192 | require(amount0In > 0 || amount1In > 0, 'UniswapV2: INSUFFICIENT_INPUT_AMOUNT'); 193 | { // scope for reserve{0,1}Adjusted, avoids stack too deep errors 194 | uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3)); 195 | uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3)); 196 | require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'UniswapV2: K'); 197 | } 198 | 199 | _update(balance0, balance1, _reserve0, _reserve1); 200 | emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to); 201 | } 202 | 203 | // force balances to match reserves 204 | function skim(address to) external lock { 205 | address _token0 = token0; // gas savings 206 | address _token1 = token1; // gas savings 207 | _safeTransfer(_token0, to, IERC20Uniswap(_token0).balanceOf(address(this)).sub(reserve0)); 208 | _safeTransfer(_token1, to, IERC20Uniswap(_token1).balanceOf(address(this)).sub(reserve1)); 209 | } 210 | 211 | // force reserves to match balances 212 | function sync() external lock { 213 | _update(IERC20Uniswap(token0).balanceOf(address(this)), IERC20Uniswap(token1).balanceOf(address(this)), reserve0, reserve1); 214 | } 215 | } 216 | -------------------------------------------------------------------------------- /uniswapv2/UniswapV2Router02.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.6.6; 2 | 3 | import './interfaces/IUniswapV2Router02.sol'; 4 | 5 | import './libraries/UniswapV2Library.sol'; 6 | import './libraries/SafeMath.sol'; 7 | import './interfaces/IERC20.sol'; 8 | import './interfaces/IWETH.sol'; 9 | import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol'; 10 | import '@uniswap/lib/contracts/libraries/TransferHelper.sol'; 11 | 12 | 13 | 14 | contract UniswapV2Router02 is IUniswapV2Router02 { 15 | using SafeMathUniswap for uint; 16 | 17 | address public immutable override factory; 18 | address public immutable override WETH; 19 | 20 | modifier ensure(uint deadline) { 21 | require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED'); 22 | _; 23 | } 24 | 25 | constructor(address _factory, address _WETH) public { 26 | factory = _factory; 27 | WETH = _WETH; 28 | } 29 | 30 | receive() external payable { 31 | assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract 32 | } 33 | 34 | // **** ADD LIQUIDITY **** 35 | function _addLiquidity( 36 | address tokenA, 37 | address tokenB, 38 | uint amountADesired, 39 | uint amountBDesired, 40 | uint amountAMin, 41 | uint amountBMin 42 | ) internal virtual returns (uint amountA, uint amountB) { 43 | // create the pair if it doesn't exist yet 44 | if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) { 45 | IUniswapV2Factory(factory).createPair(tokenA, tokenB); 46 | } 47 | (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB); 48 | if (reserveA == 0 && reserveB == 0) { 49 | (amountA, amountB) = (amountADesired, amountBDesired); 50 | } else { 51 | uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB); 52 | if (amountBOptimal <= amountBDesired) { 53 | require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT'); 54 | (amountA, amountB) = (amountADesired, amountBOptimal); 55 | } else { 56 | uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA); 57 | assert(amountAOptimal <= amountADesired); 58 | require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT'); 59 | (amountA, amountB) = (amountAOptimal, amountBDesired); 60 | } 61 | } 62 | } 63 | function addLiquidity( 64 | address tokenA, 65 | address tokenB, 66 | uint amountADesired, 67 | uint amountBDesired, 68 | uint amountAMin, 69 | uint amountBMin, 70 | address to, 71 | uint deadline 72 | ) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) { 73 | (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin); 74 | address pair = IUniswapV2Factory(factory).getPair(tokenA, tokenB); 75 | TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA); 76 | TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB); 77 | liquidity = IUniswapV2Pair(pair).mint(to); 78 | } 79 | function addLiquidityETH( 80 | address token, 81 | uint amountTokenDesired, 82 | uint amountTokenMin, 83 | uint amountETHMin, 84 | address to, 85 | uint deadline 86 | ) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) { 87 | (amountToken, amountETH) = _addLiquidity( 88 | token, 89 | WETH, 90 | amountTokenDesired, 91 | msg.value, 92 | amountTokenMin, 93 | amountETHMin 94 | ); 95 | address pair = IUniswapV2Factory(factory).getPair(token, WETH); 96 | TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken); 97 | IWETH(WETH).deposit{value: amountETH}(); 98 | assert(IWETH(WETH).transfer(pair, amountETH)); 99 | liquidity = IUniswapV2Pair(pair).mint(to); 100 | // refund dust eth, if any 101 | if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH); 102 | } 103 | 104 | // **** REMOVE LIQUIDITY **** 105 | function removeLiquidity( 106 | address tokenA, 107 | address tokenB, 108 | uint liquidity, 109 | uint amountAMin, 110 | uint amountBMin, 111 | address to, 112 | uint deadline 113 | ) public virtual override ensure(deadline) returns (uint amountA, uint amountB) { 114 | address pair = IUniswapV2Factory(factory).getPair(tokenA, tokenB); 115 | IUniswapV2Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair 116 | (uint amount0, uint amount1) = IUniswapV2Pair(pair).burn(to); 117 | (address token0,) = UniswapV2Library.sortTokens(tokenA, tokenB); 118 | (amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0); 119 | require(amountA >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT'); 120 | require(amountB >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT'); 121 | } 122 | function removeLiquidityETH( 123 | address token, 124 | uint liquidity, 125 | uint amountTokenMin, 126 | uint amountETHMin, 127 | address to, 128 | uint deadline 129 | ) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) { 130 | (amountToken, amountETH) = removeLiquidity( 131 | token, 132 | WETH, 133 | liquidity, 134 | amountTokenMin, 135 | amountETHMin, 136 | address(this), 137 | deadline 138 | ); 139 | TransferHelper.safeTransfer(token, to, amountToken); 140 | IWETH(WETH).withdraw(amountETH); 141 | TransferHelper.safeTransferETH(to, amountETH); 142 | } 143 | function removeLiquidityWithPermit( 144 | address tokenA, 145 | address tokenB, 146 | uint liquidity, 147 | uint amountAMin, 148 | uint amountBMin, 149 | address to, 150 | uint deadline, 151 | bool approveMax, uint8 v, bytes32 r, bytes32 s 152 | ) external virtual override returns (uint amountA, uint amountB) { 153 | address pair = IUniswapV2Factory(factory).getPair(tokenA, tokenB); 154 | uint value = approveMax ? uint(-1) : liquidity; 155 | IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); 156 | (amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline); 157 | } 158 | function removeLiquidityETHWithPermit( 159 | address token, 160 | uint liquidity, 161 | uint amountTokenMin, 162 | uint amountETHMin, 163 | address to, 164 | uint deadline, 165 | bool approveMax, uint8 v, bytes32 r, bytes32 s 166 | ) external virtual override returns (uint amountToken, uint amountETH) { 167 | address pair = IUniswapV2Factory(factory).getPair(token, WETH); 168 | uint value = approveMax ? uint(-1) : liquidity; 169 | IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); 170 | (amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline); 171 | } 172 | 173 | // **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) **** 174 | function removeLiquidityETHSupportingFeeOnTransferTokens( 175 | address token, 176 | uint liquidity, 177 | uint amountTokenMin, 178 | uint amountETHMin, 179 | address to, 180 | uint deadline 181 | ) public virtual override ensure(deadline) returns (uint amountETH) { 182 | (, amountETH) = removeLiquidity( 183 | token, 184 | WETH, 185 | liquidity, 186 | amountTokenMin, 187 | amountETHMin, 188 | address(this), 189 | deadline 190 | ); 191 | TransferHelper.safeTransfer(token, to, IERC20Uniswap(token).balanceOf(address(this))); 192 | IWETH(WETH).withdraw(amountETH); 193 | TransferHelper.safeTransferETH(to, amountETH); 194 | } 195 | function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( 196 | address token, 197 | uint liquidity, 198 | uint amountTokenMin, 199 | uint amountETHMin, 200 | address to, 201 | uint deadline, 202 | bool approveMax, uint8 v, bytes32 r, bytes32 s 203 | ) external virtual override returns (uint amountETH) { 204 | address pair = IUniswapV2Factory(factory).getPair(token, WETH); 205 | uint value = approveMax ? uint(-1) : liquidity; 206 | IUniswapV2Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s); 207 | amountETH = removeLiquidityETHSupportingFeeOnTransferTokens( 208 | token, liquidity, amountTokenMin, amountETHMin, to, deadline 209 | ); 210 | } 211 | 212 | // **** SWAP **** 213 | // requires the initial amount to have already been sent to the first pair 214 | function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual { 215 | for (uint i; i < path.length - 1; i++) { 216 | (address input, address output) = (path[i], path[i + 1]); 217 | (address token0,) = UniswapV2Library.sortTokens(input, output); 218 | uint amountOut = amounts[i + 1]; 219 | (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0)); 220 | address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to; 221 | IUniswapV2Pair(IUniswapV2Factory(factory).getPair(input, output)).swap( 222 | amount0Out, amount1Out, to, new bytes(0) 223 | ); 224 | } 225 | } 226 | function swapExactTokensForTokens( 227 | uint amountIn, 228 | uint amountOutMin, 229 | address[] calldata path, 230 | address to, 231 | uint deadline 232 | ) external virtual override ensure(deadline) returns (uint[] memory amounts) { 233 | amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path); 234 | require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); 235 | TransferHelper.safeTransferFrom( 236 | path[0], msg.sender, IUniswapV2Factory(factory).getPair(path[0], path[1]), amounts[0] 237 | ); 238 | _swap(amounts, path, to); 239 | } 240 | function swapTokensForExactTokens( 241 | uint amountOut, 242 | uint amountInMax, 243 | address[] calldata path, 244 | address to, 245 | uint deadline 246 | ) external virtual override ensure(deadline) returns (uint[] memory amounts) { 247 | amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path); 248 | require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'); 249 | TransferHelper.safeTransferFrom( 250 | path[0], msg.sender, IUniswapV2Factory(factory).getPair(path[0], path[1]), amounts[0] 251 | ); 252 | _swap(amounts, path, to); 253 | } 254 | function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) 255 | external 256 | virtual 257 | override 258 | payable 259 | ensure(deadline) 260 | returns (uint[] memory amounts) 261 | { 262 | require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); 263 | amounts = UniswapV2Library.getAmountsOut(factory, msg.value, path); 264 | require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); 265 | IWETH(WETH).deposit{value: amounts[0]}(); 266 | assert(IWETH(WETH).transfer(IUniswapV2Factory(factory).getPair(path[0], path[1]), amounts[0])); 267 | _swap(amounts, path, to); 268 | } 269 | function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) 270 | external 271 | virtual 272 | override 273 | ensure(deadline) 274 | returns (uint[] memory amounts) 275 | { 276 | require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH'); 277 | amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path); 278 | require(amounts[0] <= amountInMax, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'); 279 | TransferHelper.safeTransferFrom( 280 | path[0], msg.sender, IUniswapV2Factory(factory).getPair(path[0], path[1]), amounts[0] 281 | ); 282 | _swap(amounts, path, address(this)); 283 | IWETH(WETH).withdraw(amounts[amounts.length - 1]); 284 | TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); 285 | } 286 | function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) 287 | external 288 | virtual 289 | override 290 | ensure(deadline) 291 | returns (uint[] memory amounts) 292 | { 293 | require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH'); 294 | amounts = UniswapV2Library.getAmountsOut(factory, amountIn, path); 295 | require(amounts[amounts.length - 1] >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); 296 | TransferHelper.safeTransferFrom( 297 | path[0], msg.sender, IUniswapV2Factory(factory).getPair(path[0], path[1]), amounts[0] 298 | ); 299 | _swap(amounts, path, address(this)); 300 | IWETH(WETH).withdraw(amounts[amounts.length - 1]); 301 | TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]); 302 | } 303 | function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) 304 | external 305 | virtual 306 | override 307 | payable 308 | ensure(deadline) 309 | returns (uint[] memory amounts) 310 | { 311 | require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); 312 | amounts = UniswapV2Library.getAmountsIn(factory, amountOut, path); 313 | require(amounts[0] <= msg.value, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT'); 314 | IWETH(WETH).deposit{value: amounts[0]}(); 315 | assert(IWETH(WETH).transfer(IUniswapV2Factory(factory).getPair(path[0], path[1]), amounts[0])); 316 | _swap(amounts, path, to); 317 | // refund dust eth, if any 318 | if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]); 319 | } 320 | 321 | // **** SWAP (supporting fee-on-transfer tokens) **** 322 | // requires the initial amount to have already been sent to the first pair 323 | function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual { 324 | for (uint i; i < path.length - 1; i++) { 325 | (address input, address output) = (path[i], path[i + 1]); 326 | (address token0,) = UniswapV2Library.sortTokens(input, output); 327 | IUniswapV2Pair pair = IUniswapV2Pair(IUniswapV2Factory(factory).getPair(input, output)); 328 | uint amountInput; 329 | uint amountOutput; 330 | { // scope to avoid stack too deep errors 331 | (uint reserve0, uint reserve1,) = pair.getReserves(); 332 | (uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0); 333 | amountInput = IERC20Uniswap(input).balanceOf(address(pair)).sub(reserveInput); 334 | amountOutput = UniswapV2Library.getAmountOut(amountInput, reserveInput, reserveOutput); 335 | } 336 | (uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0)); 337 | address to = i < path.length - 2 ? UniswapV2Library.pairFor(factory, output, path[i + 2]) : _to; 338 | pair.swap(amount0Out, amount1Out, to, new bytes(0)); 339 | } 340 | } 341 | function swapExactTokensForTokensSupportingFeeOnTransferTokens( 342 | uint amountIn, 343 | uint amountOutMin, 344 | address[] calldata path, 345 | address to, 346 | uint deadline 347 | ) external virtual override ensure(deadline) { 348 | TransferHelper.safeTransferFrom( 349 | path[0], msg.sender, IUniswapV2Factory(factory).getPair(path[0], path[1]), amountIn 350 | ); 351 | uint balanceBefore = IERC20Uniswap(path[path.length - 1]).balanceOf(to); 352 | _swapSupportingFeeOnTransferTokens(path, to); 353 | require( 354 | IERC20Uniswap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 355 | 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT' 356 | ); 357 | } 358 | function swapExactETHForTokensSupportingFeeOnTransferTokens( 359 | uint amountOutMin, 360 | address[] calldata path, 361 | address to, 362 | uint deadline 363 | ) 364 | external 365 | virtual 366 | override 367 | payable 368 | ensure(deadline) 369 | { 370 | require(path[0] == WETH, 'UniswapV2Router: INVALID_PATH'); 371 | uint amountIn = msg.value; 372 | IWETH(WETH).deposit{value: amountIn}(); 373 | assert(IWETH(WETH).transfer(IUniswapV2Factory(factory).getPair(path[0], path[1]), amountIn)); 374 | uint balanceBefore = IERC20Uniswap(path[path.length - 1]).balanceOf(to); 375 | _swapSupportingFeeOnTransferTokens(path, to); 376 | require( 377 | IERC20Uniswap(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin, 378 | 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT' 379 | ); 380 | } 381 | function swapExactTokensForETHSupportingFeeOnTransferTokens( 382 | uint amountIn, 383 | uint amountOutMin, 384 | address[] calldata path, 385 | address to, 386 | uint deadline 387 | ) 388 | external 389 | virtual 390 | override 391 | ensure(deadline) 392 | { 393 | 394 | require(path[path.length - 1] == WETH, 'UniswapV2Router: INVALID_PATH'); 395 | TransferHelper.safeTransferFrom( 396 | path[0], msg.sender, IUniswapV2Factory(factory).getPair(path[0], path[1]), amountIn 397 | ); 398 | _swapSupportingFeeOnTransferTokens(path, address(this)); 399 | uint amountOut = IERC20Uniswap(WETH).balanceOf(address(this)); 400 | require(amountOut >= amountOutMin, 'UniswapV2Router: INSUFFICIENT_OUTPUT_AMOUNT'); 401 | IWETH(WETH).withdraw(amountOut); 402 | TransferHelper.safeTransferETH(to, amountOut); 403 | } 404 | 405 | // **** LIBRARY FUNCTIONS **** 406 | function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) { 407 | return UniswapV2Library.quote(amountA, reserveA, reserveB); 408 | } 409 | 410 | function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) 411 | public 412 | pure 413 | virtual 414 | override 415 | returns (uint amountOut) 416 | { 417 | return UniswapV2Library.getAmountOut(amountIn, reserveIn, reserveOut); 418 | } 419 | 420 | function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) 421 | public 422 | pure 423 | virtual 424 | override 425 | returns (uint amountIn) 426 | { 427 | return UniswapV2Library.getAmountIn(amountOut, reserveIn, reserveOut); 428 | } 429 | 430 | function getAmountsOut(uint amountIn, address[] memory path) 431 | public 432 | view 433 | virtual 434 | override 435 | returns (uint[] memory amounts) 436 | { 437 | return UniswapV2Library.getAmountsOut(factory, amountIn, path); 438 | } 439 | 440 | function getAmountsIn(uint amountOut, address[] memory path) 441 | public 442 | view 443 | virtual 444 | override 445 | returns (uint[] memory amounts) 446 | { 447 | return UniswapV2Library.getAmountsIn(factory, amountOut, path); 448 | } 449 | } -------------------------------------------------------------------------------- /uniswapv2/interfaces/IERC20.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.5.0; 2 | 3 | interface IERC20Uniswap { 4 | event Approval(address indexed owner, address indexed spender, uint value); 5 | event Transfer(address indexed from, address indexed to, uint value); 6 | 7 | function name() external view returns (string memory); 8 | function symbol() external view returns (string memory); 9 | function decimals() external view returns (uint8); 10 | function totalSupply() external view returns (uint); 11 | function balanceOf(address owner) external view returns (uint); 12 | function allowance(address owner, address spender) external view returns (uint); 13 | 14 | function approve(address spender, uint value) external returns (bool); 15 | function transfer(address to, uint value) external returns (bool); 16 | function transferFrom(address from, address to, uint value) external returns (bool); 17 | } 18 | -------------------------------------------------------------------------------- /uniswapv2/interfaces/IUniswapV2Callee.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.5.0; 2 | 3 | interface IUniswapV2Callee { 4 | function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external; 5 | } 6 | -------------------------------------------------------------------------------- /uniswapv2/interfaces/IUniswapV2ERC20.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.5.0; 2 | 3 | interface IUniswapV2ERC20 { 4 | event Approval(address indexed owner, address indexed spender, uint value); 5 | event Transfer(address indexed from, address indexed to, uint value); 6 | 7 | function name() external pure returns (string memory); 8 | function symbol() external pure returns (string memory); 9 | function decimals() external pure returns (uint8); 10 | function totalSupply() external view returns (uint); 11 | function balanceOf(address owner) external view returns (uint); 12 | function allowance(address owner, address spender) external view returns (uint); 13 | 14 | function approve(address spender, uint value) external returns (bool); 15 | function transfer(address to, uint value) external returns (bool); 16 | function transferFrom(address from, address to, uint value) external returns (bool); 17 | 18 | function DOMAIN_SEPARATOR() external view returns (bytes32); 19 | function PERMIT_TYPEHASH() external pure returns (bytes32); 20 | function nonces(address owner) external view returns (uint); 21 | 22 | function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; 23 | } -------------------------------------------------------------------------------- /uniswapv2/interfaces/IUniswapV2Factory.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.5.0; 2 | 3 | interface IUniswapV2Factory { 4 | event PairCreated(address indexed token0, address indexed token1, address pair, uint); 5 | 6 | function feeTo() external view returns (address); 7 | function feeToSetter() external view returns (address); 8 | function migrator() external view returns (address); 9 | 10 | function getPair(address tokenA, address tokenB) external view returns (address pair); 11 | function allPairs(uint) external view returns (address pair); 12 | function allPairsLength() external view returns (uint); 13 | 14 | function createPair(address tokenA, address tokenB) external returns (address pair); 15 | 16 | function setFeeTo(address) external; 17 | function setFeeToSetter(address) external; 18 | function setMigrator(address) external; 19 | } 20 | -------------------------------------------------------------------------------- /uniswapv2/interfaces/IUniswapV2Pair.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.5.0; 2 | 3 | interface IUniswapV2Pair { 4 | event Approval(address indexed owner, address indexed spender, uint value); 5 | event Transfer(address indexed from, address indexed to, uint value); 6 | 7 | function name() external pure returns (string memory); 8 | function symbol() external pure returns (string memory); 9 | function decimals() external pure returns (uint8); 10 | function totalSupply() external view returns (uint); 11 | function balanceOf(address owner) external view returns (uint); 12 | function allowance(address owner, address spender) external view returns (uint); 13 | 14 | function approve(address spender, uint value) external returns (bool); 15 | function transfer(address to, uint value) external returns (bool); 16 | function transferFrom(address from, address to, uint value) external returns (bool); 17 | 18 | function DOMAIN_SEPARATOR() external view returns (bytes32); 19 | function PERMIT_TYPEHASH() external pure returns (bytes32); 20 | function nonces(address owner) external view returns (uint); 21 | 22 | function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; 23 | 24 | event Mint(address indexed sender, uint amount0, uint amount1); 25 | event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); 26 | event Swap( 27 | address indexed sender, 28 | uint amount0In, 29 | uint amount1In, 30 | uint amount0Out, 31 | uint amount1Out, 32 | address indexed to 33 | ); 34 | event Sync(uint112 reserve0, uint112 reserve1); 35 | 36 | function MINIMUM_LIQUIDITY() external pure returns (uint); 37 | function factory() external view returns (address); 38 | function token0() external view returns (address); 39 | function token1() external view returns (address); 40 | function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); 41 | function price0CumulativeLast() external view returns (uint); 42 | function price1CumulativeLast() external view returns (uint); 43 | function kLast() external view returns (uint); 44 | 45 | function mint(address to) external returns (uint liquidity); 46 | function burn(address to) external returns (uint amount0, uint amount1); 47 | function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; 48 | function skim(address to) external; 49 | function sync() external; 50 | 51 | function initialize(address, address) external; 52 | } -------------------------------------------------------------------------------- /uniswapv2/interfaces/IUniswapV2Router01.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.6.2; 2 | 3 | interface IUniswapV2Router01 { 4 | function factory() external pure returns (address); 5 | function WETH() external pure returns (address); 6 | 7 | function addLiquidity( 8 | address tokenA, 9 | address tokenB, 10 | uint amountADesired, 11 | uint amountBDesired, 12 | uint amountAMin, 13 | uint amountBMin, 14 | address to, 15 | uint deadline 16 | ) external returns (uint amountA, uint amountB, uint liquidity); 17 | function addLiquidityETH( 18 | address token, 19 | uint amountTokenDesired, 20 | uint amountTokenMin, 21 | uint amountETHMin, 22 | address to, 23 | uint deadline 24 | ) external payable returns (uint amountToken, uint amountETH, uint liquidity); 25 | function removeLiquidity( 26 | address tokenA, 27 | address tokenB, 28 | uint liquidity, 29 | uint amountAMin, 30 | uint amountBMin, 31 | address to, 32 | uint deadline 33 | ) external returns (uint amountA, uint amountB); 34 | function removeLiquidityETH( 35 | address token, 36 | uint liquidity, 37 | uint amountTokenMin, 38 | uint amountETHMin, 39 | address to, 40 | uint deadline 41 | ) external returns (uint amountToken, uint amountETH); 42 | function removeLiquidityWithPermit( 43 | address tokenA, 44 | address tokenB, 45 | uint liquidity, 46 | uint amountAMin, 47 | uint amountBMin, 48 | address to, 49 | uint deadline, 50 | bool approveMax, uint8 v, bytes32 r, bytes32 s 51 | ) external returns (uint amountA, uint amountB); 52 | function removeLiquidityETHWithPermit( 53 | address token, 54 | uint liquidity, 55 | uint amountTokenMin, 56 | uint amountETHMin, 57 | address to, 58 | uint deadline, 59 | bool approveMax, uint8 v, bytes32 r, bytes32 s 60 | ) external returns (uint amountToken, uint amountETH); 61 | function swapExactTokensForTokens( 62 | uint amountIn, 63 | uint amountOutMin, 64 | address[] calldata path, 65 | address to, 66 | uint deadline 67 | ) external returns (uint[] memory amounts); 68 | function swapTokensForExactTokens( 69 | uint amountOut, 70 | uint amountInMax, 71 | address[] calldata path, 72 | address to, 73 | uint deadline 74 | ) external returns (uint[] memory amounts); 75 | function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) 76 | external 77 | payable 78 | returns (uint[] memory amounts); 79 | function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) 80 | external 81 | returns (uint[] memory amounts); 82 | function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) 83 | external 84 | returns (uint[] memory amounts); 85 | function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) 86 | external 87 | payable 88 | returns (uint[] memory amounts); 89 | 90 | function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); 91 | function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); 92 | function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); 93 | function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); 94 | function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); 95 | } -------------------------------------------------------------------------------- /uniswapv2/interfaces/IUniswapV2Router02.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.6.2; 2 | 3 | import './IUniswapV2Router01.sol'; 4 | 5 | interface IUniswapV2Router02 is IUniswapV2Router01 { 6 | function removeLiquidityETHSupportingFeeOnTransferTokens( 7 | address token, 8 | uint liquidity, 9 | uint amountTokenMin, 10 | uint amountETHMin, 11 | address to, 12 | uint deadline 13 | ) external returns (uint amountETH); 14 | function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( 15 | address token, 16 | uint liquidity, 17 | uint amountTokenMin, 18 | uint amountETHMin, 19 | address to, 20 | uint deadline, 21 | bool approveMax, uint8 v, bytes32 r, bytes32 s 22 | ) external returns (uint amountETH); 23 | 24 | function swapExactTokensForTokensSupportingFeeOnTransferTokens( 25 | uint amountIn, 26 | uint amountOutMin, 27 | address[] calldata path, 28 | address to, 29 | uint deadline 30 | ) external; 31 | function swapExactETHForTokensSupportingFeeOnTransferTokens( 32 | uint amountOutMin, 33 | address[] calldata path, 34 | address to, 35 | uint deadline 36 | ) external payable; 37 | function swapExactTokensForETHSupportingFeeOnTransferTokens( 38 | uint amountIn, 39 | uint amountOutMin, 40 | address[] calldata path, 41 | address to, 42 | uint deadline 43 | ) external; 44 | } -------------------------------------------------------------------------------- /uniswapv2/interfaces/IWETH.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.5.0; 2 | 3 | interface IWETH { 4 | function deposit() external payable; 5 | function transfer(address to, uint value) external returns (bool); 6 | function withdraw(uint) external; 7 | } -------------------------------------------------------------------------------- /uniswapv2/libraries/Math.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.6.12; 2 | 3 | // a library for performing various math operations 4 | 5 | library Math { 6 | function min(uint x, uint y) internal pure returns (uint z) { 7 | z = x < y ? x : y; 8 | } 9 | 10 | // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) 11 | function sqrt(uint y) internal pure returns (uint z) { 12 | if (y > 3) { 13 | z = y; 14 | uint x = y / 2 + 1; 15 | while (x < z) { 16 | z = x; 17 | x = (y / x + x) / 2; 18 | } 19 | } else if (y != 0) { 20 | z = 1; 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /uniswapv2/libraries/SafeMath.sol: -------------------------------------------------------------------------------- 1 | pragma solidity =0.6.12; 2 | 3 | // a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math) 4 | 5 | library SafeMathUniswap { 6 | function add(uint x, uint y) internal pure returns (uint z) { 7 | require((z = x + y) >= x, 'ds-math-add-overflow'); 8 | } 9 | 10 | function sub(uint x, uint y) internal pure returns (uint z) { 11 | require((z = x - y) <= x, 'ds-math-sub-underflow'); 12 | } 13 | 14 | function mul(uint x, uint y) internal pure returns (uint z) { 15 | require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow'); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /uniswapv2/libraries/TransferHelper.sol: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: GPL-3.0-or-later 2 | 3 | pragma solidity >=0.6.0; 4 | 5 | // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false 6 | library TransferHelper { 7 | function safeApprove(address token, address to, uint value) internal { 8 | // bytes4(keccak256(bytes('approve(address,uint256)'))); 9 | (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); 10 | require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); 11 | } 12 | 13 | function safeTransfer(address token, address to, uint value) internal { 14 | // bytes4(keccak256(bytes('transfer(address,uint256)'))); 15 | (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); 16 | require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); 17 | } 18 | 19 | function safeTransferFrom(address token, address from, address to, uint value) internal { 20 | // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); 21 | (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); 22 | require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); 23 | } 24 | 25 | function safeTransferETH(address to, uint value) internal { 26 | (bool success,) = to.call{value:value}(new bytes(0)); 27 | require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /uniswapv2/libraries/UQ112x112.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.6.12; 2 | 3 | // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) 4 | 5 | // range: [0, 2**112 - 1] 6 | // resolution: 1 / 2**112 7 | 8 | library UQ112x112 { 9 | uint224 constant Q112 = 2**112; 10 | 11 | // encode a uint112 as a UQ112x112 12 | function encode(uint112 y) internal pure returns (uint224 z) { 13 | z = uint224(y) * Q112; // never overflows 14 | } 15 | 16 | // divide a UQ112x112 by a uint112, returning a UQ112x112 17 | function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) { 18 | z = x / uint224(y); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /uniswapv2/libraries/UniswapV2Library.sol: -------------------------------------------------------------------------------- 1 | pragma solidity >=0.5.0; 2 | 3 | import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol'; 4 | import '@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol'; 5 | import "@nomiclabs/buidler/console.sol"; 6 | 7 | import "./SafeMath.sol"; 8 | 9 | library UniswapV2Library { 10 | using SafeMathUniswap for uint; 11 | 12 | // returns sorted token addresses, used to handle return values from pairs sorted in this order 13 | function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { 14 | require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); 15 | (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); 16 | require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); 17 | } 18 | 19 | // calculates the CREATE2 address for a pair without making any external calls 20 | function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { 21 | (address token0, address token1) = sortTokens(tokenA, tokenB); 22 | pair = address(uint(keccak256(abi.encodePacked( 23 | hex'ff', 24 | factory, 25 | keccak256(abi.encodePacked(token0, token1)), 26 | hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash 27 | )))); 28 | } 29 | 30 | // fetches and sorts the reserves for a pair 31 | function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { 32 | (address token0,) = sortTokens(tokenA, tokenB); 33 | (uint reserve0, uint reserve1,) = IUniswapV2Pair(IUniswapV2Factory(factory).getPair(tokenA, tokenB)).getReserves(); 34 | (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); 35 | } 36 | 37 | // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset 38 | function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { 39 | require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); 40 | require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); 41 | amountB = amountA.mul(reserveB) / reserveA; 42 | } 43 | 44 | // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset 45 | function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { 46 | require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); 47 | require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); 48 | uint amountInWithFee = amountIn.mul(997); 49 | uint numerator = amountInWithFee.mul(reserveOut); 50 | uint denominator = reserveIn.mul(1000).add(amountInWithFee); 51 | amountOut = numerator / denominator; 52 | } 53 | 54 | // given an output amount of an asset and pair reserves, returns a required input amount of the other asset 55 | function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { 56 | require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); 57 | require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); 58 | uint numerator = reserveIn.mul(amountOut).mul(1000); 59 | uint denominator = reserveOut.sub(amountOut).mul(997); 60 | amountIn = (numerator / denominator).add(1); 61 | } 62 | 63 | // performs chained getAmountOut calculations on any number of pairs 64 | function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { 65 | require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); 66 | amounts = new uint[](path.length); 67 | amounts[0] = amountIn; 68 | for (uint i; i < path.length - 1; i++) { 69 | (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); 70 | amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); 71 | } 72 | } 73 | 74 | // performs chained getAmountIn calculations on any number of pairs 75 | function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { 76 | require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); 77 | amounts = new uint[](path.length); 78 | amounts[amounts.length - 1] = amountOut; 79 | for (uint i = path.length - 1; i > 0; i--) { 80 | (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); 81 | amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); 82 | } 83 | } 84 | } --------------------------------------------------------------------------------