file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
/** * Token name: KT * Interface: ERC721 * This token is established by Krypital Group LLC, mainly used as a gift for Krypital supporters. * Total supply of KTs is set to 2100. * A KT holder can either hold it as a souvenir (leave message on the message board), or play the game by merging/decomposing tokens. */ pragma solidity ^0.4.19; /** * @title safemath * @dev Math operations with safety checks that throw on error */ library safemath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title ownable * @dev The ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract erc721 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function transfer(address _to, uint256 _tokenId) public; function approve(address _to, uint256 _tokenId) public; function takeOwnership(uint256 _tokenId) public; } /** * @title KTaccess * @author Yihan -- CyberMiles * @dev This contract is for regulating the owners' addr. * Inherited by KTfactory. */ contract KTaccess is ownable{ address public o1Address; address public o2Address; address public o3Address; modifier onlyOLevel() { require( msg.sender == o1Address || msg.sender == o2Address || msg.sender == o3Address || msg.sender == owner ); _; } function setO1(address _newAddr) external onlyOLevel { require(_newAddr != address(0)); o1Address = _newAddr; } function setO2(address _newAddr) external onlyOLevel { require(_newAddr != address(0)); o2Address = _newAddr; } function setO3(address _newAddr) external onlyOLevel { require(_newAddr != address(0)); o3Address = _newAddr; } } /** * @title KTfactory * @author Yihan -- CyberMiles * @dev This main contract for creating KTs. * * A KT, which is the token issued by Krypital, has the following properties: * an officail note that can be created only by the contract owner; * a personal note that can be modified by the current owner of the token; * a bool value indicating if the token is currently frozen by Krypital; * a gene which is a hashed value that changes when mutate (merge or decompose). This is for some future interesting apps :D * level, namely, the level of the token. Apparently higher is better :D * id, the key used to map to the associated KT. * */ contract KTfactory is ownable, KTaccess { using safemath for uint256; uint256 public maxId; uint256 public initial_supply; uint256 public curr_number; event NewKT(string note, uint256 gene, uint256 level, uint256 tokenId); event UpdateNote(string newNote, uint256 tokenId); event PauseToken(uint256 tokenId); event UnpauseToken(uint256 tokenId); struct KT { string officialNote; string personalNote; bool paused; uint256 gene; uint256 level; uint256 id; } mapping (uint256 => KT) public KTs; mapping (uint => address) public KTToOwner; mapping (address => uint) ownerKTCount; modifier onlyOwnerOf(uint token_id) { require(msg.sender == KTToOwner[token_id]); _; } modifier whenNotFrozen(uint token_id) { require(KTs[token_id].paused == false); _; } modifier withinTotal() { require(curr_number<= initial_supply); _; } modifier hasKT(uint token_id) { require(KTs[token_id].id != 0); _; } /** * @dev The constructor. Sets the initial supply and some other global variables. * That's right, Krypital will only issue 2100 tokens in total. It also means the total number of KTs will not exceed this number! */ constructor() public { initial_supply = 2100; maxId=0; curr_number=0; } /** * @dev The creator of KTs. Only done by Krypital. * @param oNote - the official, special note left only by Krypital! */ function _createKT(string oNote) public onlyOLevel withinTotal { uint thisId = maxId + 1; string pNote; uint256 thisGene = uint256(keccak256(oNote)); KT memory thisKT = KT({ officialNote: oNote, personalNote: pNote, paused: false, gene: thisGene, level: 1, id: thisId }); KTs[thisId] = thisKT; maxId = maxId + 1; curr_number = curr_number + 1; KTToOwner[thisId] = msg.sender; ownerKTCount[msg.sender]++; emit NewKT(oNote, thisGene, 1, thisId); } /** * @dev This method is for editing your personal note! * @param note - the note you want the old one to be replaced by * @param token_id - just token id */ function _editPersonalNote(string note, uint token_id) public onlyOwnerOf(token_id) hasKT(token_id){ KT storage currKT = KTs[token_id]; currKT.personalNote = note; emit UpdateNote(note, token_id); } /** * @dev Pauses a token, done by Krypital * When a token is paused by Krypital, the owner of the token can still update the personal note but the ownership cannot be transferred. * @param token_id - just token id */ function pauseToken(uint token_id) public onlyOLevel hasKT(token_id){ KT storage currKT = KTs[token_id]; currKT.paused = true; emit PauseToken(token_id); } /** * @dev Unpauses a token, done by Krypital * @param token_id - just token id */ function unpauseToken(uint token_id) public onlyOLevel hasKT(token_id){ KT storage currKT = KTs[token_id]; currKT.paused = false; emit UnpauseToken(token_id); } } /** * @title KT * @author Yihan -- CyberMiles * @dev This contract is the contract regulating the transfer, decomposition, merging mechanism amaong the tokens. */ contract KT is KTfactory, erc721 { using safemath for uint256; mapping (uint => address) KTApprovals; /** * @dev The modifer to regulate a KT's decomposability. * A level 1 KT is not decomposable. * @param token_id - simply token id. */ modifier decomposeAllowed(uint token_id){ require(KTs[token_id].level > 1); _; } event Decompose(uint256 tokenId); event Merge(uint256 tokenId1, uint256 tokenId2); /** * @dev This is for getting the ether back to the contract owner's account. Just in case someone generous sends the creator some ethers :P */ function withdraw() external onlyOwner { owner.transfer(this.balance); } /** * @dev For checking how many tokens you own. * @param _owner - the owner's addr */ function balanceOf(address _owner) public view returns(uint256) { return ownerKTCount[_owner]; } /** * @dev For checking the owner of the given token. * @param _tokenId - just token id */ function ownerOf(uint256 _tokenId) public view returns(address) { return KTToOwner[_tokenId]; } /** * @dev the private helper function for transfering ownership. * @param _from - current KT owner * @param _to - new KT owner * @param _tokenId - just token id */ function _transfer(address _from, address _to, uint256 _tokenId) private hasKT(_tokenId) { ownerKTCount[_to] = ownerKTCount[_to].add(1); ownerKTCount[msg.sender] = ownerKTCount[msg.sender].sub(1); KTToOwner[_tokenId] = _to; emit Transfer(_from, _to, _tokenId); } /** * @dev This method can be called if you are the token owner and you want to transfer the token to someone else. * @param _to - new KT owner * @param _tokenId - just token id */ function transfer(address _to, uint256 _tokenId) public whenNotFrozen(_tokenId) onlyOwnerOf(_tokenId) hasKT(_tokenId){ require(_to != address(0)); _transfer(msg.sender, _to, _tokenId); } /** * @dev An approved user can 'claim' a token of another user. * @param _to - new KT owner * @param _tokenId - just token id */ function approve(address _to, uint256 _tokenId) public onlyOwnerOf(_tokenId) hasKT(_tokenId) { require(_to != address(0)); KTApprovals[_tokenId] = _to; emit Approval(msg.sender, _to, _tokenId); } /** * @dev The user to be approved must be approved by the current token holder. * @param _tokenId - just token id */ function takeOwnership(uint256 _tokenId) public whenNotFrozen(_tokenId) hasKT(_tokenId){ require(KTApprovals[_tokenId] == msg.sender); address owner = ownerOf(_tokenId); _transfer(owner, msg.sender, _tokenId); } /** * @dev This method is for decomposing (or split) a token. Only can be done by token holder when token is not frozen. * Note: one of the tokens will take the original token's place, that is, the old ID will actually map to a new token! * Level down by 1!!! A level 1 token cannot be decomposed. * The genes of the two new born tokens will be both identical to the old token. * Notes of the two new tokens are identical to the original token. */ function decompose(uint256 token_id) public whenNotFrozen(token_id) onlyOwnerOf(token_id) decomposeAllowed(token_id) hasKT(token_id) withinTotal{ KT storage decomposed = KTs[token_id]; decomposed.level = decomposed.level-1; decomposed.gene = decomposed.gene/2; KT memory newKT = KT({ officialNote: decomposed.officialNote, personalNote: decomposed.personalNote, paused: false, gene: decomposed.gene, level: decomposed.level, id: maxId.add(1) }); maxId=maxId.add(1); curr_number=curr_number.add(1); KTs[maxId]=newKT; KTToOwner[maxId]=KTToOwner[token_id]; ownerKTCount[msg.sender]=ownerKTCount[msg.sender].add(1); emit Decompose(token_id); } /** * @dev This function is for merging 2 tokens. Only tokens with the same levels can be merge. A user can only choose to merge from his own tokens. * After merging, id and official note are merged to the previous token passed in the args. * NOTE that the notes associated with the second token will be wiped out! Use with your caution. * Level up by 1!!! * New gene = (gene1 + gene2) / 2 * @param id1 - the ID to the 1st token, this ID will remain after merging. * @param id2 - the ID of the 2nd token, this ID will map to nothing after merging!! */ function merge(uint256 id1, uint256 id2) public hasKT(id1) hasKT(id2) whenNotFrozen(id1) whenNotFrozen(id2) onlyOwnerOf(id1) onlyOwnerOf(id2){ require(KTs[id1].level == KTs[id2].level); KT storage token1 = KTs[id1]; token1.gene = (token1.gene + KTs[id2].gene) / 2; token1.level = (token1.level).add(1); KT memory toDelete = KT ({ officialNote: "", personalNote: "", paused: false, gene: 0, level: 0, id: 0 }); KTs[id2] = toDelete; curr_number = curr_number.sub(1); KTToOwner[id2] = address(0); ownerKTCount[msg.sender] = ownerKTCount[msg.sender].sub(1); emit Merge(id1, id2); } }
This method is for decomposing (or split) a token. Only can be done by token holder when token is not frozen. Note: one of the tokens will take the original token's place, that is, the old ID will actually map to a new token! Level down by 1!!! A level 1 token cannot be decomposed. The genes of the two new born tokens will be both identical to the old token. Notes of the two new tokens are identical to the original token./
function decompose(uint256 token_id) public whenNotFrozen(token_id) onlyOwnerOf(token_id) decomposeAllowed(token_id) hasKT(token_id) withinTotal{ KT storage decomposed = KTs[token_id]; decomposed.level = decomposed.level-1; decomposed.gene = decomposed.gene/2; KT memory newKT = KT({ officialNote: decomposed.officialNote, personalNote: decomposed.personalNote, paused: false, gene: decomposed.gene, level: decomposed.level, id: maxId.add(1) }); maxId=maxId.add(1); curr_number=curr_number.add(1); KTs[maxId]=newKT; KTToOwner[maxId]=KTToOwner[token_id]; ownerKTCount[msg.sender]=ownerKTCount[msg.sender].add(1); emit Decompose(token_id); }
7,283,920
pragma solidity ^0.4.23; /** * @title Datatrust Anchoring system * @author Blockchain Partner * @author https://blockchainpartner.fr */ contract Datatrust { // Event emitted when saving a new anchor event NewAnchor(bytes32 merkleRoot); /** * @dev Save a new anchor for a given Merkle tree root hash * @dev Use events as a form of storage * @param _merkleRoot bytes32 hash to anchor */ function saveNewAnchor(bytes32 _merkleRoot) public { emit NewAnchor(_merkleRoot); } }
Save a new anchor for a given Merkle tree root hash Use events as a form of storage _merkleRoot bytes32 hash to anchor/
function saveNewAnchor(bytes32 _merkleRoot) public { emit NewAnchor(_merkleRoot); }
2,119,584
./full_match/42161/0xAcD1cAeF47E4c47BafE8a51B3F4305Fc38203b7A/sources/contracts/Luneko.sol
Activate the taxes.
function activateTaxes() external onlyOwner { taxRate = 2; taxActive = true; }
16,307,476
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol"; import "@openzeppelin/contracts/finance/PaymentSplitter.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol"; /** * @title NFT Smart Contract * @author Stephan Fowler * @notice ERC721 contract for stand-alone NFT collections with separable "agent" role, payment splitting, and lazy-minting capability * @dev Enables lazy-minting by any user via precomputed signatures */ contract NFTsurface is ERC721, ERC721Burnable, EIP712, AccessControl, PaymentSplitter { event IdRevoked(uint256 tokenId); event IdFloorSet(uint256 idFloor); bytes32 public constant AGENT_ROLE = keccak256("AGENT_ROLE"); // See NFT Provenance notes regarding why these are immutable address public immutable owner; uint16 public immutable royaltyBasisPoints; uint256 public totalSupply; uint256 public idFloor; mapping(uint256 => string) private tokenURIs; mapping(uint256 => bool) private revokedIds; mapping(uint256 => uint256) private prices; /** * @dev Constructor immutably sets "owner" to the message sender; be sure to deploy contract using the account of the creator/artist/brand/etc. * @param name ERC721 token name * @param symbol ERC721 token symbol * @param admin The administrator address can reassign roles * @param agent The agent address is authorised for all minting, signing, and revoking operations * @param payees Array of PaymentSplitter payee addresses * @param shares Array of PaymentSplitter shares * @param royaltyBasisPoints_ Percentage basis-points for royalty on secondary sales, eg 495 == 4.95% */ constructor( string memory name, string memory symbol, address admin, address agent, address[] memory payees, uint256[] memory shares, uint16 royaltyBasisPoints_ ) ERC721(name, symbol) EIP712("NFTsurface", "1.0.0") PaymentSplitter(payees, shares) { owner = _msgSender(); royaltyBasisPoints = royaltyBasisPoints_; _setupRole(DEFAULT_ADMIN_ROLE, admin); _setupRole(AGENT_ROLE, agent); } event PriceSet(uint256 id, uint256 price); event Bought(uint256 id, address buyer); /** * @notice Minting by the agent only * @param recipient The recipient of the NFT * @param id The intended token Id * @param uri The intended token URI */ function mintAuthorized( address recipient, uint256 id, string memory uri ) external { require(hasRole(AGENT_ROLE, _msgSender()), "unauthorized to mint"); require(vacant(id)); _mint(recipient, id, uri); } /** * @notice Minting by any caller * @dev Enables "lazy" minting by any user who can provide an agent's signature for the specified params and value * @param id The intended token Id * @param uri The intended token URI * @param signature The ERC712 signature of the hash of message value, id, and uri */ function mint( uint256 id, string memory uri, bytes calldata signature ) external payable { require(mintable(msg.value, id, uri, signature)); _mint(_msgSender(), id, uri); } /** * @notice Checks availability for minting and validity of a signature * @dev Typically run before offering a mint option to users * @param weiPrice The advertised price of the token * @param id The intended token Id * @param uri The intended token URI * @param signature The ERC712 signature of the hash of weiPrice, id, and uri */ function mintable( uint256 weiPrice, uint256 id, string memory uri, bytes calldata signature ) public view returns (bool) { require(vacant(id)); require( hasRole( AGENT_ROLE, ECDSA.recover(_hash(weiPrice, id, uri), signature) ), "signature invalid or signer unauthorized" ); return true; } /** * @notice Checks the availability of a token Id * @dev Reverts if the Id is previously minted, revoked, or burnt * @param id The token Id */ function vacant(uint256 id) public view returns (bool) { require(!_exists(id), "tokenId already minted"); require(id >= idFloor, "tokenId below floor"); require(!revokedIds[id], "tokenId revoked or burnt"); return true; } /** * @notice Sets the price at which a token may be bought * @dev Setting a zero price cancels the sale (all prices are zero by default) * @param id The token id * @param _price The token price in wei */ function setPrice(uint256 id, uint256 _price) external { require(_msgSender() == ownerOf(id), "caller is not token owner"); prices[id] = _price; emit PriceSet(id, _price); } /** * @notice Returns the price at which a token may be bought * @dev A zero price means the token is not for sale * @param id The token id */ function price(uint256 id) external view returns (uint256) { return prices[id]; } /** * @notice Transfers the token to the caller, transfers the paid ETH to its owner (minus any royalty) * @dev A zero price means the token is not for sale * @param id The token id */ function buy(uint256 id) external payable { require(_msgSender() != ownerOf(id), "caller is token owner"); require(prices[id] > 0, "token not for sale"); require(msg.value >= prices[id], "insufficient ETH sent"); address seller = ownerOf(id); delete prices[id]; _safeTransfer(seller, _msgSender(), id, ""); Address.sendValue( payable(seller), (10000 - royaltyBasisPoints) * (msg.value / 10000) ); emit Bought(id, _msgSender()); } /** * @notice Revokes a specified token Id, to disable any signatures that include it * @param id The token Id that can no longer be minted */ function revokeId(uint256 id) external { require(hasRole(AGENT_ROLE, _msgSender()), "unauthorized to revoke id"); require(vacant(id)); revokedIds[id] = true; IdRevoked(id); } /** * @notice Revokes token Ids below a given floor, to disable any signatures that include them * @param floor The floor for token Ids minted from now onward */ function setIdFloor(uint256 floor) external { require( hasRole(AGENT_ROLE, _msgSender()), "unauthorized to set idFloor" ); require(floor > idFloor, "must exceed current floor"); idFloor = floor; IdFloorSet(idFloor); } /** * @notice Returns the token URI, given the token Id * @param id The token Id */ function tokenURI(uint256 id) public view override returns (string memory) { return tokenURIs[id]; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view override(ERC721, AccessControl) returns (bool) { return super.supportsInterface(interfaceId); } /** * @dev Minting also increments totalSupply */ function _mint( address recipient, uint256 id, string memory uri ) internal { _safeMint(recipient, id); _setTokenURI(id, uri); totalSupply += 1; } /** * @dev Recreates the hash that the signer (may have) signed */ function _hash( uint256 weiPrice, uint256 id, string memory uri ) internal view returns (bytes32) { return _hashTypedDataV4( keccak256( abi.encode( keccak256( "mint(uint256 weiPrice,uint256 tokenId,string tokenURI)" ), weiPrice, id, keccak256(bytes(uri)) ) ) ); } /** * @dev record a token's URI against its Id */ function _setTokenURI(uint256 id, string memory uri) internal { require(bytes(uri).length != 0, "tokenURI cannot be empty"); tokenURIs[id] = uri; } /** * @dev burn a token and prevent the reuse of its Id */ function _burn(uint256 id) internal override { super._burn(id); delete tokenURIs[id]; revokedIds[id] = true; totalSupply -= 1; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721) { super._beforeTokenTransfer(from, to, tokenId); delete prices[tokenId]; } }
Minting by the agent only recipient The recipient of the NFT id The intended token Id uri The intended token URI/
function mintAuthorized( address recipient, uint256 id, string memory uri ) external { require(hasRole(AGENT_ROLE, _msgSender()), "unauthorized to mint"); require(vacant(id)); _mint(recipient, id, uri); }
14,015,101
pragma solidity 0.6.7; import "./lib/enumerableSet.sol"; import "./lib/safe-math.sol"; import "./lib/erc20.sol"; import "./lib/ownable.sol"; import "./interfaces/strategy.sol"; import "./pud-token.sol"; // MasterChef was the master of pud. He now governs over Pud. He can make Pud and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once Pud is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 shares; // How many LP tokens shares the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of Pud // entitled to a user but is pending to be distributed is: // // pending reward = (user.shares * pool.accPudPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accPudPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. Pud to distribute per block. uint256 lastRewardBlock; // Last block number that Pud distribution occurs. uint256 accPudPerShare; // Accumulated Pud per share, times 1e12. See below. address strategy; uint256 totalShares; } // The Pud TOKEN! PudToken public pud; // Dev fund (10%, initially) uint256 public devFundDivRate = 10; // Dev address. address public devaddr; // Treasure address. address public treasury; // Block number when bonus Pud period ends. uint256 public bonusEndBlock; // Pud tokens created per block. uint256 public pudPerBlock; // Bonus muliplier for early pud makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when Pud mining starts. uint256 public startBlock; // Events event Recovered(address token, uint256 amount); event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); constructor( PudToken _pud, address _devaddr, address _treasury, uint256 _pudPerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { pud = _pud; devaddr = _devaddr; treasury = _treasury; pudPerBlock = _pudPerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate, address _strategy ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accPudPerShare: 0, strategy: _strategy, totalShares: 0 }) ); } // Update the given pool's Pud allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending Pud on frontend. function pendingPud(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accPudPerShare = pool.accPudPerShare; uint256 lpSupply = pool.totalShares; if (block.number > pool.lastRewardBlock && lpSupply != 0 && pool.allocPoint > 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 pudReward = multiplier.mul(pudPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); accPudPerShare = accPudPerShare.add( pudReward.mul(1e12).div(lpSupply) ); } return user.shares.mul(accPudPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.totalShares; if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 pudReward = 0; if (pool.allocPoint > 0){ pudReward = multiplier.mul(pudPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); if (pudReward > 0){ pud.mint(devaddr, pudReward.div(devFundDivRate)); pud.mint(address(this), pudReward); } } pool.accPudPerShare = pool.accPudPerShare.add( pudReward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for Pud allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.shares > 0) { uint256 pending = user.shares.mul(pool.accPudPerShare).div(1e12).sub( user.rewardDebt ); safePudTransfer(msg.sender, pending); } // uint256 _pool = balance(_pid); //get _pid lptoken balance if (_amount > 0) { uint256 _before = pool.lpToken.balanceOf(pool.strategy); pool.lpToken.safeTransferFrom( address(msg.sender), pool.strategy, _amount ); uint256 _after = pool.lpToken.balanceOf(pool.strategy); _amount = _after.sub(_before); // Additional check for deflationary tokens } uint256 shares = 0; if (pool.totalShares == 0) { shares = _amount; } else { shares = (_amount.mul(pool.totalShares)).div(_pool); } user.shares = user.shares.add(shares); //add shares instead of amount user.rewardDebt = user.shares.mul(pool.accPudPerShare).div(1e12); pool.totalShares = pool.totalShares.add(shares); //add shares in pool emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _shares) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.shares >= _shares, "withdraw: not good"); updatePool(_pid); uint256 r = (balance(_pid).mul(_shares)).div(pool.totalShares); uint256 pending = user.shares.mul(pool.accPudPerShare).div(1e12).sub( user.rewardDebt ); safePudTransfer(msg.sender, pending); user.shares = user.shares.sub(_shares); user.rewardDebt = user.shares.mul(pool.accPudPerShare).div(1e12); pool.totalShares = pool.totalShares.sub(_shares); //minus shares in pool // Check balance if (r > 0) { uint256 b = pool.lpToken.balanceOf(address(this)); IStrategy(pool.strategy).withdraw(r); uint256 _after = pool.lpToken.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < r) { r = b.add(_diff); } pool.lpToken.safeTransfer(address(msg.sender), r); } emit Withdraw(msg.sender, _pid, r); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 r = (balance(_pid).mul(user.shares)).div(pool.totalShares); // Check balance uint256 b = pool.lpToken.balanceOf(address(this)); IStrategy(pool.strategy).withdraw(r); uint256 _after = pool.lpToken.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < r) { r = b.add(_diff); } pool.lpToken.safeTransfer(address(msg.sender), r); emit EmergencyWithdraw(msg.sender, _pid, user.shares); user.shares = 0; user.rewardDebt = 0; } // Safe pud transfer function, just in case if rounding error causes pool to not have enough Pud. function safePudTransfer(address _to, uint256 _amount) internal { uint256 pudBal = pud.balanceOf(address(this)); if (_amount > pudBal) { pud.transfer(_to, pudBal); } else { pud.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // **** Additional functions separate from the original masterchef contract **** function setTreasury(address _treasury) public onlyOwner { treasury = _treasury; } function setPudPerBlock(uint256 _pudPerBlock) public onlyOwner { require(_pudPerBlock > 0, "!pudPerBlock-0"); pudPerBlock = _pudPerBlock; } function setStartBlock(uint256 _startBlock) public onlyOwner { startBlock = _startBlock; uint256 length = poolInfo.length; for (uint256 _pid = 0; _pid < length; ++_pid) { PoolInfo storage pool = poolInfo[_pid]; pool.lastRewardBlock = startBlock; } } function setBonusEndBlock(uint256 _bonusEndBlock) public onlyOwner { bonusEndBlock = _bonusEndBlock; } function setDevFundDivRate(uint256 _devFundDivRate) public onlyOwner { require(_devFundDivRate > 0, "!devFundDivRate-0"); devFundDivRate = _devFundDivRate; } function balance(uint256 _pid) public view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; return IStrategy(pool.strategy).balanceOf(); } function setPoolStrategy(uint256 _pid,address _strategy) public onlyOwner { PoolInfo storage pool = poolInfo[_pid]; IStrategy(pool.strategy).harvest(); IStrategy(pool.strategy).withdrawAll(_strategy); pool.strategy = _strategy; } }
Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.totalShares; if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 pudReward = 0; if (pool.allocPoint > 0){ pudReward = multiplier.mul(pudPerBlock).mul(pool.allocPoint).div( totalAllocPoint ); if (pudReward > 0){ pud.mint(devaddr, pudReward.div(devFundDivRate)); pud.mint(address(this), pudReward); } } pool.accPudPerShare = pool.accPudPerShare.add( pudReward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = block.number; }
7,245,949
./full_match/3/0x89ce35170d5de0fb1FaddC27Df1b9E91dD2e83D4/sources/contracts/SigmoidBonds.sol
check if the bond is redeemable
function bondIsRedeemable(uint256 class, uint256 nonce) public view override returns (bool){ if (last_bond_redeemed[class] >= nonce) { return (true); } if (uint256(_info[class][nonce][1]) < now) { uint256 total_liquidity = last_activeSupply[class]; uint256 needed_liquidity = last_activeSupply[class]; for ( uint256 i = last_bond_redeemed[class]; i <= last_bond_nonce[class]; i++ ) { total_liquidity += _activeSupply[class][i] + _redeemedSupply[class][i]; } for (uint256 i = last_bond_redeemed[class]; i <= nonce; i++) { needed_liquidity += (_activeSupply[class][i] + _redeemedSupply[class][i]) * 2; } if (total_liquidity >= needed_liquidity) { return (true); return (false); } return (false); } }
8,173,767
./partial_match/1/0xe8765eC7b69ab754c149b96178106082fabf5a65/sources/contracts/ERC-721/ERC721PoolFactory.sol
PUBLIC STORAGE @inheritdoc IERC721PoolFactory @inheritdoc IERC721PoolFactory @inheritdoc IERC721PoolFactory PUBLIC CONSTANT FUNCTIONS @inheritdoc IERC721PoolFactory
function allPoolsLength() external view override returns (uint256) { return allPools.length; }
2,766,431
./partial_match/1/0xf6c33a5aCA089BE53bA8c95685426aCD2fc4F4e1/sources/helpers.sol
Moves tokens `amount` from `sender` to `recipient`. This is internal function is equivalent to {transfer}, and can be used to e.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `sender` cannot be the zero address. - `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`./
function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); require(amount <= availableAmount(sender),"ERC20 : amount exceeds available amount"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); }
15,727,184
./full_match/80001/0xD8224491fcF8dE30135A4c53ac2c1Edb90D82A06/sources/MembershipCrossmint.sol
set mintRate as per new collection launch
function setMintRate(uint256 _mintRate) external onlyOwner { mintRate = _mintRate; }
845,059
//SPDX-License-Identifier: MIT pragma solidity 0.8.8; import "./IERC20.sol"; import "./IERC20_Bridge_Logic_Restricted.sol"; import "./IMultisigControl.sol"; import "./ERC20_Asset_Pool.sol"; /// @title ERC20 Bridge Logic /// @author Vega Protocol /// @notice This contract is used by Vega network users to deposit and withdraw ERC20 tokens to/from Vega. // @notice All funds deposited/withdrawn are to/from the assigned ERC20_Asset_Pool contract ERC20_Bridge_Logic_Restricted is IERC20_Bridge_Logic_Restricted { address payable erc20_asset_pool_address; // asset address => is listed mapping(address => bool) listed_tokens; // asset address => minimum deposit amt mapping(address => uint256) minimum_deposits; // asset address => maximum deposit amt mapping(address => uint256) maximum_deposits; // Vega asset ID => asset_source mapping(bytes32 => address) vega_asset_ids_to_source; // asset_source => Vega asset ID mapping(address => bytes32) asset_source_to_vega_asset_id; /// @param erc20_asset_pool Initial Asset Pool contract address constructor(address payable erc20_asset_pool) { erc20_asset_pool_address = erc20_asset_pool; } function multisig_control_address() internal view returns(address) { return ERC20_Asset_Pool(erc20_asset_pool_address).multisig_control_address(); } /***************************FUNCTIONS*************************/ /// @notice This function lists the given ERC20 token contract as valid for deposit to this bridge /// @param asset_source Contract address for given ERC20 token /// @param vega_asset_id Vega-generated asset ID for internal use in Vega Core /// @param lifetime_limit Initial lifetime deposit limit *RESTRICTION FEATURE* /// @param withdraw_threshold Amount at which the withdraw delay goes into effect *RESTRICTION FEATURE* /// @param nonce Vega-assigned single-use number that provides replay attack protection /// @param signatures Vega-supplied signature bundle of a validator-signed order /// @notice See MultisigControl for more about signatures /// @dev Emits Asset_Listed if successful function list_asset(address asset_source, bytes32 vega_asset_id, uint256 lifetime_limit, uint256 withdraw_threshold, uint256 nonce, bytes memory signatures) public override { require(!listed_tokens[asset_source], "asset already listed"); bytes memory message = abi.encode(asset_source, vega_asset_id, lifetime_limit, withdraw_threshold, nonce, 'list_asset'); require(IMultisigControl(multisig_control_address()).verify_signatures(signatures, message, nonce), "bad signatures"); listed_tokens[asset_source] = true; vega_asset_ids_to_source[vega_asset_id] = asset_source; asset_source_to_vega_asset_id[asset_source] = vega_asset_id; asset_deposit_lifetime_limit[asset_source] = lifetime_limit; withdraw_thresholds[asset_source] = withdraw_threshold; emit Asset_Listed(asset_source, vega_asset_id, nonce); } /// @notice This function removes from listing the given ERC20 token contract. This marks the token as invalid for deposit to this bridge /// @param asset_source Contract address for given ERC20 token /// @param nonce Vega-assigned single-use number that provides replay attack protection /// @param signatures Vega-supplied signature bundle of a validator-signed order /// @notice See MultisigControl for more about signatures /// @dev Emits Asset_Removed if successful function remove_asset(address asset_source, uint256 nonce, bytes memory signatures) public override { require(listed_tokens[asset_source], "asset not listed"); bytes memory message = abi.encode(asset_source, nonce, 'remove_asset'); require(IMultisigControl(multisig_control_address()).verify_signatures(signatures, message, nonce), "bad signatures"); listed_tokens[asset_source] = false; emit Asset_Removed(asset_source, nonce); } /// @notice This function sets the minimum allowable deposit for the given ERC20 token /// @param asset_source Contract address for given ERC20 token /// @param minimum_amount Minimum deposit amount /// @param nonce Vega-assigned single-use number that provides replay attack protection /// @param signatures Vega-supplied signature bundle of a validator-signed order /// @notice See MultisigControl for more about signatures /// @dev Emits Asset_Deposit_Minimum_Set if successful function set_deposit_minimum(address asset_source, uint256 minimum_amount, uint256 nonce, bytes memory signatures) public override{ require(listed_tokens[asset_source], "asset not listed"); bytes memory message = abi.encode(asset_source, minimum_amount, nonce, 'set_deposit_minimum'); require(IMultisigControl(multisig_control_address()).verify_signatures(signatures, message, nonce), "bad signatures"); minimum_deposits[asset_source] = minimum_amount; emit Asset_Deposit_Minimum_Set(asset_source, minimum_amount, nonce); } /// @notice This function sets the maximum allowable deposit for the given ERC20 token /// @param asset_source Contract address for given ERC20 token /// @param maximum_amount Maximum deposit amount /// @param nonce Vega-assigned single-use number that provides replay attack protection /// @param signatures Vega-supplied signature bundle of a validator-signed order /// @notice See MultisigControl for more about signatures /// @dev Emits Asset_Deposit_Maximum_Set if successful function set_deposit_maximum(address asset_source, uint256 maximum_amount, uint256 nonce, bytes memory signatures) public override { require(listed_tokens[asset_source], "asset not listed"); bytes memory message = abi.encode(asset_source, maximum_amount, nonce, 'set_deposit_maximum'); require(IMultisigControl(multisig_control_address()).verify_signatures(signatures, message, nonce), "bad signatures"); maximum_deposits[asset_source] = maximum_amount; emit Asset_Deposit_Maximum_Set(asset_source, maximum_amount, nonce); } /************************RESTRICTIONS***************************/ // user => asset_source => deposit total mapping(address => mapping(address => uint256)) user_lifetime_deposits; // asset_source => deposit_limit mapping(address => uint256) asset_deposit_lifetime_limit; uint256 public default_withdraw_delay = 432000; // asset_source => threshold mapping(address => uint256) withdraw_thresholds; bool public is_stopped; // depositor => is exempt from deposit limits mapping(address => bool) exempt_depositors; address exemption_lister; /// @notice This function sets the lifetime maximum deposit for a given asset /// @param asset_source Contract address for given ERC20 token /// @param lifetime_limit Deposit limit for a given ethereum address /// @param nonce Vega-assigned single-use number that provides replay attack protection /// @param signatures Vega-supplied signature bundle of a validator-signed order /// @dev asset must first be listed function set_lifetime_deposit_max(address asset_source, uint256 lifetime_limit, uint256 nonce, bytes calldata signatures) public override { require(listed_tokens[asset_source], "asset not listed"); bytes memory message = abi.encode(asset_source, lifetime_limit, nonce, 'set_lifetime_deposit_max'); require(IMultisigControl(multisig_control_address()).verify_signatures(signatures, message, nonce), "bad signatures"); asset_deposit_lifetime_limit[asset_source] = lifetime_limit; } /// @notice This view returns the lifetime deposit limit for the given asset /// @param asset_source Contract address for given ERC20 token /// @return Lifetime limit for the given asset function get_asset_deposit_limit(address asset_source) public override view returns(uint256) { return asset_deposit_lifetime_limit[asset_source]; } /// @notice This function sets the withdraw delay for withdrawals over the per-asset set thresholds /// @param delay Amount of time to delay a withdrawal /// @param nonce Vega-assigned single-use number that provides replay attack protection /// @param signatures Vega-supplied signature bundle of a validator-signed order function set_withdraw_delay(uint256 delay, uint256 nonce, bytes calldata signatures) public override { bytes memory message = abi.encode(delay, nonce, 'set_withdraw_delay'); require(IMultisigControl(multisig_control_address()).verify_signatures(signatures, message, nonce), "bad signatures"); default_withdraw_delay = delay; } /// @notice This function sets the withdraw threshold above which the withdraw delay goes into effect /// @param asset_source Contract address for given ERC20 token /// @param threshold Withdraw size above which the withdraw delay goes into effect /// @param nonce Vega-assigned single-use number that provides replay attack protection /// @param signatures Vega-supplied signature bundle of a validator-signed order /// @dev asset must first be listed function set_withdraw_threshold(address asset_source, uint256 threshold, uint256 nonce, bytes calldata signatures) public override { require(listed_tokens[asset_source], "asset not listed"); bytes memory message = abi.encode(asset_source, threshold, nonce, 'set_withdraw_threshold'); require(IMultisigControl(multisig_control_address()).verify_signatures(signatures, message, nonce), "bad signatures"); withdraw_thresholds[asset_source] = threshold; } /// @notice This view returns the given token's withdraw threshold above which the withdraw delay goes into effect /// @param asset_source Contract address for given ERC20 token /// @return Withdraw threshold function get_withdraw_threshold(address asset_source) public override view returns(uint256) { return withdraw_thresholds[asset_source]; } /// @notice This function triggers the global bridge stop that halts all withdrawals and deposits until it is resumed /// @param nonce Vega-assigned single-use number that provides replay attack protection /// @param signatures Vega-supplied signature bundle of a validator-signed order /// @dev bridge must not be stopped already /// @dev emits Bridge_Stopped if successful function global_stop(uint256 nonce, bytes calldata signatures) public override { require(!is_stopped, "bridge already stopped"); bytes memory message = abi.encode(nonce, 'global_stop'); require(IMultisigControl(multisig_control_address()).verify_signatures(signatures, message, nonce), "bad signatures"); is_stopped = true; emit Bridge_Stopped(); } /// @notice This function resumes bridge operations from the stopped state /// @param nonce Vega-assigned single-use number that provides replay attack protection /// @param signatures Vega-supplied signature bundle of a validator-signed order /// @dev bridge must be stopped /// @dev emits Bridge_Resumed if successful function global_resume(uint256 nonce, bytes calldata signatures) public override { require(is_stopped, "bridge not stopped"); bytes memory message = abi.encode(nonce, 'global_resume'); require(IMultisigControl(multisig_control_address()).verify_signatures(signatures, message, nonce), "bad signatures"); is_stopped = false; emit Bridge_Resumed(); } /// @notice this function allows MultisigControl to set the address that can exempt depositors from the deposit limits /// @notice this feature is specifically for liquidity and rewards providers /// @param lister The address that can exempt depositors /// @param nonce Vega-assigned single-use number that provides replay attack protection /// @param signatures Vega-supplied signature bundle of a validator-signed order /// @dev emits Exemption_Lister_Set if successful function set_exemption_lister(address lister, uint256 nonce, bytes calldata signatures) public override{ bytes memory message = abi.encode(lister, nonce, 'set_exemption_lister'); require(IMultisigControl(multisig_control_address()).verify_signatures(signatures, message, nonce), "bad signatures"); exemption_lister = lister; emit Exemption_Lister_Set(lister); } /// @notice this function allows the exemption_lister to exempt a depositor from the deposit limits /// @notice this feature is specifically for liquidity and rewards providers /// @param depositor The depositor to exempt from limits /// @dev emits Depositor_Exempted if successful function exempt_depositor(address depositor) public override { require(depositor != address(0), "cannot exempt zero address"); require(!exempt_depositors[depositor], "depositor already exempt"); require(msg.sender == exemption_lister, "unauthorized exemption lister"); exempt_depositors[depositor] = true; emit Depositor_Exempted(depositor); } /// @notice this function allows the exemption_lister to revoke a depositor's exemption from deposit limits /// @notice this feature is specifically for liquidity and rewards providers /// @param depositor The depositor from which to revoke deposit exemptions /// @dev emits Depositor_Exemption_Revoked if successful function revoke_exempt_depositor(address depositor) public override { require(msg.sender == exemption_lister, "unauthorized exemption lister"); require(exempt_depositors[depositor], "depositor not exempt"); exempt_depositors[depositor] = false; emit Depositor_Exemption_Revoked(depositor); } /// @notice this view returns the address that can exempt depositors from deposit limits /// @return the address can exempt depositors from deposit limits function get_exemption_lister() public override view returns(address) { return exemption_lister; } /// @notice this view returns true if the given despoitor address has been exempted from deposit limits /// @param depositor The depositor to check /// @return true if depositor is exempt function is_exempt_depositor(address depositor) public override view returns(bool) { return exempt_depositors[depositor]; } /***********************END RESTRICTIONS*************************/ /// @notice This function withdrawals assets to the target Ethereum address /// @param asset_source Contract address for given ERC20 token /// @param amount Amount of ERC20 tokens to withdraw /// @param target Target Ethereum address to receive withdrawn ERC20 tokens /// @param creation Timestamp of when requestion was created *RESTRICTION FEATURE* /// @param nonce Vega-assigned single-use number that provides replay attack protection /// @param signatures Vega-supplied signature bundle of a validator-signed order /// @notice See MultisigControl for more about signatures /// @dev Emits Asset_Withdrawn if successful function withdraw_asset(address asset_source, uint256 amount, address target, uint256 creation, uint256 nonce, bytes memory signatures) public override{ require(!is_stopped, "bridge stopped"); require(withdraw_thresholds[asset_source] > amount || creation + default_withdraw_delay <= block.timestamp, "large withdraw is not old enough"); bytes memory message = abi.encode(asset_source, amount, target, creation, nonce, 'withdraw_asset'); require(IMultisigControl(multisig_control_address()).verify_signatures(signatures, message, nonce), "bad signatures"); ERC20_Asset_Pool(erc20_asset_pool_address).withdraw(asset_source, target, amount); emit Asset_Withdrawn(target, asset_source, amount, nonce); } /// @notice This function allows a user to deposit given ERC20 tokens into Vega /// @param asset_source Contract address for given ERC20 token /// @param amount Amount of tokens to be deposited into Vega /// @param vega_public_key Target Vega public key to be credited with this deposit /// @dev emits Asset_Deposited if successful /// @dev ERC20 approve function should be run before running this /// @notice ERC20 approve function should be run before running this function deposit_asset(address asset_source, uint256 amount, bytes32 vega_public_key) public override { require(!is_stopped, "bridge stopped"); require(exempt_depositors[msg.sender] || user_lifetime_deposits[msg.sender][asset_source] + amount <= asset_deposit_lifetime_limit[asset_source], "deposit over lifetime limit"); require(listed_tokens[asset_source], "asset not listed"); //User must run approve before deposit require(maximum_deposits[asset_source] == 0 || amount <= maximum_deposits[asset_source], "deposit above maximum"); require(amount >= minimum_deposits[asset_source], "deposit below minimum"); require(IERC20(asset_source).transferFrom(msg.sender, erc20_asset_pool_address, amount), "transfer failed in deposit"); user_lifetime_deposits[msg.sender][asset_source] += amount; emit Asset_Deposited(msg.sender, asset_source, amount, vega_public_key); } /***************************VIEWS*****************************/ /// @notice This view returns true if the given ERC20 token contract has been listed valid for deposit /// @param asset_source Contract address for given ERC20 token /// @return True if asset is listed function is_asset_listed(address asset_source) public override view returns(bool){ return listed_tokens[asset_source]; } /// @notice This view returns minimum valid deposit /// @param asset_source Contract address for given ERC20 token /// @return Minimum valid deposit of given ERC20 token function get_deposit_minimum(address asset_source) public override view returns(uint256){ return minimum_deposits[asset_source]; } /// @notice This view returns maximum valid deposit /// @param asset_source Contract address for given ERC20 token /// @return Maximum valid deposit of given ERC20 token function get_deposit_maximum(address asset_source) public override view returns(uint256){ return maximum_deposits[asset_source]; } /// @return current multisig_control_address function get_multisig_control_address() public override view returns(address) { return multisig_control_address(); } /// @param asset_source Contract address for given ERC20 token /// @return The assigned Vega Asset Id for given ERC20 token function get_vega_asset_id(address asset_source) public override view returns(bytes32){ return asset_source_to_vega_asset_id[asset_source]; } /// @param vega_asset_id Vega-assigned asset ID for which you want the ERC20 token address /// @return The ERC20 token contract address for a given Vega Asset Id function get_asset_source(bytes32 vega_asset_id) public override view returns(address){ return vega_asset_ids_to_source[vega_asset_id]; } } /** MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMWEMMMMMMMMMMMMMMMMMMMMMMMMMM...............MMMMMMMMMMMMM MMMMMMLOVEMMMMMMMMMMMMMMMMMMMMMM...............MMMMMMMMMMMMM MMMMMMMMMMHIXELMMMMMMMMMMMM....................MMMMMNNMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMM....................MMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMM88=........................+MMMMMMMMMM MMMMMMMMMMMMMMMMM....................MMMMM...MMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMM....................MMMMM...MMMMMMMMMMMMMMM MMMMMMMMMMMM.........................MM+..MMM....+MMMMMMMMMM MMMMMMMMMNMM...................... ..MM?..MMM.. .+MMMMMMMMMM MMMMNDDMM+........................+MM........MM..+MMMMMMMMMM MMMMZ.............................+MM....................MMM MMMMZ.............................+MM....................MMM MMMMZ.............................+MM....................DDD MMMMZ.............................+MM..ZMMMMMMMMMMMMMMMMMMMM MMMMZ.............................+MM..ZMMMMMMMMMMMMMMMMMMMM MM..............................MMZ....ZMMMMMMMMMMMMMMMMMMMM MM............................MM.......ZMMMMMMMMMMMMMMMMMMMM MM............................MM.......ZMMMMMMMMMMMMMMMMMMMM MM......................ZMMMMM.......MMMMMMMMMMMMMMMMMMMMMMM MM............... ......ZMMMMM.... ..MMMMMMMMMMMMMMMMMMMMMMM MM...............MMMMM88~.........+MM..ZMMMMMMMMMMMMMMMMMMMM MM.......$DDDDDDD.......$DDDDD..DDNMM..ZMMMMMMMMMMMMMMMMMMMM MM.......$DDDDDDD.......$DDDDD..DDNMM..ZMMMMMMMMMMMMMMMMMMMM MM.......ZMMMMMMM.......ZMMMMM..MMMMM..ZMMMMMMMMMMMMMMMMMMMM MMMMMMMMM+.......MMMMM88NMMMMM..MMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMM+.......MMMMM88NMMMMM..MMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM*/
this function allows the exemption_lister to exempt a depositor from the deposit limits this feature is specifically for liquidity and rewards providers depositor The depositor to exempt from limits emits Depositor_Exempted if successful
function exempt_depositor(address depositor) public override { require(depositor != address(0), "cannot exempt zero address"); require(!exempt_depositors[depositor], "depositor already exempt"); require(msg.sender == exemption_lister, "unauthorized exemption lister"); exempt_depositors[depositor] = true; emit Depositor_Exempted(depositor); }
12,891,044
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC1155/extensions/IERC1155MetadataURI.sol"; import "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol"; import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165Storage.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "./IERC2981.sol"; import "./common/meta-transactions/ContentMixin.sol"; import "./common/meta-transactions/NativeMetaTransaction.sol"; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @title ERC721Tradable * ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality. */ contract ERC1155Tradable is ContextMixin, ERC1155Supply, Ownable, NativeMetaTransaction, IERC2981 { using SafeMath for uint256; address proxyRegistryAddress; uint256 private _currentTokenId; // The next tokenid to be minted mapping(uint256 => string) private _CIDS; mapping(uint256 => address payable) private royaltyBeneficiaries; mapping(uint256 => uint96) private royaltyBasisPoints; constructor( address _proxyRegistryAddress ) ERC1155("ipfs://") { proxyRegistryAddress = _proxyRegistryAddress; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, IERC2981) returns (bool) { return // Register erc2981 royalty compatibility interfaceId == type(IERC2981).interfaceId || // register raribly royalty compatibility interfaceId == bytes4(keccak256('getRaribleV2Royalties(uint256)')) || super.supportsInterface(interfaceId); } /** * @dev Mints a token to an address with a tokenURI. * @param _to address of the future owner of the token */ function mintTo(address _to, uint256 _amount, string memory _CID ) public { uint256 newTokenId = _getNextTokenId(); _CIDS[newTokenId] = _CID; _mint(_to, newTokenId, _amount, ""); _incrementTokenId(); } function mintToWithRoyalty(address _to, uint256 _amount, string memory _CID, address payable beneficiary, uint32 bps) external { uint256 newTokenId = _getNextTokenId(); royaltyBeneficiaries[newTokenId] = beneficiary; royaltyBasisPoints[newTokenId] = bps; mintTo(_to, _amount, _CID); } /** * Rarible specific royalties * @param id tokenid to lookup */ function getRaribleV2Royalties(uint256 id) external view returns (address payable, uint96){ return (royaltyBeneficiaries[id], royaltyBasisPoints[id]); } /** * EIP2981 Royalties * @param _tokenId tokenid to lookup * @param _salePrice price of the sale (unitless, could be any currency) */ function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external override view returns ( address receiver, uint256 royaltyAmount ) { return (royaltyBeneficiaries[_tokenId], (royaltyBasisPoints[_tokenId]*_salePrice)/10000); } /** * @dev calculates the next token ID based on value of _currentTokenId * @return uint256 for the next token ID */ function _getNextTokenId() private view returns (uint256) { return _currentTokenId.add(1); } /** * @dev increments the value of _currentTokenId */ function _incrementTokenId() private { _currentTokenId++; } function uri(uint256 _tokenId) override public view returns (string memory) { return string(abi.encodePacked(string("ipfs://"), _CIDS[_tokenId], string("/metadata.json"))); } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) override public view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } /** * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea. */ function _msgSender() internal override view returns (address sender) { return ContextMixin.msgSender(); } }
Mints a token to an address with a tokenURI. _to address of the future owner of the token/
function mintTo(address _to, uint256 _amount, string memory _CID ) public { uint256 newTokenId = _getNextTokenId(); _CIDS[newTokenId] = _CID; _mint(_to, newTokenId, _amount, ""); _incrementTokenId(); }
12,882,342
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title A base MisBlock token contract /// @author Anderson L /// @notice This contract is inherited by MisBlockETH and MisBlockBSC token contracts. /// @dev All functions requiring onlyOwner are also pausable. import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import '@openzeppelin/contracts/access/Ownable.sol'; import "@openzeppelin/contracts/utils/Address.sol"; import '@openzeppelin/contracts/security/Pausable.sol'; import "./interfaces/UniswapInterfaces.sol"; contract MisBlockBase is ERC20, Pausable, Ownable { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _tokenAllowances; mapping (address => bool) private _isExcludedFromFee; mapping (address => bool) private _isExcluded; address[] private _excluded; uint256 private constant MAX = ~uint256(0) / 1000; uint256 private _tTotal = 0; uint256 private _rTotal = 0; uint256 private _tFeeTotal; uint256 public deployTime = block.timestamp; uint256 public taxFee; uint256 public liquidityFee; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; mapping (address => bool) private _isMintAvailable; address[] private _mintAvailableAddresses; mapping (address => bool) private _isBurnAvailable; address[] private _burnAvailableAddresses; // Should re-set following 2 values as our token's requirement. uint256 public maxTxAmount = 5000000 ether; uint256 private constant TOKEN_SELL_TO_LIQUIDITY = 500000 ether; event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); event TransferForVesting(address recipient, uint256 amount); event Mint(address account, uint256 amount); event AllocateVesting(address indexed vestingContract, uint256 amount, uint256 timestamp); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } struct LockFund { uint256 amount; uint256 releasetime; } mapping (address => bool) public isSwapAddress; address[] public swapAddresses; mapping (address => LockFund[]) private _lockFundsArray; /// @notice Constructor. The token name is UNICOIN and the symbol name is UNICN. /// @dev Should input swapaddress as PCS router address in BSC contract and UNISWAP router addres in ETH contract. /// @param swapaddress An address of pcs or uniswap router contract. /// @param initialMintAmount An address of pcs or uniswap router contract. constructor(address swapaddress, uint256 initialMintAmount) ERC20("UNICOIN", "UNICN") { _tTotal = initialMintAmount; _rTotal = MAX.sub(MAX.mod(_tTotal)); _rOwned[_msgSender()] = _rTotal; // Uniswap Address should be in SwapAddress list isSwapAddress[swapaddress] = true; swapAddresses.push(swapaddress); // Owner should be in burn/mint available list _isMintAvailable[_msgSender()] = true; _mintAvailableAddresses.push(_msgSender()); _isBurnAvailable[_msgSender()] = true; _burnAvailableAddresses.push(_msgSender()); //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(swapaddress); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); emit Transfer(address(0), _msgSender(), _tTotal); } /** * @notice Throws if called by any account other than mint available addresses. */ modifier onlyMintAvailable() { require(_isMintAvailable[_msgSender()], "caller is not in the mint available list"); _; } /** * @notice Throws if called by any account other than burn available addresses. */ modifier onlyBurnAvailable() { require(_isBurnAvailable[_msgSender()], "caller is not in the burn available list"); _; } /** * @notice add mint available address */ function addMintAvailableAddress(address account) external onlyOwner whenNotPaused { require(!_isMintAvailable[account], "Account is already in list of mint available addresses"); _isMintAvailable[account] = true; _mintAvailableAddresses.push(account); } /** * @notice remove mint available address */ function removeMintAvailableAddress(address account) external onlyOwner whenNotPaused { require(_isMintAvailable[account] == true, "Account is not in list of mint available addresses"); for (uint256 i = 0; i < _mintAvailableAddresses.length; i++) { if (_mintAvailableAddresses[i] == account) { _mintAvailableAddresses[i] = _mintAvailableAddresses[_mintAvailableAddresses.length - 1]; _isMintAvailable[account] = false; _mintAvailableAddresses.pop(); break; } } } /** * @notice add burn available address */ function addBurnAvailableAddress(address account) external onlyOwner whenNotPaused { require(!_isBurnAvailable[account], "Account is already in list of burn available addresses"); _isBurnAvailable[account] = true; _burnAvailableAddresses.push(account); } /** * @notice remove burn available address */ function removeBurnAvailableAddress(address account) external onlyOwner whenNotPaused { require(_isBurnAvailable[account] == true, "Account is not in list of burn available addresses"); for (uint256 i = 0; i < _burnAvailableAddresses.length; i++) { if (_burnAvailableAddresses[i] == account) { _burnAvailableAddresses[i] = _burnAvailableAddresses[_burnAvailableAddresses.length - 1]; _isBurnAvailable[account] = false; _burnAvailableAddresses.pop(); break; } } } /// @notice We are despositing 1T tokens initially and allowing to mint 9T tokens more. This function can be called by only owner. function mint(address account, uint256 amount) external onlyMintAvailable whenNotPaused { _mint(account, amount); emit Mint(account, amount); } /// @dev We should check reflection value should not be overr uint256's max value. function _mint(address account, uint256 amount) internal override virtual { require(account != address(0), "ERC20: mint to the zero address"); (uint256 rAmount,,,,,) = _getValues(amount); require((~uint256(0) - rAmount) > _rTotal , "Mint value is exceeded limitation"); _rOwned[account] = _rOwned[account].add(rAmount); if(_isExcluded[account]) { _tOwned[account] = _tOwned[account].add(amount); } _rTotal += rAmount; _tTotal += amount; } /// @notice Getting totalSupply. function totalSupply() public view override returns (uint256) { return _tTotal; } /** * @notice Getting balance of the account. * @dev Checking the account is including in Reward List or not. */ function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } /** * @dev Checking whether the account is contract address or not. */ // function isContract(address account) internal view returns (bool) { // uint32 size; // assembly { // size := extcodesize(account) // } // return (size > 0); // } /** * @notice This function is standard transfer function. * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Taking fees and set timelock by proper logic. * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) public override returns (bool) { _transferBase(_msgSender(), recipient, amount); return true; } /** * @notice This function is to getting allowance of spender. * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `sender` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address sender, address spender) public view override returns (uint256) { return _tokenAllowances[sender][spender]; } /** * @notice This function is to approve transfer. * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) public override returns (bool) { _approveBase(_msgSender(), spender, amount); return true; } /** * @notice This function is for delegating transfer. * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { require(sender != recipient, "sender and recipient is same address"); _transferBase(sender, recipient, amount); _approveBase(sender, _msgSender(), _tokenAllowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @notice This function is to increase allowance. * @dev Adds `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * Emits an {Approval} event. */ function increaseAllowance(address spender, uint256 addedValue) public override virtual returns (bool) { _approveBase(_msgSender(), spender, _tokenAllowances[_msgSender()][spender].add(addedValue)); return true; } /** * @notice This function is to decrease allowance. * @dev Subs `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * Emits an {Approval} event. */ function decreaseAllowance(address spender, uint256 subtractedValue) public override virtual returns (bool) { _approveBase(_msgSender(), spender, _tokenAllowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @notice This function is to check whether the account is excluded from reward or not. * @dev Check the account is excluded from reward or not. * * Returns a boolean value indicating whether the account is excluded from reward or not. * */ function isExcludedFromReward(address account) external view returns (bool) { return _isExcluded[account]; } /** * @notice Get total Fees taken by taxes. */ function totalFees() external view returns (uint256) { return _tFeeTotal; } /** * @notice This function is to deliver tokens to account holders. */ function deliver(uint256 tAmount) external { address sender = _msgSender(); require(!_isExcluded[sender], "Excluded addresses cannot call this function"); (uint256 rAmount,,,,,) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tAmount); } /** * @notice Getting reflection value from token value. */ function reflectionFromToken(uint256 tAmount, bool deductTransferFee) external view returns(uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tAmount); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tAmount); return rTransferAmount; } } /** * @notice Getting token value from reflection value. */ function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "Amount must be less than total reflections"); uint256 currentRate = _getRate(); return rAmount.div(currentRate); } /** * @notice exclude the account from the reward list. * * Must be called from only owner. * */ function excludeFromReward(address account) external onlyOwner whenNotPaused { // require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.'); require(!_isExcluded[account], "Account is already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } /** * @notice include the account into the reward list. * * Must be called from only owner. * */ function includeInReward(address account) external onlyOwner whenNotPaused { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } /** * @notice exclude the account from the taking fee. taxes are not applied for accounts from this list. * * Must be called from only owner. * */ function excludeFromFee(address account) external onlyOwner whenNotPaused { _isExcludedFromFee[account] = true; } /** * @notice include the account into the taking fee. taxes would be applied for accounts from this list. * * Must be called from only owner. * */ function includeInFee(address account) external onlyOwner { _isExcludedFromFee[account] = false; } /** * @notice setting maximum transfer amount as percentage. * * Must be called from only owner. * */ function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner whenNotPaused { maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**2 ); } /** * @notice enable/disable Swap and Liquidity feature. * * Must be called from only owner. * */ function setSwapAndLiquifyEnabled(bool enabled) external onlyOwner whenNotPaused { swapAndLiquifyEnabled = enabled; emit SwapAndLiquifyEnabledUpdated(enabled); } /** * @notice burn tokens from the account. * * Must be called from only owner. * */ function burn(address account, uint256 tAmount) external onlyBurnAvailable whenNotPaused { uint256 burnerBalance = balanceOf(account); require(burnerBalance >= tAmount, "Burnning amount is exceed balance"); (uint256 rAmount, , , , , ) = _getValues(tAmount); _rOwned[account] = _rOwned[account].sub(rAmount); if(_isExcluded[account]) { _tOwned[account] = _tOwned[account].sub(tAmount); } _rTotal = _rTotal.sub(rAmount); _tTotal = _tTotal.sub(tAmount); } /** * @dev Inspired from Reflect Finance concept. * to recieve ETH from uniswapV2Router when swaping */ receive() external payable {} /** * @dev applying fees. called by transfer functions. * * Internal function. * */ function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } /** * @dev Internal function to get values related with reflection feature based on transfer amount. * - rAmount : reflection amount for tAmount * - rTransferAmount : reflection amount for tTransferAmount * - rFee : reflection amount for tFee * - tTransferAmount : transfer amount without all taxes(fee and liquidity) * - tFee : tax fee for account holders * - tLiquidity : tax fee for liquidity */ function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } /** * @dev Internal function to get token values based on transfer amount. called by {_getValues} * - tTransferAmount : transfer amount without all taxes(fee and liquidity) * - tFee : tax fee for account holders * - tLiquidity : tax fee for liquidity */ function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } /** * @dev Internal function to get reflection values based on token values. called by {_getValues} * - rAmount : reflection amount for tAmount * - rTransferAmount : reflection amount for tTransferAmount * - rFee : reflection amount for tFee */ function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tAmount.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } /** * @dev Internal function to get rate between token and reflection value */ function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } /** * @dev Internal function to get total Supply of token and reflection. called by {_getRate} */ function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } /** * @dev Internal function to to apply liquidity fee. */ function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } /** * @dev Internal function to calculate tax fee. Used 1000 instead of 100 for max percent to avoid decimals. For example, 7.5% will be calculated by 75/1000 */ function calculateTaxFee(uint256 amount) private view returns (uint256) { return amount.mul(taxFee).div( 10**3 ); } /** * @dev Internal function to calculate liquidity fee. Used 1000 instead of 100 for max percent to avoid decimals. For example, 7.5% will be calculated by 75/1000 */ function calculateLiquidityFee(uint256 amount) private view returns (uint256) { return amount.mul(liquidityFee).div( 10**3 ); } /** * @dev Internal function to set tax fees. * First Month : 7.5%, Second Month : 5%, Third Month : 2.5%, From Fourth Month : 0 */ function _setTaxFee(bool takeFee) private { if (!takeFee) { taxFee = 0; liquidityFee = 0; } else if ( block.timestamp < deployTime + 30 days) { taxFee = 75; liquidityFee = 75; } else if ( block.timestamp < deployTime + 60 days) { taxFee = 50; liquidityFee = 50; } else if ( block.timestamp < deployTime + 90 days) { taxFee = 25; liquidityFee = 25; } else { taxFee = 0; liquidityFee = 0; } } /** * @notice Checking whether the address is excluded from fee or not */ function isExcludedFromFee(address account) external view returns(bool) { return _isExcludedFromFee[account]; } /** * @dev Internal function to approve. * Emits a {Approval} event. */ function _approveBase(address sender, address spender, uint256 amount) private { require(sender != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _tokenAllowances[sender][spender] = amount; emit Approval(sender, spender, amount); } /** * @dev Internal function for standard transfer. */ function _transferBase( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(from != owner() && to != owner()) require(amount <= maxTxAmount, "Transfer amount exceeds the maxTxAmount."); uint256 senderBalance = balanceOf(from); require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); //indicates if fee should be deducted from transfer bool takeFee = true; //if from address is not in SwapAddress list, not taking fee if(!isSwapAddress[from]){ takeFee = false; } //if any account belongs to _isExcludedFromFee account then remove the fee if(_isExcludedFromFee[from] || _isExcludedFromFee[to]){ takeFee = false; } //it will check timelock _beforeTokenTransferBase(from, amount); //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); //it will calculate timelock _afterTokenTransferBase(from, to, amount); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= maxTxAmount) { contractTokenBalance = maxTxAmount; } bool overMinTokenBalance = contractTokenBalance >= TOKEN_SELL_TO_LIQUIDITY; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { contractTokenBalance = TOKEN_SELL_TO_LIQUIDITY; //add liquidity swapAndLiquify(contractTokenBalance); } } /** * @dev Internal function of swap feature. * Emits {SwapAndLiquify} */ function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // split the contract balance into halves uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity to uniswap addLiquidity(otherHalf, newBalance); } /** * @dev Internal function for swapTokensForEth. */ function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approveBase(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } /** * @dev Internal function for addLiquidity. */ function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approveBase(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity (uint token, uint eth, uint liquidity) = uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); emit SwapAndLiquify(token, eth, liquidity); } /** * @dev Internal function of transfer. * this method is responsible for taking all fee, if takeFee is true */ function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { _setTaxFee(takeFee); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } } /** * @dev called in case of both of sender and recipient are in reward list. */ function _transferStandard(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } /** * @dev called in case of only sender is in reward list. */ function _transferToExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } /** * @dev called in case of only recipient is in reward list. */ function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } /** * @dev called in case of both are not in reward list. */ function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount); _tOwned[sender] = _tOwned[sender].sub(tAmount); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); emit Transfer(sender, recipient, tTransferAmount); } /** * @notice getting the list of addresses set as applying timelock from. All tokens transfered from addresses of this list is time locked by proper logic. */ function getSwapAddresses() external view returns (address[] memory){ return swapAddresses; } /** * @notice add swap address */ function addSwapAddress(address account) external onlyOwner whenNotPaused { require(!isSwapAddress[account], "Account is already in list of swap addresses"); isSwapAddress[account] = true; swapAddresses.push(account); } /** * @notice remove swap address */ function removeSwapAddress(address account) external onlyOwner whenNotPaused { require(isSwapAddress[account] == true, "Account is not in list of swap addresses"); for (uint256 i = 0; i < swapAddresses.length; i++) { if (swapAddresses[i] == account) { swapAddresses[i] = swapAddresses[swapAddresses.length - 1]; isSwapAddress[account] = false; swapAddresses.pop(); break; } } } /** * @dev Internal function to be called before token transfer. * Check time locked funds. * If the address is having 1000 tokens. And 500 tokens were time locked. * At this point if the account wants to transfer 600 tokens, then it will be reverted since the user is having only 500 tokens available. */ function _beforeTokenTransferBase( address from, uint256 amount ) private view { LockFund[] storage lockFunds = _lockFundsArray[from]; if(lockFunds.length < 1) return; uint256 lockedFundsSum = 0; for (uint i = 0; i < lockFunds.length; i++) { if(lockFunds[i].releasetime > block.timestamp) { lockedFundsSum += lockFunds[i].amount; } } require(balanceOf(from) - lockedFundsSum >= amount, "Some of your balances were locked. And you don't have enough unlocked balance for this transaction."); } /** * @dev Internal function to be called after token transfer. * Applying time lock against tokens transferred from addresses in the timelock list */ function _afterTokenTransferBase( address from, address to, uint256 amount ) private { if(!isSwapAddress[from]) return; LockFund[] storage lockFunds = _lockFundsArray[to]; lockFunds.push(LockFund(amount.div(10), block.timestamp + 1 days)); for (uint256 i = 1; i < 10; i++) { lockFunds.push(LockFund(amount.div(10), block.timestamp + 1 days + i * 1 weeks)); } } }
enable/disable Swap and Liquidity feature. Must be called from only owner./
function setSwapAndLiquifyEnabled(bool enabled) external onlyOwner whenNotPaused { swapAndLiquifyEnabled = enabled; emit SwapAndLiquifyEnabledUpdated(enabled); }
5,426,048
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.8.0 <0.9.0; library BLS { // Field order uint256 constant N = 21888242871839275222246405745257275088696311157297823662689037894645226208583; // Negated genarator of G2 uint256 constant nG2x1 = 11559732032986387107991004021392285783925812861821192530917403151452391805634; uint256 constant nG2x0 = 10857046999023057135944570762232829481370756359578518086990519993285655852781; uint256 constant nG2y1 = 17805874995975841540914202342111839520379459829704422454583296818431106115052; uint256 constant nG2y0 = 13392588948715843804641432497768002650278120570034223513918757245338268106653; uint256 constant FIELD_MASK = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; uint256 constant SIGN_MASK = 0x8000000000000000000000000000000000000000000000000000000000000000; uint256 constant ODD_NUM = 0x8000000000000000000000000000000000000000000000000000000000000000; function verifySingle( uint256[2] memory signature, uint256[4] memory pubkey, uint256[2] memory message ) public view returns (bool) { uint256[12] memory input = [ signature[0], signature[1], nG2x1, nG2x0, nG2y1, nG2y0, message[0], message[1], pubkey[1], pubkey[0], pubkey[3], pubkey[2] ]; uint256[1] memory out; bool success; // solium-disable-next-line security/no-inline-assembly assembly { success := staticcall(sub(gas(), 2000), 8, input, 384, out, 0x20) switch success case 0 { invalid() } } require(success, ""); return out[0] != 0; } function verifyMultiple( uint256[2] memory signature, uint256[4][] memory pubkeys, uint256[2][] memory messages ) internal view returns (bool) { uint256 size = pubkeys.length; require(size > 0, "BLS: number of public key is zero"); require( size == messages.length, "BLS: number of public keys and messages must be equal" ); uint256 inputSize = (size + 1) * 6; uint256[] memory input = new uint256[](inputSize); input[0] = signature[0]; input[1] = signature[1]; input[2] = nG2x1; input[3] = nG2x0; input[4] = nG2y1; input[5] = nG2y0; for (uint256 i = 0; i < size; i++) { input[i * 6 + 6] = messages[i][0]; input[i * 6 + 7] = messages[i][1]; input[i * 6 + 8] = pubkeys[i][1]; input[i * 6 + 9] = pubkeys[i][0]; input[i * 6 + 10] = pubkeys[i][3]; input[i * 6 + 11] = pubkeys[i][2]; } uint256[1] memory out; bool success; // solium-disable-next-line security/no-inline-assembly assembly { success := staticcall( sub(gas(), 2000), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20 ) switch success case 0 { invalid() } } require(success, ""); return out[0] != 0; } function hashToPoint(bytes memory data) internal view returns (uint256[2] memory p) { return mapToPoint(keccak256(data)); } function mapToPoint(bytes32 _x) public view returns (uint256[2] memory p) { uint256 x = uint256(_x) % N; uint256 y; bool found = false; while (true) { y = mulmod(x, x, N); y = mulmod(y, x, N); y = addmod(y, 3, N); (y, found) = sqrt(y); if (found) { p[0] = x; p[1] = y; break; } x = addmod(x, 1, N); } } function mapToPointWithHelp(bytes32 _x, uint256[] memory expected_roots) public pure returns (uint256[2] memory p) { uint256 x = uint256(_x) % N; uint8 i = 0; uint256 y; uint256 m; while (true) { y = mulmod(x, x, N); y = mulmod(y, x, N); y = addmod(y, 3, N); m = mulmod(expected_roots[i],expected_roots[i], N); if (m == y) { p[0] = x; p[1] = expected_roots[i]; break; } else if (N-m == y) { x = addmod(x, 1, N); i += 1; } else { revert("Wrong expected root."); } } } function isValidPublicKey(uint256[4] memory publicKey) internal pure returns (bool) { if ( (publicKey[0] >= N) || (publicKey[1] >= N) || (publicKey[2] >= N || (publicKey[3] >= N)) ) { return false; } else { return isOnCurveG2(publicKey); } } function isValidSignature(uint256[2] memory signature) internal pure returns (bool) { if ((signature[0] >= N) || (signature[1] >= N)) { return false; } else { return isOnCurveG1(signature); } } function pubkeyToUncompressed( uint256[2] memory compressed, uint256[2] memory y ) internal pure returns (uint256[4] memory uncompressed) { uint256 decision = compressed[0] & SIGN_MASK; require( decision == ODD_NUM || y[0] & 1 != 1, "BLS: bad y coordinate for uncompressed key" ); uncompressed[0] = compressed[0] & FIELD_MASK; uncompressed[1] = compressed[1]; uncompressed[2] = y[0]; uncompressed[3] = y[1]; } function signatureToUncompressed(uint256 compressed, uint256 y) internal pure returns (uint256[2] memory uncompressed) { uint256 decision = compressed & SIGN_MASK; require( decision == ODD_NUM || y & 1 != 1, "BLS: bad y coordinate for uncompressed key" ); return [compressed & FIELD_MASK, y]; } function isValidCompressedPublicKey(uint256[2] memory publicKey) internal view returns (bool) { uint256 x0 = publicKey[0] & FIELD_MASK; uint256 x1 = publicKey[1]; if ((x0 >= N) || (x1 >= N)) { return false; } else if ((x0 == 0) && (x1 == 0)) { return false; } else { return isOnCurveG2([x0, x1]); } } function isValidCompressedSignature(uint256 signature) internal view returns (bool) { uint256 x = signature & FIELD_MASK; if (x >= N) { return false; } else if (x == 0) { return false; } return isOnCurveG1(x); } function isOnCurveG1(uint256[2] memory point) internal pure returns (bool _isOnCurve) { // solium-disable-next-line security/no-inline-assembly assembly { let t0 := mload(point) let t1 := mload(add(point, 32)) let t2 := mulmod(t0, t0, N) t2 := mulmod(t2, t0, N) t2 := addmod(t2, 3, N) t1 := mulmod(t1, t1, N) _isOnCurve := eq(t1, t2) } } function isOnCurveG1(uint256 x) internal view returns (bool _isOnCurve) { bool callSuccess; // solium-disable-next-line security/no-inline-assembly assembly { let t0 := x let t1 := mulmod(t0, t0, N) t1 := mulmod(t1, t0, N) t1 := addmod(t1, 3, N) let freemem := mload(0x40) mstore(freemem, 0x20) mstore(add(freemem, 0x20), 0x20) mstore(add(freemem, 0x40), 0x20) mstore(add(freemem, 0x60), t1) // (N - 1) / 2 = 0x183227397098d014dc2822db40c0ac2ecbc0b548b438e5469e10460b6c3e7ea3 mstore( add(freemem, 0x80), 0x183227397098d014dc2822db40c0ac2ecbc0b548b438e5469e10460b6c3e7ea3 ) // N = 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47 mstore( add(freemem, 0xA0), 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47 ) callSuccess := staticcall( sub(gas(), 2000), 5, freemem, 0xC0, freemem, 0x20 ) _isOnCurve := eq(1, mload(freemem)) } } function isOnCurveG2(uint256[4] memory point) internal pure returns (bool _isOnCurve) { // solium-disable-next-line security/no-inline-assembly assembly { // x0, x1 let t0 := mload(point) let t1 := mload(add(point, 32)) // x0 ^ 2 let t2 := mulmod(t0, t0, N) // x1 ^ 2 let t3 := mulmod(t1, t1, N) // 3 * x0 ^ 2 let t4 := add(add(t2, t2), t2) // 3 * x1 ^ 2 let t5 := addmod(add(t3, t3), t3, N) // x0 * (x0 ^ 2 - 3 * x1 ^ 2) t2 := mulmod(add(t2, sub(N, t5)), t0, N) // x1 * (3 * x0 ^ 2 - x1 ^ 2) t3 := mulmod(add(t4, sub(N, t3)), t1, N) // x ^ 3 + b t0 := addmod( t2, 0x2b149d40ceb8aaae81be18991be06ac3b5b4c5e559dbefa33267e6dc24a138e5, N ) t1 := addmod( t3, 0x009713b03af0fed4cd2cafadeed8fdf4a74fa084e52d1852e4a2bd0685c315d2, N ) // y0, y1 t2 := mload(add(point, 64)) t3 := mload(add(point, 96)) // y ^ 2 t4 := mulmod(addmod(t2, t3, N), addmod(t2, sub(N, t3), N), N) t3 := mulmod(shl(1, t2), t3, N) // y ^ 2 == x ^ 3 + b _isOnCurve := and(eq(t0, t4), eq(t1, t3)) } } function isOnCurveG2(uint256[2] memory x) internal view returns (bool _isOnCurve) { bool callSuccess; // solium-disable-next-line security/no-inline-assembly assembly { // x0, x1 let t0 := mload(add(x, 0)) let t1 := mload(add(x, 32)) // x0 ^ 2 let t2 := mulmod(t0, t0, N) // x1 ^ 2 let t3 := mulmod(t1, t1, N) // 3 * x0 ^ 2 let t4 := add(add(t2, t2), t2) // 3 * x1 ^ 2 let t5 := addmod(add(t3, t3), t3, N) // x0 * (x0 ^ 2 - 3 * x1 ^ 2) t2 := mulmod(add(t2, sub(N, t5)), t0, N) // x1 * (3 * x0 ^ 2 - x1 ^ 2) t3 := mulmod(add(t4, sub(N, t3)), t1, N) // x ^ 3 + b t0 := add( t2, 0x2b149d40ceb8aaae81be18991be06ac3b5b4c5e559dbefa33267e6dc24a138e5 ) t1 := add( t3, 0x009713b03af0fed4cd2cafadeed8fdf4a74fa084e52d1852e4a2bd0685c315d2 ) // is non residue ? t0 := addmod(mulmod(t0, t0, N), mulmod(t1, t1, N), N) let freemem := mload(0x40) mstore(freemem, 0x20) mstore(add(freemem, 0x20), 0x20) mstore(add(freemem, 0x40), 0x20) mstore(add(freemem, 0x60), t0) // (N - 1) / 2 = 0x183227397098d014dc2822db40c0ac2ecbc0b548b438e5469e10460b6c3e7ea3 mstore( add(freemem, 0x80), 0x183227397098d014dc2822db40c0ac2ecbc0b548b438e5469e10460b6c3e7ea3 ) // N = 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47 mstore( add(freemem, 0xA0), 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47 ) callSuccess := staticcall( sub(gas(), 2000), 5, freemem, 0xC0, freemem, 0x20 ) _isOnCurve := eq(1, mload(freemem)) } } function isNonResidueFP(uint256 e) internal view returns (bool isNonResidue) { bool callSuccess; // solium-disable-next-line security/no-inline-assembly assembly { let freemem := mload(0x40) mstore(freemem, 0x20) mstore(add(freemem, 0x20), 0x20) mstore(add(freemem, 0x40), 0x20) mstore(add(freemem, 0x60), e) // (N - 1) / 2 = 0x183227397098d014dc2822db40c0ac2ecbc0b548b438e5469e10460b6c3e7ea3 mstore( add(freemem, 0x80), 0x183227397098d014dc2822db40c0ac2ecbc0b548b438e5469e10460b6c3e7ea3 ) // N = 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47 mstore( add(freemem, 0xA0), 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47 ) callSuccess := staticcall( sub(gas(), 2000), 5, freemem, 0xC0, freemem, 0x20 ) isNonResidue := eq(1, mload(freemem)) } require(callSuccess, "BLS: isNonResidueFP modexp call failed"); return !isNonResidue; } function isNonResidueFP2(uint256[2] memory e) internal view returns (bool isNonResidue) { uint256 a = addmod(mulmod(e[0], e[0], N), mulmod(e[1], e[1], N), N); bool callSuccess; // solium-disable-next-line security/no-inline-assembly assembly { let freemem := mload(0x40) mstore(freemem, 0x20) mstore(add(freemem, 0x20), 0x20) mstore(add(freemem, 0x40), 0x20) mstore(add(freemem, 0x60), a) // (N - 1) / 2 = 0x183227397098d014dc2822db40c0ac2ecbc0b548b438e5469e10460b6c3e7ea3 mstore( add(freemem, 0x80), 0x183227397098d014dc2822db40c0ac2ecbc0b548b438e5469e10460b6c3e7ea3 ) // N = 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47 mstore( add(freemem, 0xA0), 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47 ) callSuccess := staticcall( sub(gas(), 2000), 5, freemem, 0xC0, freemem, 0x20 ) isNonResidue := eq(1, mload(freemem)) } require(callSuccess, "BLS: isNonResidueFP2 modexp call failed"); return !isNonResidue; } function sqrt(uint256 xx) internal view returns (uint256 x, bool hasRoot) { bool callSuccess; // solium-disable-next-line security/no-inline-assembly assembly { let freemem := mload(0x40) mstore(freemem, 0x20) mstore(add(freemem, 0x20), 0x20) mstore(add(freemem, 0x40), 0x20) mstore(add(freemem, 0x60), xx) // (N + 1) / 4 = 0xc19139cb84c680a6e14116da060561765e05aa45a1c72a34f082305b61f3f52 mstore( add(freemem, 0x80), 0xc19139cb84c680a6e14116da060561765e05aa45a1c72a34f082305b61f3f52 ) // N = 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47 mstore( add(freemem, 0xA0), 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47 ) callSuccess := staticcall( sub(gas(), 2000), 5, freemem, 0xC0, freemem, 0x20 ) x := mload(freemem) hasRoot := eq(xx, mulmod(x, x, N)) } require(callSuccess, "BLS: sqrt modexp call failed"); } }
solium-disable-next-line security/no-inline-assembly (N + 1) / 4 = 0xc19139cb84c680a6e14116da060561765e05aa45a1c72a34f082305b61f3f52 N = 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47
function sqrt(uint256 xx) internal view returns (uint256 x, bool hasRoot) { bool callSuccess; assembly { let freemem := mload(0x40) mstore(freemem, 0x20) mstore(add(freemem, 0x20), 0x20) mstore(add(freemem, 0x40), 0x20) mstore(add(freemem, 0x60), xx) mstore( add(freemem, 0x80), 0xc19139cb84c680a6e14116da060561765e05aa45a1c72a34f082305b61f3f52 ) mstore( add(freemem, 0xA0), 0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47 ) callSuccess := staticcall( sub(gas(), 2000), 5, freemem, 0xC0, freemem, 0x20 ) x := mload(freemem) hasRoot := eq(xx, mulmod(x, x, N)) } require(callSuccess, "BLS: sqrt modexp call failed"); }
2,504,711
pragma solidity ^0.4.13; interface ERC721Enumerable /* is ERC721 */ { /// @notice Count NFTs tracked by this contract /// @return A count of valid NFTs tracked by this contract, where each one of /// them has an assigned and queryable owner not equal to the zero address function totalSupply() public view returns (uint256); /// @notice Enumerate valid NFTs /// @dev Throws if `_index` >= `totalSupply()`. /// @param _index A counter less than `totalSupply()` /// @return The token identifier for the `_index`th NFT, /// (sort order not specified) function tokenByIndex(uint256 _index) external view returns (uint256); /// @notice Enumerate NFTs assigned to an owner /// @dev Throws if `_index` >= `balanceOf(_owner)` or if /// `_owner` is the zero address, representing invalid NFTs. /// @param _owner An address where we are interested in NFTs owned by them /// @param _index A counter less than `balanceOf(_owner)` /// @return The token identifier for the `_index`th NFT assigned to `_owner`, /// (sort order not specified) function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId); } interface ERC721Metadata /* is ERC721 */ { /// @notice A descriptive name for a collection of NFTs in this contract function name() external pure returns (string _name); /// @notice An abbreviated name for NFTs in this contract function symbol() external pure returns (string _symbol); /// @notice A distinct Uniform Resource Identifier (URI) for a given asset. /// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC /// 3986. The URI may point to a JSON file that conforms to the "ERC721 /// Metadata JSON Schema". function tokenURI(uint256 _tokenId) external view returns (string); } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0)); OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } interface ERC721TokenReceiver { /// @notice Handle the receipt of an NFT /// @dev The ERC721 smart contract calls this function on the recipient /// after a `transfer`. This function MAY throw to revert and reject the /// transfer. This function MUST use 50,000 gas or less. Return of other /// than the magic value MUST result in the transaction being reverted. /// Note: the contract address is always the message sender. /// @param _from The sending address /// @param _tokenId The NFT identifier which is being transfered /// @param _data Additional data with no specified format /// @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))` /// unless throwing function onERC721Received(address _from, uint256 _tokenId, bytes _data) external returns(bytes4); } library Math { function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract LicenseAccessControl { /** * @notice ContractUpgrade is the event that will be emitted if we set a new contract address */ event ContractUpgrade(address newContract); event Paused(); event Unpaused(); /** * @notice CEO's address FOOBAR */ address public ceoAddress; /** * @notice CFO's address */ address public cfoAddress; /** * @notice COO's address */ address public cooAddress; /** * @notice withdrawal address */ address public withdrawalAddress; bool public paused = false; /** * @dev Modifier to make a function only callable by the CEO */ modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /** * @dev Modifier to make a function only callable by the CFO */ modifier onlyCFO() { require(msg.sender == cfoAddress); _; } /** * @dev Modifier to make a function only callable by the COO */ modifier onlyCOO() { require(msg.sender == cooAddress); _; } /** * @dev Modifier to make a function only callable by C-level execs */ modifier onlyCLevel() { require( msg.sender == cooAddress || msg.sender == ceoAddress || msg.sender == cfoAddress ); _; } /** * @dev Modifier to make a function only callable by CEO or CFO */ modifier onlyCEOOrCFO() { require( msg.sender == cfoAddress || msg.sender == ceoAddress ); _; } /** * @dev Modifier to make a function only callable by CEO or COO */ modifier onlyCEOOrCOO() { require( msg.sender == cooAddress || msg.sender == ceoAddress ); _; } /** * @notice Sets a new CEO * @param _newCEO - the address of the new CEO */ function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /** * @notice Sets a new CFO * @param _newCFO - the address of the new CFO */ function setCFO(address _newCFO) external onlyCEO { require(_newCFO != address(0)); cfoAddress = _newCFO; } /** * @notice Sets a new COO * @param _newCOO - the address of the new COO */ function setCOO(address _newCOO) external onlyCEO { require(_newCOO != address(0)); cooAddress = _newCOO; } /** * @notice Sets a new withdrawalAddress * @param _newWithdrawalAddress - the address where we'll send the funds */ function setWithdrawalAddress(address _newWithdrawalAddress) external onlyCEO { require(_newWithdrawalAddress != address(0)); withdrawalAddress = _newWithdrawalAddress; } /** * @notice Withdraw the balance to the withdrawalAddress * @dev We set a withdrawal address seperate from the CFO because this allows us to withdraw to a cold wallet. */ function withdrawBalance() external onlyCEOOrCFO { require(withdrawalAddress != address(0)); withdrawalAddress.transfer(this.balance); } /** Pausable functionality adapted from OpenZeppelin **/ /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @notice called by any C-level to pause, triggers stopped state */ function pause() public onlyCLevel whenNotPaused { paused = true; Paused(); } /** * @notice called by the CEO to unpause, returns to normal state */ function unpause() public onlyCEO whenPaused { paused = false; Unpaused(); } } contract LicenseBase is LicenseAccessControl { /** * @notice Issued is emitted when a new license is issued */ event LicenseIssued( address indexed owner, address indexed purchaser, uint256 licenseId, uint256 productId, uint256 attributes, uint256 issuedTime, uint256 expirationTime, address affiliate ); event LicenseRenewal( address indexed owner, address indexed purchaser, uint256 licenseId, uint256 productId, uint256 expirationTime ); struct License { uint256 productId; uint256 attributes; uint256 issuedTime; uint256 expirationTime; address affiliate; } /** * @notice All licenses in existence. * @dev The ID of each license is an index in this array. */ License[] licenses; /** internal **/ function _isValidLicense(uint256 _licenseId) internal view returns (bool) { return licenseProductId(_licenseId) != 0; } /** anyone **/ /** * @notice Get a license's productId * @param _licenseId the license id */ function licenseProductId(uint256 _licenseId) public view returns (uint256) { return licenses[_licenseId].productId; } /** * @notice Get a license's attributes * @param _licenseId the license id */ function licenseAttributes(uint256 _licenseId) public view returns (uint256) { return licenses[_licenseId].attributes; } /** * @notice Get a license's issueTime * @param _licenseId the license id */ function licenseIssuedTime(uint256 _licenseId) public view returns (uint256) { return licenses[_licenseId].issuedTime; } /** * @notice Get a license's issueTime * @param _licenseId the license id */ function licenseExpirationTime(uint256 _licenseId) public view returns (uint256) { return licenses[_licenseId].expirationTime; } /** * @notice Get a the affiliate credited for the sale of this license * @param _licenseId the license id */ function licenseAffiliate(uint256 _licenseId) public view returns (address) { return licenses[_licenseId].affiliate; } /** * @notice Get a license's info * @param _licenseId the license id */ function licenseInfo(uint256 _licenseId) public view returns (uint256, uint256, uint256, uint256, address) { return ( licenseProductId(_licenseId), licenseAttributes(_licenseId), licenseIssuedTime(_licenseId), licenseExpirationTime(_licenseId), licenseAffiliate(_licenseId) ); } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract AffiliateProgram is Pausable { using SafeMath for uint256; event AffiliateCredit( // The address of the affiliate address affiliate, // The store's ID of what was sold (e.g. a tokenId) uint256 productId, // The amount owed this affiliate in this sale uint256 amount ); event Withdraw(address affiliate, address to, uint256 amount); event Whitelisted(address affiliate, uint256 amount); event RateChanged(uint256 rate, uint256 amount); // @notice A mapping from affiliate address to their balance mapping (address => uint256) public balances; // @notice A mapping from affiliate address to the time of last deposit mapping (address => uint256) public lastDepositTimes; // @notice The last deposit globally uint256 public lastDepositTime; // @notice The maximum rate for any affiliate // @dev The hard-coded maximum affiliate rate (in basis points) // All rates are measured in basis points (1/100 of a percent) // Values 0-10,000 map to 0%-100% uint256 private constant hardCodedMaximumRate = 5000; // @notice The commission exiration time // @dev Affiliate commissions expire if they are unclaimed after this amount of time uint256 private constant commissionExpiryTime = 30 days; // @notice The baseline affiliate rate (in basis points) for non-whitelisted referrals uint256 public baselineRate = 0; // @notice A mapping from whitelisted referrals to their individual rates mapping (address => uint256) public whitelistRates; // @notice The maximum rate for any affiliate // @dev overrides individual rates. This can be used to clip the rate used in bulk, if necessary uint256 public maximumRate = 5000; // @notice The address of the store selling products address public storeAddress; // @notice The contract is retired // @dev If we decide to retire this program, this value will be set to true // and then the contract cannot be unpaused bool public retired = false; /** * @dev Modifier to make a function only callable by the store or the owner */ modifier onlyStoreOrOwner() { require( msg.sender == storeAddress || msg.sender == owner); _; } /** * @dev AffiliateProgram constructor - keeps the address of it's parent store * and pauses the contract */ function AffiliateProgram(address _storeAddress) public { require(_storeAddress != address(0)); storeAddress = _storeAddress; paused = true; } /** * @notice Exposes that this contract thinks it is an AffiliateProgram */ function isAffiliateProgram() public pure returns (bool) { return true; } /** * @notice returns the commission rate for a sale * * @dev rateFor returns the rate which should be used to calculate the comission * for this affiliate/sale combination, in basis points (1/100th of a percent). * * We may want to completely blacklist a particular address (e.g. a known bad actor affilite). * To that end, if the whitelistRate is exactly 1bp, we use that as a signal for blacklisting * and return a rate of zero. The upside is that we can completely turn off * sending transactions to a particular address when this is needed. The * downside is that you can't issued 1/100th of a percent commission. * However, since this is such a small amount its an acceptable tradeoff. * * This implementation does not use the _productId, _pruchaseId, * _purchaseAmount, but we include them here as part of the protocol, because * they could be useful in more advanced affiliate programs. * * @param _affiliate - the address of the affiliate to check for */ function rateFor( address _affiliate, uint256 /*_productId*/, uint256 /*_purchaseId*/, uint256 /*_purchaseAmount*/) public view returns (uint256) { uint256 whitelistedRate = whitelistRates[_affiliate]; if(whitelistedRate > 0) { // use 1 bp as a blacklist signal if(whitelistedRate == 1) { return 0; } else { return Math.min256(whitelistedRate, maximumRate); } } else { return Math.min256(baselineRate, maximumRate); } } /** * @notice cutFor returns the affiliate cut for a sale * @dev cutFor returns the cut (amount in wei) to give in comission to the affiliate * * @param _affiliate - the address of the affiliate to check for * @param _productId - the productId in the sale * @param _purchaseId - the purchaseId in the sale * @param _purchaseAmount - the purchaseAmount */ function cutFor( address _affiliate, uint256 _productId, uint256 _purchaseId, uint256 _purchaseAmount) public view returns (uint256) { uint256 rate = rateFor( _affiliate, _productId, _purchaseId, _purchaseAmount); require(rate <= hardCodedMaximumRate); return (_purchaseAmount.mul(rate)).div(10000); } /** * @notice credit an affiliate for a purchase * @dev credit accepts eth and credits the affiliate's balance for the amount * * @param _affiliate - the address of the affiliate to credit * @param _purchaseId - the purchaseId of the sale */ function credit( address _affiliate, uint256 _purchaseId) public onlyStoreOrOwner whenNotPaused payable { require(msg.value > 0); require(_affiliate != address(0)); balances[_affiliate] += msg.value; lastDepositTimes[_affiliate] = now; // solium-disable-line security/no-block-members lastDepositTime = now; // solium-disable-line security/no-block-members AffiliateCredit(_affiliate, _purchaseId, msg.value); } /** * @dev _performWithdraw performs a withdrawal from address _from and * transfers it to _to. This can be different because we allow the owner * to withdraw unclaimed funds after a period of time. * * @param _from - the address to subtract balance from * @param _to - the address to transfer ETH to */ function _performWithdraw(address _from, address _to) private { require(balances[_from] > 0); uint256 balanceValue = balances[_from]; balances[_from] = 0; _to.transfer(balanceValue); Withdraw(_from, _to, balanceValue); } /** * @notice withdraw * @dev withdraw the msg.sender's balance */ function withdraw() public whenNotPaused { _performWithdraw(msg.sender, msg.sender); } /** * @notice withdraw from a specific account * @dev withdrawFrom allows the owner to withdraw an affiliate's unclaimed * ETH, after the alotted time. * * This function can be called even if the contract is paused * * @param _affiliate - the address of the affiliate * @param _to - the address to send ETH to */ function withdrawFrom(address _affiliate, address _to) onlyOwner public { // solium-disable-next-line security/no-block-members require(now > lastDepositTimes[_affiliate].add(commissionExpiryTime)); _performWithdraw(_affiliate, _to); } /** * @notice retire the contract (dangerous) * @dev retire - withdraws the entire balance and marks the contract as retired, which * prevents unpausing. * * If no new comissions have been deposited for the alotted time, * then the owner may pause the program and retire this contract. * This may only be performed once as the contract cannot be unpaused. * * We do this as an alternative to selfdestruct, because certain operations * can still be performed after the contract has been selfdestructed, such as * the owner withdrawing ETH accidentally sent here. */ function retire(address _to) onlyOwner whenPaused public { // solium-disable-next-line security/no-block-members require(now > lastDepositTime.add(commissionExpiryTime)); _to.transfer(this.balance); retired = true; } /** * @notice whitelist an affiliate address * @dev whitelist - white listed affiliates can receive a different * rate than the general public (whitelisted accounts would generally get a * better rate). * @param _affiliate - the affiliate address to whitelist * @param _rate - the rate, in basis-points (1/100th of a percent) to give this affiliate in each sale. NOTE: a rate of exactly 1 is the signal to blacklist this affiliate. That is, a rate of 1 will set the commission to 0. */ function whitelist(address _affiliate, uint256 _rate) onlyOwner public { require(_rate <= hardCodedMaximumRate); whitelistRates[_affiliate] = _rate; Whitelisted(_affiliate, _rate); } /** * @notice set the rate for non-whitelisted affiliates * @dev setBaselineRate - sets the baseline rate for any affiliate that is not whitelisted * @param _newRate - the rate, in bp (1/100th of a percent) to give any non-whitelisted affiliate. Set to zero to "turn off" */ function setBaselineRate(uint256 _newRate) onlyOwner public { require(_newRate <= hardCodedMaximumRate); baselineRate = _newRate; RateChanged(0, _newRate); } /** * @notice set the maximum rate for any affiliate * @dev setMaximumRate - Set the maximum rate for any affiliate, including whitelists. That is, this overrides individual rates. * @param _newRate - the rate, in bp (1/100th of a percent) */ function setMaximumRate(uint256 _newRate) onlyOwner public { require(_newRate <= hardCodedMaximumRate); maximumRate = _newRate; RateChanged(1, _newRate); } /** * @notice unpause the contract * @dev called by the owner to unpause, returns to normal state. Will not * unpause if the contract is retired. */ function unpause() onlyOwner whenPaused public { require(!retired); paused = false; Unpause(); } } contract ERC721 { event Transfer(address indexed _from, address indexed _to, uint256 _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId); event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); function balanceOf(address _owner) public view returns (uint256 _balance); function ownerOf(uint256 _tokenId) public view returns (address _owner); function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) public; function safeTransferFrom(address _from, address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) public; function approve(address _to, uint256 _tokenId) external; function setApprovalForAll(address _to, bool _approved) external; function getApproved(uint256 _tokenId) public view returns (address); function isApprovedForAll(address _owner, address _operator) public view returns (bool); } contract LicenseInventory is LicenseBase { using SafeMath for uint256; event ProductCreated( uint256 id, uint256 price, uint256 available, uint256 supply, uint256 interval, bool renewable ); event ProductInventoryAdjusted(uint256 productId, uint256 available); event ProductPriceChanged(uint256 productId, uint256 price); event ProductRenewableChanged(uint256 productId, bool renewable); /** * @notice Product defines a product * * renewable: There may come a time when we which to disable the ability to renew a subscription. For example, a plan we no longer wish to support. Obviously care needs to be taken with how we communicate this to customers, but contract-wise, we want to support the ability to discontinue renewal of certain plans. */ struct Product { uint256 id; uint256 price; uint256 available; uint256 supply; uint256 sold; uint256 interval; bool renewable; } // @notice All products in existence uint256[] public allProductIds; // @notice A mapping from product ids to Products mapping (uint256 => Product) public products; /*** internal ***/ /** * @notice _productExists checks to see if a product exists */ function _productExists(uint256 _productId) internal view returns (bool) { return products[_productId].id != 0; } function _productDoesNotExist(uint256 _productId) internal view returns (bool) { return products[_productId].id == 0; } function _createProduct( uint256 _productId, uint256 _initialPrice, uint256 _initialInventoryQuantity, uint256 _supply, uint256 _interval) internal { require(_productDoesNotExist(_productId)); require(_initialInventoryQuantity <= _supply); Product memory _product = Product({ id: _productId, price: _initialPrice, available: _initialInventoryQuantity, supply: _supply, sold: 0, interval: _interval, renewable: _interval == 0 ? false : true }); products[_productId] = _product; allProductIds.push(_productId); ProductCreated( _product.id, _product.price, _product.available, _product.supply, _product.interval, _product.renewable ); } function _incrementInventory( uint256 _productId, uint256 _inventoryAdjustment) internal { require(_productExists(_productId)); uint256 newInventoryLevel = products[_productId].available.add(_inventoryAdjustment); // A supply of "0" means "unlimited". Otherwise we need to ensure that we're not over-creating this product if(products[_productId].supply > 0) { // you have to take already sold into account require(products[_productId].sold.add(newInventoryLevel) <= products[_productId].supply); } products[_productId].available = newInventoryLevel; } function _decrementInventory( uint256 _productId, uint256 _inventoryAdjustment) internal { require(_productExists(_productId)); uint256 newInventoryLevel = products[_productId].available.sub(_inventoryAdjustment); // unnecessary because we're using SafeMath and an unsigned int // require(newInventoryLevel >= 0); products[_productId].available = newInventoryLevel; } function _clearInventory(uint256 _productId) internal { require(_productExists(_productId)); products[_productId].available = 0; } function _setPrice(uint256 _productId, uint256 _price) internal { require(_productExists(_productId)); products[_productId].price = _price; } function _setRenewable(uint256 _productId, bool _isRenewable) internal { require(_productExists(_productId)); products[_productId].renewable = _isRenewable; } function _purchaseOneUnitInStock(uint256 _productId) internal { require(_productExists(_productId)); require(availableInventoryOf(_productId) > 0); // lower inventory _decrementInventory(_productId, 1); // record that one was sold products[_productId].sold = products[_productId].sold.add(1); } function _requireRenewableProduct(uint256 _productId) internal view { // productId must exist require(_productId != 0); // You can only renew a subscription product require(isSubscriptionProduct(_productId)); // The product must currently be renewable require(renewableOf(_productId)); } /*** public ***/ /** executives-only **/ /** * @notice createProduct creates a new product in the system * @param _productId - the id of the product to use (cannot be changed) * @param _initialPrice - the starting price (price can be changed) * @param _initialInventoryQuantity - the initial inventory (inventory can be changed) * @param _supply - the total supply - use `0` for "unlimited" (cannot be changed) */ function createProduct( uint256 _productId, uint256 _initialPrice, uint256 _initialInventoryQuantity, uint256 _supply, uint256 _interval) external onlyCEOOrCOO { _createProduct( _productId, _initialPrice, _initialInventoryQuantity, _supply, _interval); } /** * @notice incrementInventory - increments the inventory of a product * @param _productId - the product id * @param _inventoryAdjustment - the amount to increment */ function incrementInventory( uint256 _productId, uint256 _inventoryAdjustment) external onlyCLevel { _incrementInventory(_productId, _inventoryAdjustment); ProductInventoryAdjusted(_productId, availableInventoryOf(_productId)); } /** * @notice decrementInventory removes inventory levels for a product * @param _productId - the product id * @param _inventoryAdjustment - the amount to decrement */ function decrementInventory( uint256 _productId, uint256 _inventoryAdjustment) external onlyCLevel { _decrementInventory(_productId, _inventoryAdjustment); ProductInventoryAdjusted(_productId, availableInventoryOf(_productId)); } /** * @notice clearInventory clears the inventory of a product. * @dev decrementInventory verifies inventory levels, whereas this method * simply sets the inventory to zero. This is useful, for example, if an * executive wants to take a product off the market quickly. There could be a * race condition with decrementInventory where a product is sold, which could * cause the admins decrement to fail (because it may try to decrement more * than available). * * @param _productId - the product id */ function clearInventory(uint256 _productId) external onlyCLevel { _clearInventory(_productId); ProductInventoryAdjusted(_productId, availableInventoryOf(_productId)); } /** * @notice setPrice - sets the price of a product * @param _productId - the product id * @param _price - the product price */ function setPrice(uint256 _productId, uint256 _price) external onlyCLevel { _setPrice(_productId, _price); ProductPriceChanged(_productId, _price); } /** * @notice setRenewable - sets if a product is renewable * @param _productId - the product id * @param _newRenewable - the new renewable setting */ function setRenewable(uint256 _productId, bool _newRenewable) external onlyCLevel { _setRenewable(_productId, _newRenewable); ProductRenewableChanged(_productId, _newRenewable); } /** anyone **/ /** * @notice The price of a product * @param _productId - the product id */ function priceOf(uint256 _productId) public view returns (uint256) { return products[_productId].price; } /** * @notice The available inventory of a product * @param _productId - the product id */ function availableInventoryOf(uint256 _productId) public view returns (uint256) { return products[_productId].available; } /** * @notice The total supply of a product * @param _productId - the product id */ function totalSupplyOf(uint256 _productId) public view returns (uint256) { return products[_productId].supply; } /** * @notice The total sold of a product * @param _productId - the product id */ function totalSold(uint256 _productId) public view returns (uint256) { return products[_productId].sold; } /** * @notice The renewal interval of a product in seconds * @param _productId - the product id */ function intervalOf(uint256 _productId) public view returns (uint256) { return products[_productId].interval; } /** * @notice Is this product renewable? * @param _productId - the product id */ function renewableOf(uint256 _productId) public view returns (bool) { return products[_productId].renewable; } /** * @notice The product info for a product * @param _productId - the product id */ function productInfo(uint256 _productId) public view returns (uint256, uint256, uint256, uint256, bool) { return ( priceOf(_productId), availableInventoryOf(_productId), totalSupplyOf(_productId), intervalOf(_productId), renewableOf(_productId)); } /** * @notice Get all product ids */ function getAllProductIds() public view returns (uint256[]) { return allProductIds; } /** * @notice returns the total cost to renew a product for a number of cycles * @dev If a product is a subscription, the interval defines the period of * time, in seconds, users can subscribe for. E.g. 1 month or 1 year. * _numCycles is the number of these intervals we want to use in the * calculation of the price. * * We require that the end user send precisely the amount required (instead * of dealing with excess refunds). This method is public so that clients can * read the exact amount our contract expects to receive. * * @param _productId - the product we're calculating for * @param _numCycles - the number of cycles to calculate for */ function costForProductCycles(uint256 _productId, uint256 _numCycles) public view returns (uint256) { return priceOf(_productId).mul(_numCycles); } /** * @notice returns if this product is a subscription or not * @dev Some products are subscriptions and others are not. An interval of 0 * means the product is not a subscription * @param _productId - the product we're checking */ function isSubscriptionProduct(uint256 _productId) public view returns (bool) { return intervalOf(_productId) > 0; } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } interface ERC165 { /// @notice Query if a contract implements an interface /// @param interfaceID The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceID) external view returns (bool); } contract LicenseOwnership is LicenseInventory, ERC721, ERC165, ERC721Metadata, ERC721Enumerable { using SafeMath for uint256; // Total amount of tokens uint256 private totalTokens; // Mapping from token ID to owner mapping (uint256 => address) private tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private tokenApprovals; // Mapping from owner address to operator address to approval mapping (address => mapping (address => bool)) private operatorApprovals; // Mapping from owner to list of owned token IDs mapping (address => uint256[]) private ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private ownedTokensIndex; /*** Constants ***/ // Configure these for your own deployment string public constant NAME = "Dottabot"; string public constant SYMBOL = "DOTTA"; string public tokenMetadataBaseURI = "https://api.dottabot.com/"; /** * @notice token's name */ function name() external pure returns (string) { return NAME; } /** * @notice symbols's name */ function symbol() external pure returns (string) { return SYMBOL; } function implementsERC721() external pure returns (bool) { return true; } function tokenURI(uint256 _tokenId) external view returns (string infoUrl) { return Strings.strConcat( tokenMetadataBaseURI, Strings.uint2str(_tokenId)); } function supportsInterface( bytes4 interfaceID) // solium-disable-line dotta/underscore-function-arguments external view returns (bool) { return interfaceID == this.supportsInterface.selector || // ERC165 interfaceID == 0x5b5e139f || // ERC721Metadata interfaceID == 0x6466353c || // ERC-721 on 3/7/2018 interfaceID == 0x780e9d63; // ERC721Enumerable } function setTokenMetadataBaseURI(string _newBaseURI) external onlyCEOOrCOO { tokenMetadataBaseURI = _newBaseURI; } /** * @notice Guarantees msg.sender is owner of the given token * @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender */ modifier onlyOwnerOf(uint256 _tokenId) { require(ownerOf(_tokenId) == msg.sender); _; } /** * @notice Gets the total amount of tokens stored by the contract * @return uint256 representing the total amount of tokens */ function totalSupply() public view returns (uint256) { return totalTokens; } /** * @notice Enumerate valid NFTs * @dev Our Licenses are kept in an array and each new License-token is just * the next element in the array. This method is required for ERC721Enumerable * which may support more complicated storage schemes. However, in our case the * _index is the tokenId * @param _index A counter less than `totalSupply()` * @return The token identifier for the `_index`th NFT */ function tokenByIndex(uint256 _index) external view returns (uint256) { require(_index < totalSupply()); return _index; } /** * @notice Gets the balance of the specified address * @param _owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address _owner) public view returns (uint256) { require(_owner != address(0)); return ownedTokens[_owner].length; } /** * @notice Gets the list of tokens owned by a given address * @param _owner address to query the tokens of * @return uint256[] representing the list of tokens owned by the passed address */ function tokensOf(address _owner) public view returns (uint256[]) { return ownedTokens[_owner]; } /** * @notice Enumerate NFTs assigned to an owner * @dev Throws if `_index` >= `balanceOf(_owner)` or if * `_owner` is the zero address, representing invalid NFTs. * @param _owner An address where we are interested in NFTs owned by them * @param _index A counter less than `balanceOf(_owner)` * @return The token identifier for the `_index`th NFT assigned to `_owner`, */ function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId) { require(_index < balanceOf(_owner)); return ownedTokens[_owner][_index]; } /** * @notice Gets the owner of the specified token ID * @param _tokenId uint256 ID of the token to query the owner of * @return owner address currently marked as the owner of the given token ID */ function ownerOf(uint256 _tokenId) public view returns (address) { address owner = tokenOwner[_tokenId]; require(owner != address(0)); return owner; } /** * @notice Gets the approved address to take ownership of a given token ID * @param _tokenId uint256 ID of the token to query the approval of * @return address currently approved to take ownership of the given token ID */ function getApproved(uint256 _tokenId) public view returns (address) { return tokenApprovals[_tokenId]; } /** * @notice Tells whether the msg.sender is approved to transfer the given token ID or not * Checks both for specific approval and operator approval * @param _tokenId uint256 ID of the token to query the approval of * @return bool whether transfer by msg.sender is approved for the given token ID or not */ function isSenderApprovedFor(uint256 _tokenId) internal view returns (bool) { return ownerOf(_tokenId) == msg.sender || isSpecificallyApprovedFor(msg.sender, _tokenId) || isApprovedForAll(ownerOf(_tokenId), msg.sender); } /** * @notice Tells whether the msg.sender is approved for the given token ID or not * @param _asker address of asking for approval * @param _tokenId uint256 ID of the token to query the approval of * @return bool whether the msg.sender is approved for the given token ID or not */ function isSpecificallyApprovedFor(address _asker, uint256 _tokenId) internal view returns (bool) { return getApproved(_tokenId) == _asker; } /** * @notice Tells whether an operator is approved by a given owner * @param _owner owner address which you want to query the approval of * @param _operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address _owner, address _operator) public view returns (bool) { return operatorApprovals[_owner][_operator]; } /** * @notice Transfers the ownership of a given token ID to another address * @param _to address to receive the ownership of the given token ID * @param _tokenId uint256 ID of the token to be transferred */ function transfer(address _to, uint256 _tokenId) external whenNotPaused onlyOwnerOf(_tokenId) { _clearApprovalAndTransfer(msg.sender, _to, _tokenId); } /** * @notice Approves another address to claim for the ownership of the given token ID * @param _to address to be approved for the given token ID * @param _tokenId uint256 ID of the token to be approved */ function approve(address _to, uint256 _tokenId) external whenNotPaused onlyOwnerOf(_tokenId) { address owner = ownerOf(_tokenId); require(_to != owner); if (getApproved(_tokenId) != 0 || _to != 0) { tokenApprovals[_tokenId] = _to; Approval(owner, _to, _tokenId); } } /** * @notice Enable or disable approval for a third party ("operator") to manage all your assets * @dev Emits the ApprovalForAll event * @param _to Address to add to the set of authorized operators. * @param _approved True if the operators is approved, false to revoke approval */ function setApprovalForAll(address _to, bool _approved) external whenNotPaused { if(_approved) { approveAll(_to); } else { disapproveAll(_to); } } /** * @notice Approves another address to claim for the ownership of any tokens owned by this account * @param _to address to be approved for the given token ID */ function approveAll(address _to) public whenNotPaused { require(_to != msg.sender); require(_to != address(0)); operatorApprovals[msg.sender][_to] = true; ApprovalForAll(msg.sender, _to, true); } /** * @notice Removes approval for another address to claim for the ownership of any * tokens owned by this account. * @dev Note that this only removes the operator approval and * does not clear any independent, specific approvals of token transfers to this address * @param _to address to be disapproved for the given token ID */ function disapproveAll(address _to) public whenNotPaused { require(_to != msg.sender); delete operatorApprovals[msg.sender][_to]; ApprovalForAll(msg.sender, _to, false); } /** * @notice Claims the ownership of a given token ID * @param _tokenId uint256 ID of the token being claimed by the msg.sender */ function takeOwnership(uint256 _tokenId) external whenNotPaused { require(isSenderApprovedFor(_tokenId)); _clearApprovalAndTransfer(ownerOf(_tokenId), msg.sender, _tokenId); } /** * @notice Transfer a token owned by another address, for which the calling address has * previously been granted transfer approval by the owner. * @param _from The address that owns the token * @param _to The address that will take ownership of the token. Can be any address, including the caller * @param _tokenId The ID of the token to be transferred */ function transferFrom( address _from, address _to, uint256 _tokenId ) public whenNotPaused { require(isSenderApprovedFor(_tokenId)); require(ownerOf(_tokenId) == _from); _clearApprovalAndTransfer(ownerOf(_tokenId), _to, _tokenId); } /** * @notice Transfers the ownership of an NFT from one address to another address * @dev Throws unless `msg.sender` is the current owner, an authorized * operator, or the approved address for this NFT. Throws if `_from` is * not the current owner. Throws if `_to` is the zero address. Throws if * `_tokenId` is not a valid NFT. When transfer is complete, this function * checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. * @param _from The current owner of the NFT * @param _to The new owner * @param _tokenId The NFT to transfer * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes _data ) public whenNotPaused { require(_to != address(0)); require(_isValidLicense(_tokenId)); transferFrom(_from, _to, _tokenId); if (_isContract(_to)) { bytes4 tokenReceiverResponse = ERC721TokenReceiver(_to).onERC721Received.gas(50000)( _from, _tokenId, _data ); require(tokenReceiverResponse == bytes4(keccak256("onERC721Received(address,uint256,bytes)"))); } } /* * @notice Transfers the ownership of an NFT from one address to another address * @dev This works identically to the other function with an extra data parameter, * except this function just sets data to "" * @param _from The current owner of the NFT * @param _to The new owner * @param _tokenId The NFT to transfer */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { safeTransferFrom(_from, _to, _tokenId, ""); } /** * @notice Mint token function * @param _to The address that will own the minted token * @param _tokenId uint256 ID of the token to be minted by the msg.sender */ function _mint(address _to, uint256 _tokenId) internal { require(_to != address(0)); _addToken(_to, _tokenId); Transfer(0x0, _to, _tokenId); } /** * @notice Internal function to clear current approval and transfer the ownership of a given token ID * @param _from address which you want to send tokens from * @param _to address which you want to transfer the token to * @param _tokenId uint256 ID of the token to be transferred */ function _clearApprovalAndTransfer(address _from, address _to, uint256 _tokenId) internal { require(_to != address(0)); require(_to != ownerOf(_tokenId)); require(ownerOf(_tokenId) == _from); require(_isValidLicense(_tokenId)); _clearApproval(_from, _tokenId); _removeToken(_from, _tokenId); _addToken(_to, _tokenId); Transfer(_from, _to, _tokenId); } /** * @notice Internal function to clear current approval of a given token ID * @param _tokenId uint256 ID of the token to be transferred */ function _clearApproval(address _owner, uint256 _tokenId) private { require(ownerOf(_tokenId) == _owner); tokenApprovals[_tokenId] = 0; Approval(_owner, 0, _tokenId); } /** * @notice Internal function to add a token ID to the list of a given address * @param _to address representing the new owner of the given token ID * @param _tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addToken(address _to, uint256 _tokenId) private { require(tokenOwner[_tokenId] == address(0)); tokenOwner[_tokenId] = _to; uint256 length = balanceOf(_to); ownedTokens[_to].push(_tokenId); ownedTokensIndex[_tokenId] = length; totalTokens = totalTokens.add(1); } /** * @notice Internal function to remove a token ID from the list of a given address * @param _from address representing the previous owner of the given token ID * @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeToken(address _from, uint256 _tokenId) private { require(ownerOf(_tokenId) == _from); uint256 tokenIndex = ownedTokensIndex[_tokenId]; uint256 lastTokenIndex = balanceOf(_from).sub(1); uint256 lastToken = ownedTokens[_from][lastTokenIndex]; tokenOwner[_tokenId] = 0; ownedTokens[_from][tokenIndex] = lastToken; ownedTokens[_from][lastTokenIndex] = 0; // Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to // be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping // the lastToken to the first position, and then dropping the element placed in the last position of the list ownedTokens[_from].length--; ownedTokensIndex[_tokenId] = 0; ownedTokensIndex[lastToken] = tokenIndex; totalTokens = totalTokens.sub(1); } function _isContract(address addr) internal view returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } } contract LicenseSale is LicenseOwnership { AffiliateProgram public affiliateProgram; /** * @notice We credit affiliates for renewals that occur within this time of * original purchase. E.g. If this is set to 1 year, and someone subscribes to * a monthly plan, the affiliate will receive credits for that whole year, as * the user renews their plan */ uint256 public renewalsCreditAffiliatesFor = 1 years; /** internal **/ function _performPurchase( uint256 _productId, uint256 _numCycles, address _assignee, uint256 _attributes, address _affiliate) internal returns (uint) { _purchaseOneUnitInStock(_productId); return _createLicense( _productId, _numCycles, _assignee, _attributes, _affiliate ); } function _createLicense( uint256 _productId, uint256 _numCycles, address _assignee, uint256 _attributes, address _affiliate) internal returns (uint) { // You cannot create a subscription license with zero cycles if(isSubscriptionProduct(_productId)) { require(_numCycles != 0); } // Non-subscription products have an expiration time of 0, meaning "no-expiration" uint256 expirationTime = isSubscriptionProduct(_productId) ? now.add(intervalOf(_productId).mul(_numCycles)) : // solium-disable-line security/no-block-members 0; License memory _license = License({ productId: _productId, attributes: _attributes, issuedTime: now, // solium-disable-line security/no-block-members expirationTime: expirationTime, affiliate: _affiliate }); uint256 newLicenseId = licenses.push(_license) - 1; // solium-disable-line zeppelin/no-arithmetic-operations LicenseIssued( _assignee, msg.sender, newLicenseId, _license.productId, _license.attributes, _license.issuedTime, _license.expirationTime, _license.affiliate); _mint(_assignee, newLicenseId); return newLicenseId; } function _handleAffiliate( address _affiliate, uint256 _productId, uint256 _licenseId, uint256 _purchaseAmount) internal { uint256 affiliateCut = affiliateProgram.cutFor( _affiliate, _productId, _licenseId, _purchaseAmount); if(affiliateCut > 0) { require(affiliateCut < _purchaseAmount); affiliateProgram.credit.value(affiliateCut)(_affiliate, _licenseId); } } function _performRenewal(uint256 _tokenId, uint256 _numCycles) internal { // You cannot renew a non-expiring license // ... but in what scenario can this happen? // require(licenses[_tokenId].expirationTime != 0); uint256 productId = licenseProductId(_tokenId); // If our expiration is in the future, renewing adds time to that future expiration // If our expiration has passed already, then we use `now` as the base. uint256 renewalBaseTime = Math.max256(now, licenses[_tokenId].expirationTime); // We assume that the payment has been validated outside of this function uint256 newExpirationTime = renewalBaseTime.add(intervalOf(productId).mul(_numCycles)); licenses[_tokenId].expirationTime = newExpirationTime; LicenseRenewal( ownerOf(_tokenId), msg.sender, _tokenId, productId, newExpirationTime ); } function _affiliateProgramIsActive() internal view returns (bool) { return affiliateProgram != address(0) && affiliateProgram.storeAddress() == address(this) && !affiliateProgram.paused(); } /** executives **/ function setAffiliateProgramAddress(address _address) external onlyCEO { AffiliateProgram candidateContract = AffiliateProgram(_address); require(candidateContract.isAffiliateProgram()); affiliateProgram = candidateContract; } function setRenewalsCreditAffiliatesFor(uint256 _newTime) external onlyCEO { renewalsCreditAffiliatesFor = _newTime; } function createPromotionalPurchase( uint256 _productId, uint256 _numCycles, address _assignee, uint256 _attributes ) external onlyCEOOrCOO whenNotPaused returns (uint256) { return _performPurchase( _productId, _numCycles, _assignee, _attributes, address(0)); } function createPromotionalRenewal( uint256 _tokenId, uint256 _numCycles ) external onlyCEOOrCOO whenNotPaused { uint256 productId = licenseProductId(_tokenId); _requireRenewableProduct(productId); return _performRenewal(_tokenId, _numCycles); } /** anyone **/ /** * @notice Makes a purchase of a product. * @dev Requires that the value sent is exactly the price of the product * @param _productId - the product to purchase * @param _numCycles - the number of cycles being purchased. This number should be `1` for non-subscription products and the number of cycles for subscriptions. * @param _assignee - the address to assign the purchase to (doesn't have to be msg.sender) * @param _affiliate - the address to of the affiliate - use address(0) if none */ function purchase( uint256 _productId, uint256 _numCycles, address _assignee, address _affiliate ) external payable whenNotPaused returns (uint256) { require(_productId != 0); require(_numCycles != 0); require(_assignee != address(0)); // msg.value can be zero: free products are supported // Don't bother dealing with excess payments. Ensure the price paid is // accurate. No more, no less. require(msg.value == costForProductCycles(_productId, _numCycles)); // Non-subscription products should send a _numCycle of 1 -- you can't buy a // multiple quantity of a non-subscription product with this function if(!isSubscriptionProduct(_productId)) { require(_numCycles == 1); } // this can, of course, be gamed by malicious miners. But it's adequate for our application // Feel free to add your own strategies for product attributes // solium-disable-next-line security/no-block-members, zeppelin/no-arithmetic-operations uint256 attributes = uint256(keccak256(block.blockhash(block.number-1)))^_productId^(uint256(_assignee)); uint256 licenseId = _performPurchase( _productId, _numCycles, _assignee, attributes, _affiliate); if( priceOf(_productId) > 0 && _affiliate != address(0) && _affiliateProgramIsActive() ) { _handleAffiliate( _affiliate, _productId, licenseId, msg.value); } return licenseId; } /** * @notice Renews a subscription */ function renew( uint256 _tokenId, uint256 _numCycles ) external payable whenNotPaused { require(_numCycles != 0); require(ownerOf(_tokenId) != address(0)); uint256 productId = licenseProductId(_tokenId); _requireRenewableProduct(productId); // No excess payments. Ensure the price paid is exactly accurate. No more, // no less. uint256 renewalCost = costForProductCycles(productId, _numCycles); require(msg.value == renewalCost); _performRenewal(_tokenId, _numCycles); if( renewalCost > 0 && licenseAffiliate(_tokenId) != address(0) && _affiliateProgramIsActive() && licenseIssuedTime(_tokenId).add(renewalsCreditAffiliatesFor) > now ) { _handleAffiliate( licenseAffiliate(_tokenId), productId, _tokenId, msg.value); } } } contract LicenseCore is LicenseSale { address public newContractAddress; function LicenseCore() public { paused = true; ceoAddress = msg.sender; cooAddress = msg.sender; cfoAddress = msg.sender; withdrawalAddress = msg.sender; } function setNewAddress(address _v2Address) external onlyCEO whenPaused { newContractAddress = _v2Address; ContractUpgrade(_v2Address); } function() external { assert(false); } function unpause() public onlyCEO whenPaused { require(newContractAddress == address(0)); super.unpause(); } } library Strings { // via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i]; for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i]; for (i = 0; i < _be.length; i++) babcde[k++] = _be[i]; return string(babcde); } function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal pure returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal pure returns (string) { return strConcat(_a, _b, "", "", ""); } function uint2str(uint i) internal pure returns (string) { if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } }
token's name/
function name() external pure returns (string) { return NAME; }
478,468
// SPDX-License-Identifier: LGPL-3.0-only pragma solidity ^0.8.6; import "@gnosis.pm/zodiac/contracts/core/Modifier.sol"; import "./Permissions.sol"; contract Roles is Modifier { address public multisend; mapping(address => uint16) public defaultRoles; mapping(uint16 => Role) internal roles; event AssignRoles(address module, uint16[] roles, bool[] memberOf); event SetMultisendAddress(address multisendAddress); event RolesModSetup( address indexed initiator, address indexed owner, address indexed avatar, address target ); event SetDefaultRole(address module, uint16 defaultRole); /// `setUpModules` has already been called error SetUpModulesAlreadyCalled(); /// Arrays must be the same length error ArraysDifferentLength(); /// Sender is not a member of the role error NoMembership(); /// Sender is allowed to make this call, but the internal transaction failed error ModuleTransactionFailed(); /// @param _owner Address of the owner /// @param _avatar Address of the avatar (e.g. a Gnosis Safe) /// @param _target Address of the contract that will call exec function constructor( address _owner, address _avatar, address _target ) { bytes memory initParams = abi.encode(_owner, _avatar, _target); setUp(initParams); } function setUp(bytes memory initParams) public override { (address _owner, address _avatar, address _target) = abi.decode( initParams, (address, address, address) ); __Ownable_init(); avatar = _avatar; target = _target; transferOwnership(_owner); setupModules(); emit RolesModSetup(msg.sender, _owner, _avatar, _target); } function setupModules() internal { if (modules[SENTINEL_MODULES] != address(0)) { revert SetUpModulesAlreadyCalled(); } modules[SENTINEL_MODULES] = SENTINEL_MODULES; } /// @dev Set the address of the expected multisend library /// @notice Only callable by owner. /// @param _multisend address of the multisend library contract function setMultisend(address _multisend) external onlyOwner { multisend = _multisend; emit SetMultisendAddress(multisend); } /// @dev Allows all calls made to an address. /// @notice Only callable by owner. /// @param role Role to set for /// @param targetAddress Address to be allowed /// @param options defines whether or not delegate calls and/or eth can be sent to the target address. function allowTarget( uint16 role, address targetAddress, ExecutionOptions options ) external onlyOwner { Permissions.allowTarget(roles[role], role, targetAddress, options); } /// @dev Disallows all calls made to an address. /// @notice Only callable by owner. /// @param role Role to set for /// @param targetAddress Address to be disallowed function revokeTarget(uint16 role, address targetAddress) external onlyOwner { Permissions.revokeTarget(roles[role], role, targetAddress); } /// @dev Scopes calls to an address, limited to specific function signatures, and per function scoping rules. /// @notice Only callable by owner. /// @param role Role to set for. /// @param targetAddress Address to be scoped. function scopeTarget(uint16 role, address targetAddress) external onlyOwner { Permissions.scopeTarget(roles[role], role, targetAddress); } /// @dev Allows a specific function signature on a scoped target. /// @notice Only callable by owner. /// @param role Role to set for /// @param targetAddress Scoped address on which a function signature should be allowed. /// @param functionSig Function signature to be allowed. /// @param options Defines whether or not delegate calls and/or eth can be sent to the function. function scopeAllowFunction( uint16 role, address targetAddress, bytes4 functionSig, ExecutionOptions options ) external onlyOwner { Permissions.scopeAllowFunction( roles[role], role, targetAddress, functionSig, options ); } /// @dev Disallows a specific function signature on a scoped target. /// @notice Only callable by owner. /// @param role Role to set for /// @param targetAddress Scoped address on which a function signature should be disallowed. /// @param functionSig Function signature to be disallowed. function scopeRevokeFunction( uint16 role, address targetAddress, bytes4 functionSig ) external onlyOwner { Permissions.scopeRevokeFunction( roles[role], role, targetAddress, functionSig ); } /// @dev Sets scoping rules for a function, on a scoped address. /// @notice Only callable by owner. /// @param role Role to set for. /// @param targetAddress Scoped address on which scoping rules for a function are to be set. /// @param functionSig Function signature to be scoped. /// @param isParamScoped false for un-scoped, true for scoped. /// @param paramType Static, Dynamic or Dynamic32, depending on the parameter type. /// @param paramComp Any, or EqualTo, GreaterThan, or LessThan, depending on comparison type. /// @param compValue The reference value used while comparing and authorizing. /// @param options Defines whether or not delegate calls and/or eth can be sent to the function. function scopeFunction( uint16 role, address targetAddress, bytes4 functionSig, bool[] calldata isParamScoped, ParameterType[] calldata paramType, Comparison[] calldata paramComp, bytes[] memory compValue, ExecutionOptions options ) external onlyOwner { Permissions.scopeFunction( roles[role], role, targetAddress, functionSig, isParamScoped, paramType, paramComp, compValue, options ); } /// @dev Sets whether or not delegate calls and/or eth can be sent to a function on a scoped target. /// @notice Only callable by owner. /// @notice Only in play when target is scoped. /// @param role Role to set for. /// @param targetAddress Scoped address on which the ExecutionOptions for a function are to be set. /// @param functionSig Function signature on which the ExecutionOptions are to be set. /// @param options Defines whether or not delegate calls and/or eth can be sent to the function. function scopeFunctionExecutionOptions( uint16 role, address targetAddress, bytes4 functionSig, ExecutionOptions options ) external onlyOwner { Permissions.scopeFunctionExecutionOptions( roles[role], role, targetAddress, functionSig, options ); } /// @dev Sets and enforces scoping rules, for a single parameter of a function, on a scoped target. /// @notice Only callable by owner. /// @param role Role to set for. /// @param targetAddress Scoped address on which functionSig lives. /// @param functionSig Function signature to be scoped. /// @param paramIndex The index of the parameter to scope. /// @param paramType Static, Dynamic or Dynamic32, depending on the parameter type. /// @param paramComp Any, or EqualTo, GreaterThan, or LessThan, depending on comparison type. /// @param compValue The reference value used while comparing and authorizing. function scopeParameter( uint16 role, address targetAddress, bytes4 functionSig, uint256 paramIndex, ParameterType paramType, Comparison paramComp, bytes calldata compValue ) external onlyOwner { Permissions.scopeParameter( roles[role], role, targetAddress, functionSig, paramIndex, paramType, paramComp, compValue ); } /// @dev Sets and enforces scoping rules, for a single parameter of a function, on a scoped target. /// @notice Only callable by owner. /// @notice Parameter will be scoped with comparison type OneOf. /// @param role Role to set for. /// @param targetAddress Scoped address on which functionSig lives. /// @param functionSig Function signature to be scoped. /// @param paramIndex The index of the parameter to scope. /// @param paramType Static, Dynamic or Dynamic32, depending on the parameter type. /// @param compValues The reference values used while comparing and authorizing. function scopeParameterAsOneOf( uint16 role, address targetAddress, bytes4 functionSig, uint256 paramIndex, ParameterType paramType, bytes[] calldata compValues ) external onlyOwner { Permissions.scopeParameterAsOneOf( roles[role], role, targetAddress, functionSig, paramIndex, paramType, compValues ); } /// @dev Un-scopes a single parameter of a function, on a scoped target. /// @notice Only callable by owner. /// @param role Role to set for. /// @param targetAddress Scoped address on which functionSig lives. /// @param functionSig Function signature to be scoped. /// @param paramIndex The index of the parameter to un-scope. function unscopeParameter( uint16 role, address targetAddress, bytes4 functionSig, uint8 paramIndex ) external onlyOwner { Permissions.unscopeParameter( roles[role], role, targetAddress, functionSig, paramIndex ); } /// @dev Assigns and revokes roles to a given module. /// @param module Module on which to assign/revoke roles. /// @param _roles Roles to assign/revoke. /// @param memberOf Assign (true) or revoke (false) corresponding _roles. function assignRoles( address module, uint16[] calldata _roles, bool[] calldata memberOf ) external onlyOwner { if (_roles.length != memberOf.length) { revert ArraysDifferentLength(); } for (uint16 i = 0; i < _roles.length; i++) { roles[_roles[i]].members[module] = memberOf[i]; } if (!isModuleEnabled(module)) { enableModule(module); } emit AssignRoles(module, _roles, memberOf); } /// @dev Sets the default role used for a module if it calls execTransactionFromModule() or execTransactionFromModuleReturnData(). /// @param module Address of the module on which to set default role. /// @param role Role to be set as default. function setDefaultRole(address module, uint16 role) external onlyOwner { defaultRoles[module] = role; emit SetDefaultRole(module, role); } /// @dev Passes a transaction to the modifier. /// @param to Destination address of module transaction /// @param value Ether value of module transaction /// @param data Data payload of module transaction /// @param operation Operation type of module transaction /// @notice Can only be called by enabled modules function execTransactionFromModule( address to, uint256 value, bytes calldata data, Enum.Operation operation ) public override moduleOnly returns (bool success) { Permissions.check( roles[defaultRoles[msg.sender]], multisend, to, value, data, operation ); return exec(to, value, data, operation); } /// @dev Passes a transaction to the modifier, expects return data. /// @param to Destination address of module transaction /// @param value Ether value of module transaction /// @param data Data payload of module transaction /// @param operation Operation type of module transaction /// @notice Can only be called by enabled modules function execTransactionFromModuleReturnData( address to, uint256 value, bytes calldata data, Enum.Operation operation ) public override moduleOnly returns (bool, bytes memory) { Permissions.check( roles[defaultRoles[msg.sender]], multisend, to, value, data, operation ); return execAndReturnData(to, value, data, operation); } /// @dev Passes a transaction to the modifier assuming the specified role. /// @param to Destination address of module transaction /// @param value Ether value of module transaction /// @param data Data payload of module transaction /// @param operation Operation type of module transaction /// @param role Identifier of the role to assume for this transaction /// @param shouldRevert Should the function revert on inner execution returning success false? /// @notice Can only be called by enabled modules function execTransactionWithRole( address to, uint256 value, bytes calldata data, Enum.Operation operation, uint16 role, bool shouldRevert ) public moduleOnly returns (bool success) { Permissions.check(roles[role], multisend, to, value, data, operation); success = exec(to, value, data, operation); if (shouldRevert && !success) { revert ModuleTransactionFailed(); } } /// @dev Passes a transaction to the modifier assuming the specified role. Expects return data. /// @param to Destination address of module transaction /// @param value Ether value of module transaction /// @param data Data payload of module transaction /// @param operation Operation type of module transaction /// @param role Identifier of the role to assume for this transaction /// @param shouldRevert Should the function revert on inner execution returning success false? /// @notice Can only be called by enabled modules function execTransactionWithRoleReturnData( address to, uint256 value, bytes calldata data, Enum.Operation operation, uint16 role, bool shouldRevert ) public moduleOnly returns (bool success, bytes memory returnData) { Permissions.check(roles[role], multisend, to, value, data, operation); (success, returnData) = execAndReturnData(to, value, data, operation); if (shouldRevert && !success) { revert ModuleTransactionFailed(); } } } // SPDX-License-Identifier: LGPL-3.0-only /// @title Modifier Interface - A contract that sits between a Aodule and an Avatar and enforce some additional logic. pragma solidity >=0.7.0 <0.9.0; import "../interfaces/IAvatar.sol"; import "./Module.sol"; abstract contract Modifier is Module { event EnabledModule(address module); event DisabledModule(address module); address internal constant SENTINEL_MODULES = address(0x1); // Mapping of modules mapping(address => address) internal modules; /* -------------------------------------------------- You must override at least one of following two virtual functions, execTransactionFromModule() and execTransactionFromModuleReturnData(). */ /// @dev Passes a transaction to the modifier. /// @param to Destination address of module transaction /// @param value Ether value of module transaction /// @param data Data payload of module transaction /// @param operation Operation type of module transaction /// @notice Can only be called by enabled modules function execTransactionFromModule( address to, uint256 value, bytes calldata data, Enum.Operation operation ) public virtual moduleOnly returns (bool success) {} /// @dev Passes a transaction to the modifier, expects return data. /// @param to Destination address of module transaction /// @param value Ether value of module transaction /// @param data Data payload of module transaction /// @param operation Operation type of module transaction /// @notice Can only be called by enabled modules function execTransactionFromModuleReturnData( address to, uint256 value, bytes calldata data, Enum.Operation operation ) public virtual moduleOnly returns (bool success, bytes memory returnData) {} /* -------------------------------------------------- */ modifier moduleOnly() { require(modules[msg.sender] != address(0), "Module not authorized"); _; } /// @dev Disables a module on the modifier /// @param prevModule Module that pointed to the module to be removed in the linked list /// @param module Module to be removed /// @notice This can only be called by the owner function disableModule(address prevModule, address module) public onlyOwner { require( module != address(0) && module != SENTINEL_MODULES, "Invalid module" ); require(modules[prevModule] == module, "Module already disabled"); modules[prevModule] = modules[module]; modules[module] = address(0); emit DisabledModule(module); } /// @dev Enables a module that can add transactions to the queue /// @param module Address of the module to be enabled /// @notice This can only be called by the owner function enableModule(address module) public onlyOwner { require( module != address(0) && module != SENTINEL_MODULES, "Invalid module" ); require(modules[module] == address(0), "Module already enabled"); modules[module] = modules[SENTINEL_MODULES]; modules[SENTINEL_MODULES] = module; emit EnabledModule(module); } /// @dev Returns if an module is enabled /// @return True if the module is enabled function isModuleEnabled(address _module) public view returns (bool) { return SENTINEL_MODULES != _module && modules[_module] != address(0); } /// @dev Returns array of modules. /// @param start Start of the page. /// @param pageSize Maximum number of modules that should be returned. /// @return array Array of modules. /// @return next Start of the next page. function getModulesPaginated(address start, uint256 pageSize) external view returns (address[] memory array, address next) { // Init array with max page size array = new address[](pageSize); // Populate return array uint256 moduleCount = 0; address currentModule = modules[start]; while ( currentModule != address(0x0) && currentModule != SENTINEL_MODULES && moduleCount < pageSize ) { array[moduleCount] = currentModule; currentModule = modules[currentModule]; moduleCount++; } next = currentModule; // Set correct size of returned array // solhint-disable-next-line no-inline-assembly assembly { mstore(array, moduleCount) } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity ^0.8.6; import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol"; enum ParameterType { Static, Dynamic, Dynamic32 } enum Comparison { EqualTo, GreaterThan, LessThan, OneOf } enum ExecutionOptions { None, Send, DelegateCall, Both } enum Clearance { None, Target, Function } struct TargetAddress { Clearance clearance; ExecutionOptions options; } struct Role { mapping(address => bool) members; mapping(address => TargetAddress) targets; mapping(bytes32 => uint256) functions; mapping(bytes32 => bytes32) compValues; mapping(bytes32 => bytes32[]) compValuesOneOf; } library Permissions { uint256 internal constant SCOPE_MAX_PARAMS = 48; event AllowTarget( uint16 role, address targetAddress, ExecutionOptions options ); event RevokeTarget(uint16 role, address targetAddress); event ScopeTarget(uint16 role, address targetAddress); event ScopeAllowFunction( uint16 role, address targetAddress, bytes4 selector, ExecutionOptions options, uint256 resultingScopeConfig ); event ScopeRevokeFunction( uint16 role, address targetAddress, bytes4 selector, uint256 resultingScopeConfig ); event ScopeFunction( uint16 role, address targetAddress, bytes4 functionSig, bool[] isParamScoped, ParameterType[] paramType, Comparison[] paramComp, bytes[] compValue, ExecutionOptions options, uint256 resultingScopeConfig ); event ScopeFunctionExecutionOptions( uint16 role, address targetAddress, bytes4 functionSig, ExecutionOptions options, uint256 resultingScopeConfig ); event ScopeParameter( uint16 role, address targetAddress, bytes4 functionSig, uint256 index, ParameterType paramType, Comparison paramComp, bytes compValue, uint256 resultingScopeConfig ); event ScopeParameterAsOneOf( uint16 role, address targetAddress, bytes4 functionSig, uint256 index, ParameterType paramType, bytes[] compValues, uint256 resultingScopeConfig ); event UnscopeParameter( uint16 role, address targetAddress, bytes4 functionSig, uint256 index, uint256 resultingScopeConfig ); /// Sender is not a member of the role error NoMembership(); /// Arrays must be the same length error ArraysDifferentLength(); /// Function signature too short error FunctionSignatureTooShort(); /// Role not allowed to delegate call to target address error DelegateCallNotAllowed(); /// Role not allowed to call target address error TargetAddressNotAllowed(); /// Role not allowed to call this function on target address error FunctionNotAllowed(); /// Role not allowed to send to target address error SendNotAllowed(); /// Role not allowed to use bytes for parameter error ParameterNotAllowed(); /// Role not allowed to use bytes for parameter error ParameterNotOneOfAllowed(); /// Role not allowed to use bytes less than value for parameter error ParameterLessThanAllowed(); /// Role not allowed to use bytes greater than value for parameter error ParameterGreaterThanAllowed(); /// only multisend txs with an offset of 32 bytes are allowed error UnacceptableMultiSendOffset(); /// OneOf Comparison must be set via dedicated function error UnsuitableOneOfComparison(); /// Not possible to define gt/lt for Dynamic types error UnsuitableRelativeComparison(); /// CompValue for static types should have a size of exactly 32 bytes error UnsuitableStaticCompValueSize(); /// CompValue for Dynamic32 types should be a multiple of exactly 32 bytes error UnsuitableDynamic32CompValueSize(); /// Exceeds the max number of params supported error ScopeMaxParametersExceeded(); /// OneOf Comparison requires at least two compValues error NotEnoughCompValuesForOneOf(); /// The provided calldata for execution is too short, or an OutOfBounds scoped parameter was configured error CalldataOutOfBounds(); /* * * CHECKERS * */ function check( Role storage role, address multisend, address to, uint256 value, bytes calldata data, Enum.Operation operation ) public view { if (!role.members[msg.sender]) { revert NoMembership(); } if (multisend == to) { checkMultisendTransaction(role, data); } else { checkTransaction(role, to, value, data, operation); } } /// @dev Splits a multisend data blob into transactions and forwards them to be checked. /// @param data the packed transaction data (created by utils function buildMultiSendSafeTx). /// @param role Role to check for. function checkMultisendTransaction(Role storage role, bytes memory data) internal view { Enum.Operation operation; address to; uint256 value; bytes memory out; uint256 dataLength; uint256 offset; assembly { offset := mload(add(data, 36)) } if (offset != 32) { revert UnacceptableMultiSendOffset(); } // transaction data (1st tx operation) reads at byte 100, // 4 bytes (multisend_id) + 32 bytes (offset_multisend_data) + 32 bytes multisend_data_length // increment i by the transaction data length // + 85 bytes of the to, value, and operation bytes until we reach the end of the data for (uint256 i = 100; i < data.length; i += (85 + dataLength)) { assembly { // First byte of the data is the operation. // We shift by 248 bits (256 - 8 [operation byte]) right since mload will always load 32 bytes (a word). // This will also zero out unused data. operation := shr(0xf8, mload(add(data, i))) // We offset the load address by 1 byte (operation byte) // We shift it right by 96 bits (256 - 160 [20 address bytes]) to right-align the data and zero out unused data. to := shr(0x60, mload(add(data, add(i, 0x01)))) // We offset the load address by 21 byte (operation byte + 20 address bytes) value := mload(add(data, add(i, 0x15))) // We offset the load address by 53 byte (operation byte + 20 address bytes + 32 value bytes) dataLength := mload(add(data, add(i, 0x35))) // We offset the load address by 85 byte (operation byte + 20 address bytes + 32 value bytes + 32 data length bytes) out := add(data, add(i, 0x35)) } checkTransaction(role, to, value, out, operation); } } function checkTransaction( Role storage role, address targetAddress, uint256 value, bytes memory data, Enum.Operation operation ) internal view { if (data.length != 0 && data.length < 4) { revert FunctionSignatureTooShort(); } TargetAddress storage target = role.targets[targetAddress]; if (target.clearance == Clearance.None) { revert TargetAddressNotAllowed(); } if (target.clearance == Clearance.Target) { checkExecutionOptions(value, operation, target.options); return; } if (target.clearance == Clearance.Function) { uint256 scopeConfig = role.functions[ keyForFunctions(targetAddress, bytes4(data)) ]; if (scopeConfig == 0) { revert FunctionNotAllowed(); } (ExecutionOptions options, bool isWildcarded, ) = unpackFunction( scopeConfig ); checkExecutionOptions(value, operation, options); if (isWildcarded == false) { checkParameters(role, scopeConfig, targetAddress, data); } return; } assert(false); } function checkExecutionOptions( uint256 value, Enum.Operation operation, ExecutionOptions options ) internal pure { // isSend && !canSend if ( value > 0 && options != ExecutionOptions.Send && options != ExecutionOptions.Both ) { revert SendNotAllowed(); } // isDelegateCall && !canDelegateCall if ( operation == Enum.Operation.DelegateCall && options != ExecutionOptions.DelegateCall && options != ExecutionOptions.Both ) { revert DelegateCallNotAllowed(); } } /// @dev Will revert if a transaction has a parameter that is not allowed /// @param role reference to role storage /// @param targetAddress Address to check. /// @param data the transaction data to check function checkParameters( Role storage role, uint256 scopeConfig, address targetAddress, bytes memory data ) internal view { bytes4 functionSig = bytes4(data); (, , uint256 length) = unpackFunction(scopeConfig); for (uint256 i = 0; i < length; i++) { ( bool isScoped, ParameterType paramType, Comparison paramComp ) = unpackParameter(scopeConfig, i); if (!isScoped) { continue; } bytes32 value; if (paramType != ParameterType.Static) { value = pluckDynamicValue(data, paramType, i); } else { value = pluckStaticValue(data, i); } bytes32 key = keyForCompValues(targetAddress, functionSig, i); if (paramComp != Comparison.OneOf) { compare(paramComp, role.compValues[key], value); } else { compareOneOf(role.compValuesOneOf[key], value); } } } function compare( Comparison paramComp, bytes32 compValue, bytes32 value ) internal pure { if (paramComp == Comparison.EqualTo && value != compValue) { revert ParameterNotAllowed(); } else if (paramComp == Comparison.GreaterThan && value <= compValue) { revert ParameterLessThanAllowed(); } else if (paramComp == Comparison.LessThan && value >= compValue) { revert ParameterGreaterThanAllowed(); } } function compareOneOf(bytes32[] storage compValue, bytes32 value) internal view { for (uint256 i = 0; i < compValue.length; i++) { if (value == compValue[i]) return; } revert ParameterNotOneOfAllowed(); } /* * * SETTERS * */ function allowTarget( Role storage role, uint16 roleId, address targetAddress, ExecutionOptions options ) external { role.targets[targetAddress] = TargetAddress(Clearance.Target, options); emit AllowTarget(roleId, targetAddress, options); } function revokeTarget( Role storage role, uint16 roleId, address targetAddress ) external { role.targets[targetAddress] = TargetAddress( Clearance.None, ExecutionOptions.None ); emit RevokeTarget(roleId, targetAddress); } function scopeTarget( Role storage role, uint16 roleId, address targetAddress ) external { role.targets[targetAddress] = TargetAddress( Clearance.Function, ExecutionOptions.None ); emit ScopeTarget(roleId, targetAddress); } function scopeAllowFunction( Role storage role, uint16 roleId, address targetAddress, bytes4 functionSig, ExecutionOptions options ) external { /* * packLeft( * 0 -> start from a fresh scopeConfig * options -> externally provided options * true -> mark the function as wildcarded * 0 -> length * ) */ uint256 scopeConfig = packLeft(0, options, true, 0); role.functions[ keyForFunctions(targetAddress, functionSig) ] = scopeConfig; emit ScopeAllowFunction( roleId, targetAddress, functionSig, options, scopeConfig ); } function scopeRevokeFunction( Role storage role, uint16 roleId, address targetAddress, bytes4 functionSig ) external { role.functions[keyForFunctions(targetAddress, functionSig)] = 0; emit ScopeRevokeFunction(roleId, targetAddress, functionSig, 0); } function scopeFunction( Role storage role, uint16 roleId, address targetAddress, bytes4 functionSig, bool[] memory isScoped, ParameterType[] memory paramType, Comparison[] memory paramComp, bytes[] calldata compValue, ExecutionOptions options ) external { uint256 length = isScoped.length; if ( length != paramType.length || length != paramComp.length || length != compValue.length ) { revert ArraysDifferentLength(); } if (length > SCOPE_MAX_PARAMS) { revert ScopeMaxParametersExceeded(); } for (uint256 i = 0; i < length; i++) { if (isScoped[i]) { enforceComp(paramType[i], paramComp[i]); enforceCompValue(paramType[i], compValue[i]); } } /* * packLeft( * 0 -> start from a fresh scopeConfig * options -> externally provided options * false -> mark the function as not wildcarded * 0 -> length * ) */ uint256 scopeConfig = packLeft(0, options, false, length); for (uint256 i = 0; i < length; i++) { scopeConfig = packRight( scopeConfig, i, isScoped[i], paramType[i], paramComp[i] ); } //set scopeConfig role.functions[ keyForFunctions(targetAddress, functionSig) ] = scopeConfig; //set compValues for (uint256 i = 0; i < length; i++) { role.compValues[ keyForCompValues(targetAddress, functionSig, i) ] = compressCompValue(paramType[i], compValue[i]); } emit ScopeFunction( roleId, targetAddress, functionSig, isScoped, paramType, paramComp, compValue, options, scopeConfig ); } function scopeFunctionExecutionOptions( Role storage role, uint16 roleId, address targetAddress, bytes4 functionSig, ExecutionOptions options ) external { bytes32 key = keyForFunctions(targetAddress, functionSig); //set scopeConfig uint256 scopeConfig = packOptions(role.functions[key], options); role.functions[ keyForFunctions(targetAddress, functionSig) ] = scopeConfig; emit ScopeFunctionExecutionOptions( roleId, targetAddress, functionSig, options, scopeConfig ); } function scopeParameter( Role storage role, uint16 roleId, address targetAddress, bytes4 functionSig, uint256 index, ParameterType paramType, Comparison paramComp, bytes calldata compValue ) external { if (index >= SCOPE_MAX_PARAMS) { revert ScopeMaxParametersExceeded(); } enforceComp(paramType, paramComp); enforceCompValue(paramType, compValue); // set scopeConfig bytes32 key = keyForFunctions(targetAddress, functionSig); uint256 scopeConfig = packParameter( role.functions[key], index, true, // isScoped paramType, paramComp ); role.functions[key] = scopeConfig; // set compValue role.compValues[ keyForCompValues(targetAddress, functionSig, index) ] = compressCompValue(paramType, compValue); emit ScopeParameter( roleId, targetAddress, functionSig, index, paramType, paramComp, compValue, scopeConfig ); } function scopeParameterAsOneOf( Role storage role, uint16 roleId, address targetAddress, bytes4 functionSig, uint256 index, ParameterType paramType, bytes[] calldata compValues ) external { if (index >= SCOPE_MAX_PARAMS) { revert ScopeMaxParametersExceeded(); } if (compValues.length < 2) { revert NotEnoughCompValuesForOneOf(); } for (uint256 i = 0; i < compValues.length; i++) { enforceCompValue(paramType, compValues[i]); } // set scopeConfig bytes32 key = keyForFunctions(targetAddress, functionSig); uint256 scopeConfig = packParameter( role.functions[key], index, true, // isScoped paramType, Comparison.OneOf ); role.functions[key] = scopeConfig; // set compValue key = keyForCompValues(targetAddress, functionSig, index); role.compValuesOneOf[key] = new bytes32[](compValues.length); for (uint256 i = 0; i < compValues.length; i++) { role.compValuesOneOf[key][i] = compressCompValue( paramType, compValues[i] ); } emit ScopeParameterAsOneOf( roleId, targetAddress, functionSig, index, paramType, compValues, scopeConfig ); } function unscopeParameter( Role storage role, uint16 roleId, address targetAddress, bytes4 functionSig, uint256 index ) external { if (index >= SCOPE_MAX_PARAMS) { revert ScopeMaxParametersExceeded(); } // set scopeConfig bytes32 key = keyForFunctions(targetAddress, functionSig); uint256 scopeConfig = packParameter( role.functions[key], index, false, // isScoped ParameterType(0), Comparison(0) ); role.functions[key] = scopeConfig; emit UnscopeParameter( roleId, targetAddress, functionSig, index, scopeConfig ); } function enforceComp(ParameterType paramType, Comparison paramComp) internal pure { if (paramComp == Comparison.OneOf) { revert UnsuitableOneOfComparison(); } if ( (paramType != ParameterType.Static) && (paramComp != Comparison.EqualTo) ) { revert UnsuitableRelativeComparison(); } } function enforceCompValue(ParameterType paramType, bytes calldata compValue) internal pure { if (paramType == ParameterType.Static && compValue.length != 32) { revert UnsuitableStaticCompValueSize(); } if ( paramType == ParameterType.Dynamic32 && compValue.length % 32 != 0 ) { revert UnsuitableDynamic32CompValueSize(); } } /* * * HELPERS * */ function pluckDynamicValue( bytes memory data, ParameterType paramType, uint256 index ) internal pure returns (bytes32) { assert(paramType != ParameterType.Static); // pre-check: is there a word available for the current parameter at argumentsBlock? if (data.length < 4 + index * 32 + 32) { revert CalldataOutOfBounds(); } /* * Encoded calldata: * 4 bytes -> function selector * 32 bytes -> sequence, one chunk per parameter * * There is one (byte32) chunk per parameter. Depending on type it contains: * Static -> value encoded inline (not plucked by this function) * Dynamic -> a byte offset to encoded data payload * Dynamic32 -> a byte offset to encoded data payload * Note: Fixed Sized Arrays (e.g., bool[2]), are encoded inline * Note: Nested types also do not follow the above described rules, and are unsupported * Note: The offset to payload does not include 4 bytes for functionSig * * * At encoded payload, the first 32 bytes are the length encoding of the parameter payload. Depending on ParameterType: * Dynamic -> length in bytes * Dynamic32 -> length in bytes32 * Note: Dynamic types are: bytes, string * Note: Dynamic32 types are non-nested arrays: address[] bytes32[] uint[] etc */ // the start of the parameter block // 32 bytes - length encoding of the data bytes array // 4 bytes - function sig uint256 argumentsBlock; assembly { argumentsBlock := add(data, 36) } // the two offsets are relative to argumentsBlock uint256 offset = index * 32; uint256 offsetPayload; assembly { offsetPayload := mload(add(argumentsBlock, offset)) } uint256 lengthPayload; assembly { lengthPayload := mload(add(argumentsBlock, offsetPayload)) } // account for: // 4 bytes - functionSig // 32 bytes - length encoding for the parameter payload uint256 start = 4 + offsetPayload + 32; uint256 end = start + ( paramType == ParameterType.Dynamic32 ? lengthPayload * 32 : lengthPayload ); // are we slicing out of bounds? if (data.length < end) { revert CalldataOutOfBounds(); } return keccak256(slice(data, start, end)); } function pluckStaticValue(bytes memory data, uint256 index) internal pure returns (bytes32) { // pre-check: is there a word available for the current parameter at argumentsBlock? if (data.length < 4 + index * 32 + 32) { revert CalldataOutOfBounds(); } uint256 offset = 4 + index * 32; bytes32 value; assembly { // add 32 - jump over the length encoding of the data bytes array value := mload(add(32, add(data, offset))) } return value; } function slice( bytes memory data, uint256 start, uint256 end ) internal pure returns (bytes memory result) { result = new bytes(end - start); for (uint256 j = start; j < end; j++) { result[j - start] = data[j]; } } /* * pack/unpack are bit helpers for scopeConfig */ function packParameter( uint256 scopeConfig, uint256 index, bool isScoped, ParameterType paramType, Comparison paramComp ) internal pure returns (uint256) { (ExecutionOptions options, , uint256 prevLength) = unpackFunction( scopeConfig ); uint256 nextLength = index + 1 > prevLength ? index + 1 : prevLength; return packLeft( packRight(scopeConfig, index, isScoped, paramType, paramComp), options, false, // isWildcarded=false nextLength ); } function packOptions(uint256 scopeConfig, ExecutionOptions options) internal pure returns (uint256) { uint256 optionsMask = 3 << 254; scopeConfig &= ~optionsMask; scopeConfig |= uint256(options) << 254; return scopeConfig; } function packLeft( uint256 scopeConfig, ExecutionOptions options, bool isWildcarded, uint256 length ) internal pure returns (uint256) { // LEFT SIDE // 2 bits -> options // 1 bits -> isWildcarded // 5 bits -> unused // 8 bits -> length // RIGHT SIDE // 48 bits -> isScoped // 96 bits -> paramType (2 bits per entry 48*2) // 96 bits -> paramComp (2 bits per entry 48*2) // Wipe the LEFT SIDE clean. Start from there scopeConfig = (scopeConfig << 16) >> 16; // set options -> 256 - 2 = 254 scopeConfig |= uint256(options) << 254; // set isWildcarded -> 256 - 2 - 1 = 253 if (isWildcarded) { scopeConfig |= 1 << 253; } // set Length -> 48 + 96 + 96 = 240 scopeConfig |= length << 240; return scopeConfig; } function packRight( uint256 scopeConfig, uint256 index, bool isScoped, ParameterType paramType, Comparison paramComp ) internal pure returns (uint256) { // LEFT SIDE // 2 bits -> options // 1 bits -> isWildcarded // 5 bits -> unused // 8 bits -> length // RIGHT SIDE // 48 bits -> isScoped // 96 bits -> paramType (2 bits per entry 48*2) // 96 bits -> paramComp (2 bits per entry 48*2) uint256 isScopedMask = 1 << (index + 96 + 96); uint256 paramTypeMask = 3 << (index * 2 + 96); uint256 paramCompMask = 3 << (index * 2); if (isScoped) { scopeConfig |= isScopedMask; } else { scopeConfig &= ~isScopedMask; } scopeConfig &= ~paramTypeMask; scopeConfig |= uint256(paramType) << (index * 2 + 96); scopeConfig &= ~paramCompMask; scopeConfig |= uint256(paramComp) << (index * 2); return scopeConfig; } function unpackFunction(uint256 scopeConfig) internal pure returns ( ExecutionOptions options, bool isWildcarded, uint256 length ) { uint256 isWildcardedMask = 1 << 253; options = ExecutionOptions(scopeConfig >> 254); isWildcarded = scopeConfig & isWildcardedMask != 0; length = (scopeConfig << 8) >> 248; } function unpackParameter(uint256 scopeConfig, uint256 index) internal pure returns ( bool isScoped, ParameterType paramType, Comparison paramComp ) { uint256 isScopedMask = 1 << (index + 96 + 96); uint256 paramTypeMask = 3 << (index * 2 + 96); uint256 paramCompMask = 3 << (index * 2); isScoped = (scopeConfig & isScopedMask) != 0; paramType = ParameterType( (scopeConfig & paramTypeMask) >> (index * 2 + 96) ); paramComp = Comparison((scopeConfig & paramCompMask) >> (index * 2)); } function keyForFunctions(address targetAddress, bytes4 functionSig) public pure returns (bytes32) { return bytes32(abi.encodePacked(targetAddress, functionSig)); } function keyForCompValues( address targetAddress, bytes4 functionSig, uint256 index ) public pure returns (bytes32) { return bytes32(abi.encodePacked(targetAddress, functionSig, uint8(index))); } function compressCompValue( ParameterType paramType, bytes calldata compValue ) internal pure returns (bytes32) { return paramType == ParameterType.Static ? bytes32(compValue) : keccak256(compValue); } } // SPDX-License-Identifier: LGPL-3.0-only /// @title Zodiac Avatar - A contract that manages modules that can execute transactions via this contract. pragma solidity >=0.7.0 <0.9.0; import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol"; interface IAvatar { /// @dev Enables a module on the avatar. /// @notice Can only be called by the avatar. /// @notice Modules should be stored as a linked list. /// @notice Must emit EnabledModule(address module) if successful. /// @param module Module to be enabled. function enableModule(address module) external; /// @dev Disables a module on the avatar. /// @notice Can only be called by the avatar. /// @notice Must emit DisabledModule(address module) if successful. /// @param prevModule Address that pointed to the module to be removed in the linked list /// @param module Module to be removed. function disableModule(address prevModule, address module) external; /// @dev Allows a Module to execute a transaction. /// @notice Can only be called by an enabled module. /// @notice Must emit ExecutionFromModuleSuccess(address module) if successful. /// @notice Must emit ExecutionFromModuleFailure(address module) if unsuccessful. /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction: 0 == call, 1 == delegate call. function execTransactionFromModule( address to, uint256 value, bytes memory data, Enum.Operation operation ) external returns (bool success); /// @dev Allows a Module to execute a transaction and return data /// @notice Can only be called by an enabled module. /// @notice Must emit ExecutionFromModuleSuccess(address module) if successful. /// @notice Must emit ExecutionFromModuleFailure(address module) if unsuccessful. /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction: 0 == call, 1 == delegate call. function execTransactionFromModuleReturnData( address to, uint256 value, bytes memory data, Enum.Operation operation ) external returns (bool success, bytes memory returnData); /// @dev Returns if an module is enabled /// @return True if the module is enabled function isModuleEnabled(address module) external view returns (bool); /// @dev Returns array of modules. /// @param start Start of the page. /// @param pageSize Maximum number of modules that should be returned. /// @return array Array of modules. /// @return next Start of the next page. function getModulesPaginated(address start, uint256 pageSize) external view returns (address[] memory array, address next); } // SPDX-License-Identifier: LGPL-3.0-only /// @title Module Interface - A contract that can pass messages to a Module Manager contract if enabled by that contract. pragma solidity >=0.7.0 <0.9.0; import "../interfaces/IAvatar.sol"; import "../factory/FactoryFriendly.sol"; import "../guard/Guardable.sol"; abstract contract Module is FactoryFriendly, Guardable { /// @dev Emitted each time the avatar is set. event AvatarSet(address indexed previousAvatar, address indexed newAvatar); /// @dev Emitted each time the Target is set. event TargetSet(address indexed previousTarget, address indexed newTarget); /// @dev Address that will ultimately execute function calls. address public avatar; /// @dev Address that this module will pass transactions to. address public target; /// @dev Sets the avatar to a new avatar (`newAvatar`). /// @notice Can only be called by the current owner. function setAvatar(address _avatar) public onlyOwner { address previousAvatar = avatar; avatar = _avatar; emit AvatarSet(previousAvatar, _avatar); } /// @dev Sets the target to a new target (`newTarget`). /// @notice Can only be called by the current owner. function setTarget(address _target) public onlyOwner { address previousTarget = target; target = _target; emit TargetSet(previousTarget, _target); } /// @dev Passes a transaction to be executed by the avatar. /// @notice Can only be called by this contract. /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction: 0 == call, 1 == delegate call. function exec( address to, uint256 value, bytes memory data, Enum.Operation operation ) internal returns (bool success) { /// check if a transactioon guard is enabled. if (guard != address(0)) { IGuard(guard).checkTransaction( /// Transaction info used by module transactions to, value, data, operation, /// Zero out the redundant transaction information only used for Safe multisig transctions 0, 0, 0, address(0), payable(0), bytes("0x"), address(0) ); } success = IAvatar(target).execTransactionFromModule( to, value, data, operation ); if (guard != address(0)) { IGuard(guard).checkAfterExecution(bytes32("0x"), success); } return success; } /// @dev Passes a transaction to be executed by the target and returns data. /// @notice Can only be called by this contract. /// @param to Destination address of module transaction. /// @param value Ether value of module transaction. /// @param data Data payload of module transaction. /// @param operation Operation type of module transaction: 0 == call, 1 == delegate call. function execAndReturnData( address to, uint256 value, bytes memory data, Enum.Operation operation ) internal returns (bool success, bytes memory returnData) { /// check if a transactioon guard is enabled. if (guard != address(0)) { IGuard(guard).checkTransaction( /// Transaction info used by module transactions to, value, data, operation, /// Zero out the redundant transaction information only used for Safe multisig transctions 0, 0, 0, address(0), payable(0), bytes("0x"), address(0) ); } (success, returnData) = IAvatar(target) .execTransactionFromModuleReturnData(to, value, data, operation); if (guard != address(0)) { IGuard(guard).checkAfterExecution(bytes32("0x"), success); } return (success, returnData); } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @title Enum - Collection of enums /// @author Richard Meissner - <[email protected]> contract Enum { enum Operation {Call, DelegateCall} } // SPDX-License-Identifier: LGPL-3.0-only /// @title Zodiac FactoryFriendly - A contract that allows other contracts to be initializable and pass bytes as arguments to define contract state pragma solidity >=0.7.0 <0.9.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; abstract contract FactoryFriendly is OwnableUpgradeable { function setUp(bytes memory initializeParams) public virtual; } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@gnosis.pm/safe-contracts/contracts/interfaces/IERC165.sol"; import "./BaseGuard.sol"; /// @title Guardable - A contract that manages fallback calls made to this contract contract Guardable is OwnableUpgradeable { event ChangedGuard(address guard); address public guard; /// @dev Set a guard that checks transactions before execution /// @param _guard The address of the guard to be used or the 0 address to disable the guard function setGuard(address _guard) external onlyOwner { if (_guard != address(0)) { require( BaseGuard(_guard).supportsInterface(type(IGuard).interfaceId), "Guard does not implement IERC165" ); } guard = _guard; emit ChangedGuard(guard); } function getGuard() external view returns (address _guard) { return guard; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; /// @notice More details at https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/introspection/IERC165.sol interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol"; import "@gnosis.pm/safe-contracts/contracts/interfaces/IERC165.sol"; import "../interfaces/IGuard.sol"; abstract contract BaseGuard is IERC165 { function supportsInterface(bytes4 interfaceId) external pure override returns (bool) { return interfaceId == type(IGuard).interfaceId || // 0xe6d7a83a interfaceId == type(IERC165).interfaceId; // 0x01ffc9a7 } /// Module transactions only use the first four parameters: to, value, data, and operation. /// Module.sol hardcodes the remaining parameters as 0 since they are not used for module transactions. /// This interface is used to maintain compatibilty with Gnosis Safe transaction guards. function checkTransaction( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes memory signatures, address msgSender ) external virtual; function checkAfterExecution(bytes32 txHash, bool success) external virtual; } // SPDX-License-Identifier: LGPL-3.0-only pragma solidity >=0.7.0 <0.9.0; import "@gnosis.pm/safe-contracts/contracts/common/Enum.sol"; interface IGuard { function checkTransaction( address to, uint256 value, bytes memory data, Enum.Operation operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address payable refundReceiver, bytes memory signatures, address msgSender ) external; function checkAfterExecution(bytes32 txHash, bool success) external; }
Returns array of modules. start Start of the page. pageSize Maximum number of modules that should be returned. return array Array of modules. return next Start of the next page. Init array with max page size Populate return array Set correct size of returned array solhint-disable-next-line no-inline-assembly
function getModulesPaginated(address start, uint256 pageSize) external view returns (address[] memory array, address next) { array = new address[](pageSize); uint256 moduleCount = 0; address currentModule = modules[start]; while ( currentModule != address(0x0) && currentModule != SENTINEL_MODULES && moduleCount < pageSize ) { array[moduleCount] = currentModule; currentModule = modules[currentModule]; moduleCount++; } next = currentModule; assembly { mstore(array, moduleCount) } }
6,977,354
./full_match/1/0xEBc651F4A8C898b5C45FBEEEC9CF125bB8b452E1/sources/@openzeppelin/contracts@4.3.2/token/ERC721/IERC721.sol
Required interface of an ERC721 compliant contract./
interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom( address from, address to, uint256 tokenId ) external; function transferFrom( address from, address to, uint256 tokenId ) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function tokenURI(uint256) external view returns (string memory); function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; }
3,170,586
/** *Submitted for verification at Etherscan.io on 2021-09-04 */ /** *Submitted for verification at Etherscan.io on 2021-09-01 */ // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require( newOwner != address(0), "Ownable: new owner is the zero address" ); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require( currentAllowance >= amount, "ERC20: transfer amount exceeds allowance" ); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender] + addedValue ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require( currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero" ); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require( senderBalance >= amount, "ERC20: transfer amount exceeds balance" ); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } contract FirstGold is Context, Ownable, ERC20 { // first contract is available at https://etherscan.io/address/0xff9c1b15b16263c61d017ee9f65c50e4ae0113d7 address public firstContractAddress = 0xc9Cb0FEe73f060Db66D2693D92d75c825B1afdbF; IERC721Enumerable public firstContract; // Give out 10,000 First Gold for every first Bag that a user holds uint256 public FirstGoldPerTokenId = 10000 * (10**decimals()); // tokenIdStart of 1 is First on the following lines in the first contract: /** function claim(uint256 tokenId) public nonReentrant { require(tokenId > 0 && tokenId < 7778, "Token ID invalid"); _safeMint(_msgSender(), tokenId); } */ uint256 public tokenIdStart = 1; // tokenIdEnd of 8000 is First on the following lines in the first contract: /** function ownerClaim(uint256 tokenId) public nonReentrant onlyOwner { require(tokenId > 7777 && tokenId < 8001, "Token ID invalid"); _safeMint(owner(), tokenId); } */ uint256 public tokenIdEnd = 8000; // Seasons are used to allow users to claim tokens regularly. Seasons are // decided by the DAO. uint256 public season = 0; // Track claimed tokens within a season // IMPORTANT: The format of the mapping is: // claimedForSeason[season][tokenId][claimed] mapping(uint256 => mapping(uint256 => bool)) public seasonClaimedByTokenId; constructor() Ownable() ERC20("First Gold", "BGLD") { // Transfer ownership to the first DAO // Ownable by OpenZeppelin automatically sets owner to msg.sender, but // we're going to be using a separate wallet for deployment transferOwnership(_msgSender()); firstContract = IERC721Enumerable(firstContractAddress); } /// @notice Claim First Gold for a given first ID /// @param tokenId The tokenId of the first NFT function claimById(uint256 tokenId) external { // Follow the Checks-Effects-Interactions pattern to prevent reentrancy // attacks // Checks // Check that the msgSender owns the token that is being claimed require( _msgSender() == firstContract.ownerOf(tokenId), "MUST_OWN_TOKEN_ID" ); // Further Checks, Effects, and Interactions are contained within the // _claim() function _claim(tokenId, _msgSender()); } /// @notice Claim First Gold for all tokens owned by the sender /// @notice This function will run out of gas if you have too much first! If /// this is a concern, you should use claimRangeForOwner and claim First /// Gold in batches. function claimAllForOwner() external { uint256 tokenBalanceOwner = firstContract.balanceOf(_msgSender()); // Checks require(tokenBalanceOwner > 0, "NO_TOKENS_OWNED"); // i < tokenBalanceOwner because tokenBalanceOwner is 1-indexed for (uint256 i = 0; i < tokenBalanceOwner; i++) { // Further Checks, Effects, and Interactions are contained within // the _claim() function _claim( firstContract.tokenOfOwnerByIndex(_msgSender(), i), _msgSender() ); } } /// @notice Claim First Gold for all tokens owned by the sender within a /// given range /// @notice This function is useful if you own too much first to claim all at /// once or if you want to leave some first unclaimed. If you leave first /// unclaimed, however, you cannot claim it once the next season starts. function claimRangeForOwner(uint256 ownerIndexStart, uint256 ownerIndexEnd) external { uint256 tokenBalanceOwner = firstContract.balanceOf(_msgSender()); // Checks require(tokenBalanceOwner > 0, "NO_TOKENS_OWNED"); // We use < for ownerIndexEnd and tokenBalanceOwner because // tokenOfOwnerByIndex is 0-indexed while the token balance is 1-indexed require( ownerIndexStart >= 0 && ownerIndexEnd < tokenBalanceOwner, "INDEX_OUT_OF_RANGE" ); // i <= ownerIndexEnd because ownerIndexEnd is 0-indexed for (uint256 i = ownerIndexStart; i <= ownerIndexEnd; i++) { // Further Checks, Effects, and Interactions are contained within // the _claim() function _claim( firstContract.tokenOfOwnerByIndex(_msgSender(), i), _msgSender() ); } } /// @dev Internal function to mint first upon claiming function _claim(uint256 tokenId, address tokenOwner) internal { // Checks // Check that the token ID is in range // We use >= and <= to here because all of the token IDs are 0-indexed require( tokenId >= tokenIdStart && tokenId <= tokenIdEnd, "TOKEN_ID_OUT_OF_RANGE" ); // Check that First Gold have not already been claimed this season // for a given tokenId require( !seasonClaimedByTokenId[season][tokenId], "GOLD_CLAIMED_FOR_TOKEN_ID" ); // Effects // Mark that First Gold has been claimed for this season for the // given tokenId seasonClaimedByTokenId[season][tokenId] = true; // Interactions // Send First Gold to the owner of the token ID _mint(tokenOwner, FirstGoldPerTokenId); } /// @notice Allows the DAO to mint new tokens for use within the first /// Ecosystem /// @param amountDisplayValue The amount of first to mint. This should be /// input as the display value, not in raw decimals. If you want to mint /// 100 first, you should enter "100" rather than the value of 100 * 10^18. function daoMint(uint256 amountDisplayValue) external onlyOwner { _mint(owner(), amountDisplayValue * (10**decimals())); } /// @notice Allows the DAO to set a new contract address for first. This is /// relevant in the event that first migrates to a new contract. /// @param firstContractAddress_ The new contract address for first function daoSetfirstContractAddress(address firstContractAddress_) external onlyOwner { firstContractAddress = firstContractAddress_; firstContract = IERC721Enumerable(firstContractAddress); } /// @notice Allows the DAO to set the token IDs that are eligible to claim /// first /// @param tokenIdStart_ The start of the eligible token range /// @param tokenIdEnd_ The end of the eligible token range /// @dev This is relevant in case a future first contract has a different /// total supply of first function daoSetTokenIdRange(uint256 tokenIdStart_, uint256 tokenIdEnd_) external onlyOwner { tokenIdStart = tokenIdStart_; tokenIdEnd = tokenIdEnd_; } /// @notice Allows the DAO to set a season for new First Gold claims /// @param season_ The season to use for claiming first function daoSetSeason(uint256 season_) public onlyOwner { season = season_; } /// @notice Allows the DAO to set the amount of First Gold that is /// claimed per token ID /// @param FirstGoldDisplayValue The amount of first a user can claim. /// This should be input as the display value, not in raw decimals. If you /// want to mint 100 first, you should enter "100" rather than the value of /// 100 * 10^18. function daoSetFirstGoldPerTokenId(uint256 FirstGoldDisplayValue) public onlyOwner { FirstGoldPerTokenId = FirstGoldDisplayValue * (10**decimals()); } /// @notice Allows the DAO to set the season and First Gold per token ID /// in one transaction. This ensures that there is not a gap where a user /// can claim more First Gold than others /// @param season_ The season to use for claiming first /// @param FirstGoldDisplayValue The amount of first a user can claim. /// This should be input as the display value, not in raw decimals. If you /// want to mint 100 first, you should enter "100" rather than the value of /// 100 * 10^18. /// @dev We would save a tiny amount of gas by modifying the season and /// FirstGold variables directly. It is better practice for security, /// however, to avoid repeating code. This function is so rarely used that /// it's not worth moving these values into their own internal function to /// skip the gas used on the modifier check. function daoSetSeasonAndFirstGoldPerTokenID( uint256 season_, uint256 FirstGoldDisplayValue ) external onlyOwner { daoSetSeason(season_); daoSetFirstGoldPerTokenId(FirstGoldDisplayValue); } }
ERC-721 Non-Fungible Token Standard, optional enumeration extension/
interface IERC721Enumerable is IERC721 { function totalSupply() external view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); function tokenByIndex(uint256 index) external view returns (uint256); } }
124,211
/* ** ** dddddddd ** PPPPPPPPPPPPPPPPP d::::::d DDDDDDDDDDDDD AAA OOOOOOOOO ** P::::::::::::::::P d::::::d D::::::::::::DDD A:::A OO:::::::::OO ** P::::::PPPPPP:::::P d::::::d D:::::::::::::::DD A:::::A OO:::::::::::::OO ** PP:::::P P:::::P d:::::d DDD:::::DDDDD:::::D A:::::::A O:::::::OOO:::::::O ** P::::P P:::::Paaaaaaaaaaaaa nnnn nnnnnnnn ddddddddd:::::d aaaaaaaaaaaaa D:::::D D:::::D A:::::::::A O::::::O O::::::O ** P::::P P:::::Pa::::::::::::a n:::nn::::::::nn dd::::::::::::::d a::::::::::::a D:::::D D:::::D A:::::A:::::A O:::::O O:::::O ** P::::PPPPPP:::::P aaaaaaaaa:::::an::::::::::::::nn d::::::::::::::::d aaaaaaaaa:::::a D:::::D D:::::D A:::::A A:::::A O:::::O O:::::O ** P:::::::::::::PP a::::ann:::::::::::::::nd:::::::ddddd:::::d a::::a D:::::D D:::::D A:::::A A:::::A O:::::O O:::::O ** P::::PPPPPPPPP aaaaaaa:::::a n:::::nnnn:::::nd::::::d d:::::d aaaaaaa:::::a D:::::D D:::::D A:::::A A:::::A O:::::O O:::::O ** P::::P aa::::::::::::a n::::n n::::nd:::::d d:::::d aa::::::::::::a D:::::D D:::::D A:::::AAAAAAAAA:::::A O:::::O O:::::O ** P::::P a::::aaaa::::::a n::::n n::::nd:::::d d:::::d a::::aaaa::::::a D:::::D D:::::DA:::::::::::::::::::::A O:::::O O:::::O ** P::::P a::::a a:::::a n::::n n::::nd:::::d d:::::d a::::a a:::::a D:::::D D:::::DA:::::AAAAAAAAAAAAA:::::A O::::::O O::::::O ** PP::::::PP a::::a a:::::a n::::n n::::nd::::::ddddd::::::dda::::a a:::::a DDD:::::DDDDD:::::DA:::::A A:::::AO:::::::OOO:::::::O ** P::::::::P a:::::aaaa::::::a n::::n n::::n d:::::::::::::::::da:::::aaaa::::::a D:::::::::::::::DDA:::::A A:::::AOO:::::::::::::OO ** P::::::::P a::::::::::aa:::a n::::n n::::n d:::::::::ddd::::d a::::::::::aa:::aD::::::::::::DDD A:::::A A:::::A OO:::::::::OO ** PPPPPPPPPP aaaaaaaaaa aaaa nnnnnn nnnnnn ddddddddd ddddd aaaaaaaaaa aaaaDDDDDDDDDDDDD AAAAAAA AAAAAAA OOOOOOOOO ** */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./Operations.sol"; import "./ITerminalV1_1.sol"; contract PandaRefund is Ownable, ReentrancyGuard { using SafeERC20 for IERC20; IERC20 public pandaToken; ITerminalV1_1 public terminalv1_1; uint256 public treasuryRedeemAmount; bytes32 public merkleRoot; bool public openRefund = true; uint256[] private operationsRedeem = [Operations.Redeem]; mapping(address => uint256) public refundMap; uint256 public lastNow; uint256 public timeInterval = 7 days; uint256 public refundRateBase = 10000; uint256 public refundRateValue = 9584; uint256 public constant PandaTotal = 1_928_747_627 ether; uint256 public constant PandaPerETH = 500_000; uint256 public constant PANDADAO_PROJECT_ID = 409; event Redeem(address indexed recipient, uint256 tokenAmount, uint256 receiveEther); event Treasury_Redeem(address recipient, uint256 tokenAmount); event MerkleRootChanged(bytes32 merkleRoot); event RefundOpenChanged(bool open); event TimeIntervalChanged(uint256 time); event RefundRateValueChanged(uint256 time); event WithdrawERC20(address recipient, address tokenAddress, uint256 tokenAmount); event WithdrawEther(address recipient, uint256 amount); modifier refundOpenning() { require(openRefund, "PandaDAO: refund close."); _; } modifier timeOut() { require(block.timestamp - lastNow < timeInterval, "PandaDAO: time out!"); _; } /** * @dev Constructor. */ constructor( address pandaToken_, address terminalv1_1_ ) { pandaToken = IERC20(pandaToken_); terminalv1_1 = ITerminalV1_1(terminalv1_1_); lastNow = block.timestamp; } /** * @dev redeem $PANDA tokens. * @param amount The amount of the $PANDA. */ function redeem(uint256 amount, uint256 totalAmount, bytes32[] calldata merkleProof) external nonReentrant refundOpenning timeOut{ require(amount > 0, "PandaDAO: Invalid amount required."); require(pandaToken.balanceOf(msg.sender) >= amount, "PandaDAO: you do not have enough PandaToken."); require(totalAmount >= refundMap[msg.sender] + amount, "PandaDAO: you do not have enough PandaToken before refund."); bytes32 leaf = keccak256(abi.encodePacked(msg.sender, totalAmount)); bool valid = MerkleProof.verify(merkleProof, merkleRoot, leaf); require(valid, "PandaDAO: Invalid proof required."); uint256 etherAmount = amount * refundRateValue / PandaPerETH / refundRateBase; require(address(this).balance >= etherAmount, "PandaDAO: Refund Contract dont have enough ether!"); refundMap[msg.sender] = refundMap[msg.sender] + amount; terminalv1_1.redeem(msg.sender, PANDADAO_PROJECT_ID, amount, 0, payable(msg.sender), false); treasuryRedeemAmount += amount; (bool success,) = msg.sender.call{value:etherAmount}(""); require(success, "redeem ether fail!"); emit Redeem(msg.sender, amount, etherAmount); } /** * @dev treasury redeem $PANDA tokens. */ function treasuryRedeem() external nonReentrant onlyOwner { require(treasuryRedeemAmount > 0, "PandaDAO: Invalid amount required."); require(pandaToken.balanceOf(msg.sender) >= treasuryRedeemAmount, "PandaDAO: you do not have enough PandaToken."); terminalv1_1.redeem(msg.sender, PANDADAO_PROJECT_ID, treasuryRedeemAmount, 0, payable(msg.sender), false); treasuryRedeemAmount = 0; emit Treasury_Redeem(msg.sender, treasuryRedeemAmount); } /** * @dev Sets the merkle root. Only callable if the root is not yet set. * @param _merkleRoot The merkle root to set. */ function setMerkleRoot(bytes32 _merkleRoot) public onlyOwner { merkleRoot = _merkleRoot; emit MerkleRootChanged(_merkleRoot); } function setRefundOpen(bool open_) external onlyOwner { openRefund = open_; emit RefundOpenChanged(open_); } function refreshLastNow() external onlyOwner { lastNow = block.timestamp; } function setTimeInterval(uint256 timeInterval_) external onlyOwner { timeInterval = timeInterval_; emit TimeIntervalChanged(timeInterval_); } function setRefundRateValue(uint256 value_) external onlyOwner { refundRateValue = value_; emit RefundRateValueChanged(value_); } /** * @dev withdrawERC20 tokens. * @param tokenAddress token * @param tokenAmount amount */ function withdrawERC20( address tokenAddress, uint256 tokenAmount ) external onlyOwner { require(tokenAddress != address(0), "Zero Token address!"); IERC20(tokenAddress).transfer(msg.sender, tokenAmount); emit WithdrawERC20(msg.sender, tokenAddress, tokenAmount); } /** * @dev withdraw Ether. * @param amount amount */ function withdrawEther(uint256 amount) external onlyOwner { (bool success,) = msg.sender.call{value:amount}(""); require(success, "withdrawEther fail!"); emit WithdrawEther(msg.sender, amount); } fallback () external payable {} receive () external payable {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /* ** ** dddddddd ** PPPPPPPPPPPPPPPPP d::::::d DDDDDDDDDDDDD AAA OOOOOOOOO ** P::::::::::::::::P d::::::d D::::::::::::DDD A:::A OO:::::::::OO ** P::::::PPPPPP:::::P d::::::d D:::::::::::::::DD A:::::A OO:::::::::::::OO ** PP:::::P P:::::P d:::::d DDD:::::DDDDD:::::D A:::::::A O:::::::OOO:::::::O ** P::::P P:::::Paaaaaaaaaaaaa nnnn nnnnnnnn ddddddddd:::::d aaaaaaaaaaaaa D:::::D D:::::D A:::::::::A O::::::O O::::::O ** P::::P P:::::Pa::::::::::::a n:::nn::::::::nn dd::::::::::::::d a::::::::::::a D:::::D D:::::D A:::::A:::::A O:::::O O:::::O ** P::::PPPPPP:::::P aaaaaaaaa:::::an::::::::::::::nn d::::::::::::::::d aaaaaaaaa:::::a D:::::D D:::::D A:::::A A:::::A O:::::O O:::::O ** P:::::::::::::PP a::::ann:::::::::::::::nd:::::::ddddd:::::d a::::a D:::::D D:::::D A:::::A A:::::A O:::::O O:::::O ** P::::PPPPPPPPP aaaaaaa:::::a n:::::nnnn:::::nd::::::d d:::::d aaaaaaa:::::a D:::::D D:::::D A:::::A A:::::A O:::::O O:::::O ** P::::P aa::::::::::::a n::::n n::::nd:::::d d:::::d aa::::::::::::a D:::::D D:::::D A:::::AAAAAAAAA:::::A O:::::O O:::::O ** P::::P a::::aaaa::::::a n::::n n::::nd:::::d d:::::d a::::aaaa::::::a D:::::D D:::::DA:::::::::::::::::::::A O:::::O O:::::O ** P::::P a::::a a:::::a n::::n n::::nd:::::d d:::::d a::::a a:::::a D:::::D D:::::DA:::::AAAAAAAAAAAAA:::::A O::::::O O::::::O ** PP::::::PP a::::a a:::::a n::::n n::::nd::::::ddddd::::::dda::::a a:::::a DDD:::::DDDDD:::::DA:::::A A:::::AO:::::::OOO:::::::O ** P::::::::P a:::::aaaa::::::a n::::n n::::n d:::::::::::::::::da:::::aaaa::::::a D:::::::::::::::DDA:::::A A:::::AOO:::::::::::::OO ** P::::::::P a::::::::::aa:::a n::::n n::::n d:::::::::ddd::::d a::::::::::aa:::aD::::::::::::DDD A:::::A A:::::A OO:::::::::OO ** PPPPPPPPPP aaaaaaaaaa aaaa nnnnnn nnnnnn ddddddddd ddddd aaaaaaaaaa aaaaDDDDDDDDDDDDD AAAAAAA AAAAAAA OOOOOOOOO ** */ // SPDX-License-Identifier: MIT pragma solidity 0.8.6; library Operations { uint256 public constant Configure = 1; uint256 public constant PrintPreminedTickets = 2; uint256 public constant Redeem = 3; uint256 public constant Migrate = 4; uint256 public constant SetHandle = 5; uint256 public constant SetUri = 6; uint256 public constant ClaimHandle = 7; uint256 public constant RenewHandle = 8; uint256 public constant Issue = 9; uint256 public constant Stake = 10; uint256 public constant Unstake = 11; uint256 public constant Transfer = 12; uint256 public constant Lock = 13; uint256 public constant SetPayoutMods = 14; uint256 public constant SetTicketMods = 15; uint256 public constant SetTerminal = 16; uint256 public constant PrintTickets = 17; } /* ** ** dddddddd ** PPPPPPPPPPPPPPPPP d::::::d DDDDDDDDDDDDD AAA OOOOOOOOO ** P::::::::::::::::P d::::::d D::::::::::::DDD A:::A OO:::::::::OO ** P::::::PPPPPP:::::P d::::::d D:::::::::::::::DD A:::::A OO:::::::::::::OO ** PP:::::P P:::::P d:::::d DDD:::::DDDDD:::::D A:::::::A O:::::::OOO:::::::O ** P::::P P:::::Paaaaaaaaaaaaa nnnn nnnnnnnn ddddddddd:::::d aaaaaaaaaaaaa D:::::D D:::::D A:::::::::A O::::::O O::::::O ** P::::P P:::::Pa::::::::::::a n:::nn::::::::nn dd::::::::::::::d a::::::::::::a D:::::D D:::::D A:::::A:::::A O:::::O O:::::O ** P::::PPPPPP:::::P aaaaaaaaa:::::an::::::::::::::nn d::::::::::::::::d aaaaaaaaa:::::a D:::::D D:::::D A:::::A A:::::A O:::::O O:::::O ** P:::::::::::::PP a::::ann:::::::::::::::nd:::::::ddddd:::::d a::::a D:::::D D:::::D A:::::A A:::::A O:::::O O:::::O ** P::::PPPPPPPPP aaaaaaa:::::a n:::::nnnn:::::nd::::::d d:::::d aaaaaaa:::::a D:::::D D:::::D A:::::A A:::::A O:::::O O:::::O ** P::::P aa::::::::::::a n::::n n::::nd:::::d d:::::d aa::::::::::::a D:::::D D:::::D A:::::AAAAAAAAA:::::A O:::::O O:::::O ** P::::P a::::aaaa::::::a n::::n n::::nd:::::d d:::::d a::::aaaa::::::a D:::::D D:::::DA:::::::::::::::::::::A O:::::O O:::::O ** P::::P a::::a a:::::a n::::n n::::nd:::::d d:::::d a::::a a:::::a D:::::D D:::::DA:::::AAAAAAAAAAAAA:::::A O::::::O O::::::O ** PP::::::PP a::::a a:::::a n::::n n::::nd::::::ddddd::::::dda::::a a:::::a DDD:::::DDDDD:::::DA:::::A A:::::AO:::::::OOO:::::::O ** P::::::::P a:::::aaaa::::::a n::::n n::::n d:::::::::::::::::da:::::aaaa::::::a D:::::::::::::::DDA:::::A A:::::AOO:::::::::::::OO ** P::::::::P a::::::::::aa:::a n::::n n::::n d:::::::::ddd::::d a::::::::::aa:::aD::::::::::::DDD A:::::A A:::::A OO:::::::::OO ** PPPPPPPPPP aaaaaaaaaa aaaa nnnnnn nnnnnn ddddddddd ddddd aaaaaaaaaa aaaaDDDDDDDDDDDDD AAAAAAA AAAAAAA OOOOOOOOO ** */ // SPDX-License-Identifier: MIT pragma solidity 0.8.6; interface ITerminalV1_1 { function redeem( address _account, uint256 _projectId, uint256 _amount, uint256 _minReturnedWei, address payable _beneficiary, bool _preferUnstaked ) external returns (uint256 returnAmount); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
treasury redeem $PANDA tokens./
function treasuryRedeem() external nonReentrant onlyOwner { require(treasuryRedeemAmount > 0, "PandaDAO: Invalid amount required."); require(pandaToken.balanceOf(msg.sender) >= treasuryRedeemAmount, "PandaDAO: you do not have enough PandaToken."); terminalv1_1.redeem(msg.sender, PANDADAO_PROJECT_ID, treasuryRedeemAmount, 0, payable(msg.sender), false); treasuryRedeemAmount = 0; emit Treasury_Redeem(msg.sender, treasuryRedeemAmount); }
1,294,181
./full_match/80001/0xd3f069cF82bdd9C0764148Fd07a07144C729003c/sources/SCS.sol
Allows minting(transfer from 0 address), but not transferring while paused() except from owner
function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { if (!(from == address(0)) && !(from == owner())) { require(!paused(), "ERC721Pausable: token transfer while paused"); } }
846,467
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IBeacon.sol"; import "../Utils/Address.sol"; import "../Utils/StorageSlot.sol"; /** * @dev This abstract contract provides setters and getters for the different * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] storage slots. * * _Available since v4.1._ */ abstract contract ERC1967Storage { /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) internal { require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) internal { require( Address.isContract(newBeacon), "ERC1967: new beacon is not a contract" ); require( Address.isContract(IBeacon(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) internal { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } }
Stores a new address in the EIP1967 admin slot./
function _setAdmin(address newAdmin) internal { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin; }
1,821,555
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.8.0; // ==================================================================== // | ______ _______ | // | / _____________ __ __ / ____(_____ ____ _____ ________ | // | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ | // | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ | // | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ | // | | // ==================================================================== // =========================== StakeDAO_AMO_V2 =========================== // ==================================================================== // Frax Finance: https://github.com/FraxFinance // Primary Author(s) // Travis Moore: https://github.com/FortisFortuna // Jason Huan: https://github.com/jasonhuan // Reviewer(s) / Contributor(s) // Sam Kazemian: https://github.com/samkazemian // Dennis: github.com/denett import "../Curve/IStableSwap3Pool.sol"; import "../Curve/IMetaImplementationUSD.sol"; import "../Frax/IFrax.sol"; import "../Frax/IFraxAMOMinter.sol"; import "../Misc_AMOs/stakedao/IStakeDaoVault.sol"; import '../Uniswap/TransferHelper.sol'; import "../ERC20/ERC20.sol"; import "../Math/SafeMath.sol"; import "../Proxy/Initializable.sol"; import "../Staking/Owned.sol"; contract StakeDAO_AMO_V2 is Owned { using SafeMath for uint256; // SafeMath automatically included in Solidity >= 8.0.0 /* ========== STATE VARIABLES ========== */ IMetaImplementationUSD private frax3crv_metapool; IStableSwap3Pool private three_pool; IStakeDaoVault private stakedao_vault; ERC20 private three_pool_erc20; IFrax private FRAX = IFrax(0x853d955aCEf822Db058eb8505911ED77F175b99e); ERC20 private collateral_token; IFraxAMOMinter private amo_minter; address private constant fxs_contract_address = 0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0; address private frax3crv_metapool_address; address public timelock_address; address public custodian_address; // Number of decimals under 18, for collateral token uint256 private missing_decimals; // Precision related uint256 private PRICE_PRECISION; // Min ratio of collat <-> 3crv conversions via add_liquidity / remove_liquidity; 1e6 uint256 public liq_slippage_3crv; // Min ratio of (FRAX + 3CRV) <-> FRAX3CRV-f-2 metapool conversions via add_liquidity / remove_liquidity; 1e6 uint256 public slippage_metapool; // Convergence window uint256 public convergence_window; // 1 cent // Default will use global_collateral_ratio() bool public custom_floor; uint256 public frax_floor; // Discount bool public set_discount; uint256 public discount_rate; /* ========== CONSTRUCTOR ========== */ constructor ( address _owner_address, address _amo_minter_address ) Owned(_owner_address) { owner = _owner_address; collateral_token = ERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); missing_decimals = uint(18).sub(collateral_token.decimals()); frax3crv_metapool_address = 0xd632f22692FaC7611d2AA1C0D552930D43CAEd3B; frax3crv_metapool = IMetaImplementationUSD(frax3crv_metapool_address); three_pool = IStableSwap3Pool(0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7); three_pool_erc20 = ERC20(0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490); amo_minter = IFraxAMOMinter(_amo_minter_address); stakedao_vault = IStakeDaoVault(0x99780beAdd209cc3c7282536883Ef58f4ff4E52F); // Other variable initializations PRICE_PRECISION = 1e6; liq_slippage_3crv = 800000; slippage_metapool = 950000; convergence_window = 1e16; custom_floor = false; set_discount = false; // Get the custodian and timelock addresses from the minter custodian_address = amo_minter.custodian_address(); timelock_address = amo_minter.timelock_address(); } /* ========== MODIFIERS ========== */ modifier onlyByOwnGov() { require(msg.sender == timelock_address || msg.sender == owner, "Not owner or timelock"); _; } modifier onlyByOwnGovCust() { require(msg.sender == timelock_address || msg.sender == owner || msg.sender == custodian_address, "Not owner, tlck, or custd"); _; } modifier onlyByMinter() { require(msg.sender == address(amo_minter), "Not minter"); _; } /* ========== VIEWS ========== */ function showAllocations() public view returns (uint256[11] memory return_arr) { // ------------LP Balance------------ // Free LP uint256 lp_owned = (frax3crv_metapool.balanceOf(address(this))); // Staked in the vault uint256 lp_value_in_vault = FRAX3CRVInVault(); lp_owned = lp_owned.add(lp_value_in_vault); // ------------3pool Withdrawable------------ // Uses iterate() to get metapool withdrawable amounts at FRAX floor price (global_collateral_ratio) uint256 frax3crv_supply = frax3crv_metapool.totalSupply(); uint256 frax_withdrawable; uint256 _3pool_withdrawable; (frax_withdrawable, _3pool_withdrawable, ,) = iterate(); if (frax3crv_supply > 0) { _3pool_withdrawable = _3pool_withdrawable.mul(lp_owned).div(frax3crv_supply); frax_withdrawable = frax_withdrawable.mul(lp_owned).div(frax3crv_supply); } else _3pool_withdrawable = 0; // ------------Frax Balance------------ // Frax sums uint256 frax_in_contract = FRAX.balanceOf(address(this)); // ------------Collateral Balance------------ // Free Collateral uint256 usdc_in_contract = collateral_token.balanceOf(address(this)); // Returns the dollar value withdrawable of USDC if the contract redeemed its 3CRV from the metapool; assume 1 USDC = $1 uint256 usdc_withdrawable = _3pool_withdrawable.mul(three_pool.get_virtual_price()).div(1e18).div(10 ** missing_decimals); // USDC subtotal assuming FRAX drops to the CR and all reserves are arbed uint256 usdc_subtotal = usdc_in_contract.add(usdc_withdrawable); return [ frax_in_contract, // [0] Free FRAX in the contract frax_withdrawable, // [1] FRAX withdrawable from the FRAX3CRV tokens frax_withdrawable.add(frax_in_contract), // [2] FRAX withdrawable + free FRAX in the the contract usdc_in_contract, // [3] Free USDC usdc_withdrawable, // [4] USDC withdrawable from the FRAX3CRV tokens usdc_subtotal, // [5] USDC subtotal assuming FRAX drops to the CR and all reserves are arbed usdc_subtotal.add((frax_in_contract.add(frax_withdrawable)).mul(fraxDiscountRate()).div(1e6 * (10 ** missing_decimals))), // [6] USDC Total lp_owned, // [7] FRAX3CRV free or in the vault frax3crv_supply, // [8] Total supply of FRAX3CRV tokens _3pool_withdrawable, // [9] 3pool withdrawable from the FRAX3CRV tokens lp_value_in_vault // [10] FRAX3CRV in the vault ]; } function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) { // Get the allocations uint256[11] memory allocations = showAllocations(); frax_val_e18 = (allocations[2]).add((allocations[5]).mul((10 ** missing_decimals))); collat_val_e18 = (allocations[6]).mul(10 ** missing_decimals); } // Returns hypothetical reserves of metapool if the FRAX price went to the CR, // assuming no removal of liquidity from the metapool. function iterate() public view returns (uint256, uint256, uint256, uint256) { uint256 frax_balance = FRAX.balanceOf(frax3crv_metapool_address); uint256 crv3_balance = three_pool_erc20.balanceOf(frax3crv_metapool_address); uint256 total_balance = frax_balance.add(crv3_balance); uint256 floor_price_frax = uint(1e18).mul(fraxFloor()).div(1e6); uint256 crv3_received; uint256 dollar_value; // 3crv is usually slightly above $1 due to collecting 3pool swap fees for(uint i = 0; i < 256; i++){ crv3_received = frax3crv_metapool.get_dy(0, 1, 1e18, [frax_balance, crv3_balance]); dollar_value = crv3_received.mul(1e18).div(three_pool.get_virtual_price()); if(dollar_value <= floor_price_frax.add(convergence_window) && dollar_value >= floor_price_frax.sub(convergence_window)){ uint256 factor = uint256(1e6).mul(total_balance).div(frax_balance.add(crv3_balance)); //1e6 precision // Normalize back to initial balances, since this estimation method adds in extra tokens frax_balance = frax_balance.mul(factor).div(1e6); crv3_balance = crv3_balance.mul(factor).div(1e6); return (frax_balance, crv3_balance, i, factor); } else if (dollar_value <= floor_price_frax.add(convergence_window)){ uint256 crv3_to_swap = total_balance.div(2 ** i); frax_balance = frax_balance.sub(frax3crv_metapool.get_dy(1, 0, crv3_to_swap, [frax_balance, crv3_balance])); crv3_balance = crv3_balance.add(crv3_to_swap); } else if (dollar_value >= floor_price_frax.sub(convergence_window)){ uint256 frax_to_swap = total_balance.div(2 ** i); crv3_balance = crv3_balance.sub(frax3crv_metapool.get_dy(0, 1, frax_to_swap, [frax_balance, crv3_balance])); frax_balance = frax_balance.add(frax_to_swap); } } revert("No hypothetical point"); // in 256 rounds } function fraxFloor() public view returns (uint256) { if(custom_floor){ return frax_floor; } else { return FRAX.global_collateral_ratio(); } } function fraxDiscountRate() public view returns (uint256) { if(set_discount){ return discount_rate; } else { return FRAX.global_collateral_ratio(); } } // Amount of FRAX3CRV deposited in the vault contract function sdFRAX3CRV_Balance() public view returns (uint256) { return stakedao_vault.balanceOf(address(this)); } function FRAX3CRVInVault() public view returns (uint256) { uint256 sdBal = sdFRAX3CRV_Balance(); return sdBal.mul(stakedao_vault.getPricePerFullShare()).div(1e18); } // Backwards compatibility function mintedBalance() public view returns (int256) { return amo_minter.frax_mint_balances(address(this)); } /* ========== RESTRICTED FUNCTIONS ========== */ function metapoolDeposit(uint256 _frax_amount, uint256 _collateral_amount) external onlyByOwnGov returns (uint256 metapool_LP_received) { uint256 threeCRV_received = 0; if (_collateral_amount > 0) { // Approve the collateral to be added to 3pool collateral_token.approve(address(three_pool), _collateral_amount); // Convert collateral into 3pool uint256[3] memory three_pool_collaterals; three_pool_collaterals[1] = _collateral_amount; { uint256 min_3pool_out = (_collateral_amount * (10 ** missing_decimals)).mul(liq_slippage_3crv).div(PRICE_PRECISION); three_pool.add_liquidity(three_pool_collaterals, min_3pool_out); } // Approve the 3pool for the metapool threeCRV_received = three_pool_erc20.balanceOf(address(this)); // WEIRD ISSUE: NEED TO DO three_pool_erc20.approve(address(three_pool), 0); first before every time // May be related to https://github.com/vyperlang/vyper/blob/3e1ff1eb327e9017c5758e24db4bdf66bbfae371/examples/tokens/ERC20.vy#L85 three_pool_erc20.approve(frax3crv_metapool_address, 0); three_pool_erc20.approve(frax3crv_metapool_address, threeCRV_received); } // Approve the FRAX for the metapool FRAX.approve(frax3crv_metapool_address, _frax_amount); { // Add the FRAX and the collateral to the metapool uint256 min_lp_out = (_frax_amount.add(threeCRV_received)).mul(slippage_metapool).div(PRICE_PRECISION); metapool_LP_received = frax3crv_metapool.add_liquidity([_frax_amount, threeCRV_received], min_lp_out); } return metapool_LP_received; } function metapoolWithdrawAtCurRatio(uint256 _metapool_lp_in, bool burn_the_frax, uint256 min_frax, uint256 min_3pool) external onlyByOwnGov returns (uint256 frax_received) { // Approve the metapool LP tokens for the metapool contract frax3crv_metapool.approve(address(this), _metapool_lp_in); // Withdraw FRAX and 3pool from the metapool at the current balance uint256 three_pool_received; { uint256[2] memory result_arr = frax3crv_metapool.remove_liquidity(_metapool_lp_in, [min_frax, min_3pool]); frax_received = result_arr[0]; three_pool_received = result_arr[1]; } // Convert the 3pool into the collateral three_pool_erc20.approve(address(three_pool), 0); three_pool_erc20.approve(address(three_pool), three_pool_received); { // Add the FRAX and the collateral to the metapool uint256 min_collat_out = three_pool_received.mul(liq_slippage_3crv).div(PRICE_PRECISION * (10 ** missing_decimals)); three_pool.remove_liquidity_one_coin(three_pool_received, 1, min_collat_out); } // Optionally burn the FRAX if (burn_the_frax){ burnFRAX(frax_received); } } function metapoolWithdrawFrax(uint256 _metapool_lp_in, bool burn_the_frax) external onlyByOwnGov returns (uint256 frax_received) { // Withdraw FRAX from the metapool uint256 min_frax_out = _metapool_lp_in.mul(slippage_metapool).div(PRICE_PRECISION); frax_received = frax3crv_metapool.remove_liquidity_one_coin(_metapool_lp_in, 0, min_frax_out); // Optionally burn the FRAX if (burn_the_frax){ burnFRAX(frax_received); } } function metapoolWithdraw3pool(uint256 _metapool_lp_in) public onlyByOwnGov { // Withdraw 3pool from the metapool uint256 min_3pool_out = _metapool_lp_in.mul(slippage_metapool).div(PRICE_PRECISION); frax3crv_metapool.remove_liquidity_one_coin(_metapool_lp_in, 1, min_3pool_out); } function three_pool_to_collateral(uint256 _3pool_in) public onlyByOwnGov { // Convert the 3pool into the collateral // WEIRD ISSUE: NEED TO DO three_pool_erc20.approve(address(three_pool), 0); first before every time // May be related to https://github.com/vyperlang/vyper/blob/3e1ff1eb327e9017c5758e24db4bdf66bbfae371/examples/tokens/ERC20.vy#L85 three_pool_erc20.approve(address(three_pool), 0); three_pool_erc20.approve(address(three_pool), _3pool_in); uint256 min_collat_out = _3pool_in.mul(liq_slippage_3crv).div(PRICE_PRECISION * (10 ** missing_decimals)); three_pool.remove_liquidity_one_coin(_3pool_in, 1, min_collat_out); } function metapoolWithdrawAndConvert3pool(uint256 _metapool_lp_in) external onlyByOwnGov { metapoolWithdraw3pool(_metapool_lp_in); three_pool_to_collateral(three_pool_erc20.balanceOf(address(this))); } /* ========== Burns and givebacks ========== */ // Give USDC profits back. Goes through the minter function giveCollatBack(uint256 collat_amount) external onlyByOwnGovCust { collateral_token.approve(address(amo_minter), collat_amount); amo_minter.receiveCollatFromAMO(collat_amount); } // Burn unneeded or excess FRAX. Goes through the minter function burnFRAX(uint256 frax_amount) public onlyByOwnGovCust { FRAX.approve(address(amo_minter), frax_amount); amo_minter.burnFraxFromAMO(frax_amount); } /* ========== StakeDAO: Deposit / Withdrawal ========== */ // Deposit Metapool LP tokens into the vault function depositToVault(uint256 _metapool_lp_in) external onlyByOwnGovCust { // Approve the metapool LP tokens for the vault contract frax3crv_metapool.approve(address(stakedao_vault), _metapool_lp_in); // Deposit the metapool LP into the vault contract stakedao_vault.deposit(_metapool_lp_in); } // Withdraw Metapool LP from the vault back to this contract function withdrawFromVault(uint256 _vault_shares) external onlyByOwnGovCust { stakedao_vault.withdraw(_vault_shares); } /* ========== Rewards ========== */ // Rewards is in an increasing getPricePerFullShare() over time here, not a token function withdrawRewards(uint256 frax3crv_amt) external onlyByOwnGovCust { TransferHelper.safeTransfer(frax3crv_metapool_address, msg.sender, frax3crv_amt); } /* ========== RESTRICTED GOVERNANCE FUNCTIONS ========== */ function setAMOMinter(address _amo_minter_address) external onlyByOwnGov { amo_minter = IFraxAMOMinter(_amo_minter_address); // Get the custodian and timelock addresses from the minter custodian_address = amo_minter.custodian_address(); timelock_address = amo_minter.timelock_address(); // Make sure the new addresses are not address(0) require(custodian_address != address(0) && timelock_address != address(0), "Invalid custodian or timelock"); } function setVault(address _stakedao_vault_address) external onlyByOwnGov { stakedao_vault = IStakeDaoVault(_stakedao_vault_address); } function setConvergenceWindow(uint256 _window) external onlyByOwnGov { convergence_window = _window; } // in terms of 1e6 (overriding global_collateral_ratio) function setCustomFloor(bool _state, uint256 _floor_price) external onlyByOwnGov { custom_floor = _state; frax_floor = _floor_price; } // in terms of 1e6 (overriding global_collateral_ratio) function setDiscountRate(bool _state, uint256 _discount_rate) external onlyByOwnGov { set_discount = _state; discount_rate = _discount_rate; } function setSlippages(uint256 _liq_slippage_3crv, uint256 _slippage_metapool) external onlyByOwnGov { liq_slippage_3crv = _liq_slippage_3crv; slippage_metapool = _slippage_metapool; } function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov { TransferHelper.safeTransfer(address(tokenAddress), custodian_address, tokenAmount); } // Generic proxy function execute( address _to, uint256 _value, bytes calldata _data ) external onlyByOwnGov returns (bool, bytes memory) { (bool success, bytes memory result) = _to.call{value:_value}(_data); return (success, result); } }
Withdraw Metapool LP from the vault back to this contract
function withdrawFromVault(uint256 _vault_shares) external onlyByOwnGovCust { stakedao_vault.withdraw(_vault_shares); }
13,126,581
pragma solidity ^0.5.2; import "./CereneumImplementation.sol"; /// @author AshKetchumNakamoto09 /// @title A Trustless Interest-bearing Cryptographic Certificate of Interest on Ethereum contract Cereneum is CereneumImplementation { using SafeMath for uint256; constructor( bytes32 a_hBTCMerkleTreeRoot, bytes32 a_hBCHMerkleTreeRoot, bytes32 a_hBSVMerkleTreeRoot, bytes32 a_hETHMerkleTreeRoot, bytes32 a_hLTCMerkleTreeRoot ) public { //Store the launch time of the contract m_tContractLaunchTime = block.timestamp; m_hMerkleTreeRootsArray[0] = a_hBTCMerkleTreeRoot; m_hMerkleTreeRootsArray[1] = a_hBCHMerkleTreeRoot; m_hMerkleTreeRootsArray[2] = a_hBSVMerkleTreeRoot; m_hMerkleTreeRootsArray[3] = a_hETHMerkleTreeRoot; m_hMerkleTreeRootsArray[4] = a_hLTCMerkleTreeRoot; //These ratios will be updated on snapshot day //All ratios have an invisible 0.0 in front of them m_blockchainRatios[0] = 5128; //BCH m_blockchainRatios[1] = 2263; //BSV m_blockchainRatios[2] = 3106; //ETH m_blockchainRatios[3] = 1311; //LTC //Binance 1 m_exchangeAirdropAddresses[0] = 0x3f5CE5FBFe3E9af3971dD833D26bA9b5C936f0bE; m_exchangeAirdropAmounts[0] = 17400347788910; //Binance 2 m_exchangeAirdropAddresses[1] = 0xD551234Ae421e3BCBA99A0Da6d736074f22192FF; m_exchangeAirdropAmounts[1] = 6758097982665; //Binance 3 m_exchangeAirdropAddresses[2] = 0x564286362092D8e7936f0549571a803B203aAceD; m_exchangeAirdropAmounts[2] = 5557947334680; //Binance 4 m_exchangeAirdropAddresses[3] = 0x0681d8Db095565FE8A346fA0277bFfdE9C0eDBBF; m_exchangeAirdropAmounts[3] = 5953786344335; //Binance 5 has little ether in it //Binance 6 m_exchangeAirdropAddresses[4] = 0x4E9ce36E442e55EcD9025B9a6E0D88485d628A67; m_exchangeAirdropAmounts[4] = 779918770916450; //Bittrex1 m_exchangeAirdropAddresses[5] = 0xFBb1b73C4f0BDa4f67dcA266ce6Ef42f520fBB98; m_exchangeAirdropAmounts[5] = 84975797259280; //Bittrex3 m_exchangeAirdropAddresses[6] = 0x66f820a414680B5bcda5eECA5dea238543F42054; m_exchangeAirdropAmounts[6] = 651875804471280; //KuCoin1 m_exchangeAirdropAddresses[7] = 0x2B5634C42055806a59e9107ED44D43c426E58258; m_exchangeAirdropAmounts[7] = 6609673761160; //KuCoin2 m_exchangeAirdropAddresses[8] = 0x689C56AEf474Df92D44A1B70850f808488F9769C; m_exchangeAirdropAmounts[8] = 4378334643430; //LAToken m_exchangeAirdropAddresses[9] = 0x7891b20C690605F4E370d6944C8A5DBfAc5a451c; m_exchangeAirdropAmounts[9] = 6754951284855; //Huobi Global m_exchangeAirdropAddresses[10] = 0xDc76CD25977E0a5Ae17155770273aD58648900D3; m_exchangeAirdropAmounts[10] = 427305320984440; //CoinBene m_exchangeAirdropAddresses[11] = 0x33683b94334eeBc9BD3EA85DDBDA4a86Fb461405; m_exchangeAirdropAmounts[11] = 2414794474090; //Mint all claimable coins to contract wallet _mint(address(this), m_nMaxRedeemable); } //ERC20 Constants string public constant name = "Cereneum"; string public constant symbol = "CER"; uint public constant decimals = 8; /// @dev A one time callable function to airdrop Ethereum chain CER tokens to some exchange wallets. /// The amounts granted had the standard whale penalties applied and were removed from the UTXO /// set before the Merkle Tree was built so they cannot be claimed a second time. function ExchangeEthereumAirdrops() external { UpdateDailyData(); require(m_bHasAirdroppedExchanges == false); m_bHasAirdroppedExchanges = true; //The following Ethereum exchange addresses are removed from the claimable UTXO set and automatically airdropped //To encourage early exchange support. uint256 nGenesisBonuses = 0; uint256 nPublicReferralBonuses = 0; uint256 nTokensRedeemed = 0; uint256 nBonuses = 0; uint256 nPenalties = 0; for(uint256 i=0; i < 12; ++i) { (nTokensRedeemed, nBonuses, nPenalties) = GetRedeemAmount(m_exchangeAirdropAmounts[i], BlockchainType.Ethereum); //Transfer coins from contracts wallet to claim wallet _transfer(address(this), m_exchangeAirdropAddresses[i], nTokensRedeemed); //Mint speed bonus and 10% referral bonus to claiming address _mint(m_exchangeAirdropAddresses[i], nBonuses.add(nTokensRedeemed.div(10))); //Speed bonus and referral bonus matched for genesis address (20% for referral and 10% for claimer referral = 30%) nGenesisBonuses = nGenesisBonuses.add(nBonuses.add(nTokensRedeemed.mul(1000000000000).div(3333333333333))); //Grant 20% bonus of tokens to referrer nPublicReferralBonuses = nPublicReferralBonuses.add(nTokensRedeemed.div(5)); m_nTotalRedeemed = m_nTotalRedeemed.add(GetRedeemRatio(m_exchangeAirdropAmounts[i], BlockchainType.Ethereum)); m_nRedeemedCount = m_nRedeemedCount.add(1); } //Mint all of the referrer bonuses in a single call _mint(m_publicReferralAddress, nPublicReferralBonuses); //Mint all of the genesis bonuses in a single call _mint(m_genesis, nGenesisBonuses); } /*** TEST FUNCTIONS TO BE REMOVED BEFORE LAUNCHING ***/ /*** TEST FUNCTIONS TO BE REMOVED BEFORE LAUNCHING ***/ /*** TEST FUNCTIONS TO BE REMOVED BEFORE LAUNCHING ***/ /*** TEST FUNCTIONS TO BE REMOVED BEFORE LAUNCHING ***/ function testAdjustContractLaunchTime( uint256 a_days ) external { m_tContractLaunchTime = m_tContractLaunchTime.sub(a_days.mul(1 days)).sub(60); UpdateDailyData(); } function testAdjustStakeTime( uint256 a_nStakeIndex, uint256 a_days, address a_address ) external { m_staked[a_address][a_nStakeIndex].tLockTime = m_staked[a_address][a_nStakeIndex].tLockTime.sub(a_days.mul(1 days)).sub(60); m_staked[a_address][a_nStakeIndex].tLastCompoundedUpdateTime = m_staked[a_address][a_nStakeIndex].tLastCompoundedUpdateTime.sub(a_days.mul(1 days)).sub(60); m_staked[a_address][a_nStakeIndex].tEndStakeCommitTime = m_staked[a_address][a_nStakeIndex].tEndStakeCommitTime.sub(a_days.mul(1 days)).sub(60); UpdateDailyData(); } function testGetSpeedBonus(uint256 a_nAmount, uint256 a_nDays) public pure returns (uint256) { if(a_nDays < m_nClaimPhaseBufferDays) { a_nDays = 0; } else { //We give a two week buffer after contract launch before penalties a_nDays = a_nDays.sub(m_nClaimPhaseBufferDays); } uint256 nMaxDays = 350; a_nAmount = a_nAmount.div(5); return a_nAmount.mul(nMaxDays.sub(a_nDays)).div(nMaxDays); } function testGetLateClaimAdjustedAmount(uint256 a_nAmount, uint256 a_nDays) public pure returns (uint256) { return a_nAmount.sub(GetMonthlyLatePenalty(a_nAmount, a_nDays)); } function testAdjustContractLaunchTimeHours( uint256 a_hours ) external { m_tContractLaunchTime = m_tContractLaunchTime.sub(a_hours.mul(1 hours)); UpdateDailyData(); } function AdjustContractLaunchTime( uint256 a_days ) external { m_tContractLaunchTime = m_tContractLaunchTime.sub(a_days.mul(1 days)).sub(60); } function testAdjustStakeFriendlyTime( uint256 a_nStakeIndex, uint256 a_days, address a_address ) external { m_staked[a_address][a_nStakeIndex].tLockTime = m_staked[a_address][a_nStakeIndex].tLockTime.sub(a_days.mul(1 days)).sub(60); m_staked[a_address][a_nStakeIndex].tLastCompoundedUpdateTime = m_staked[a_address][a_nStakeIndex].tLastCompoundedUpdateTime.sub(a_days.mul(1 days)).sub(60); m_staked[a_address][a_nStakeIndex].tEndStakeCommitTime = m_staked[a_address][a_nStakeIndex].tEndStakeCommitTime.sub(a_days.mul(1 days)).sub(60); m_staked[a_address][a_nStakeIndex].tTimeRemovedFromGlobalPool = m_staked[a_address][a_nStakeIndex].tTimeRemovedFromGlobalPool.sub(a_days.mul(1 days)).sub(60); UpdateDailyData(); } function testAdjustStakeTimeHours( uint256 a_nStakeIndex, uint256 a_hours, address a_address ) external { m_staked[a_address][a_nStakeIndex].tLockTime = m_staked[a_address][a_nStakeIndex].tLockTime.sub(a_hours.mul(1 hours)); m_staked[a_address][a_nStakeIndex].tLastCompoundedUpdateTime = m_staked[a_address][a_nStakeIndex].tLastCompoundedUpdateTime.sub(a_hours.mul(1 hours)); m_staked[a_address][a_nStakeIndex].tEndStakeCommitTime = m_staked[a_address][a_nStakeIndex].tEndStakeCommitTime.sub(a_hours.mul(1 hours)); UpdateDailyData(); } //Skips the UTXO verification on a claim, useful for Unit Testing function testFakeClaim( uint256 a_nAmount, address a_address, BlockchainType a_nWhichChain ) external { UpdateDailyData(); m_nTotalRedeemed = m_nTotalRedeemed.add(GetRedeemRatio(a_nAmount, a_nWhichChain)); (uint256 nRedeemed, uint256 nBonuses, uint256 nPenalties) = GetRedeemAmount(a_nAmount, a_nWhichChain); _transfer(address(this), a_address, nRedeemed); _mint(a_address, nBonuses); _mint(m_genesis, nBonuses); m_nRedeemedCount = m_nRedeemedCount.add(1); return; } function getStakeStructShares( address a_address ) public view returns (uint256) { return m_staked[a_address][0].nSharesStaked; } function getStakeStructAmount( address a_address ) public view returns (uint256) { return m_staked[a_address][0].nAmountStaked; } function getStakeStructEndTime( address a_address ) public view returns (uint256) { return m_staked[a_address][0].tEndStakeCommitTime; } function getStakeStructLockTime( address a_address ) public view returns (uint256) { return m_staked[a_address][0].tLockTime; } function getBlockTime( ) public view returns (uint256) { return block.timestamp; } }
Skips the UTXO verification on a claim, useful for Unit Testing
function testFakeClaim( uint256 a_nAmount, address a_address, BlockchainType a_nWhichChain ) external { UpdateDailyData(); m_nTotalRedeemed = m_nTotalRedeemed.add(GetRedeemRatio(a_nAmount, a_nWhichChain)); (uint256 nRedeemed, uint256 nBonuses, uint256 nPenalties) = GetRedeemAmount(a_nAmount, a_nWhichChain); _transfer(address(this), a_address, nRedeemed); _mint(a_address, nBonuses); _mint(m_genesis, nBonuses); m_nRedeemedCount = m_nRedeemedCount.add(1); return; }
13,117,160
./full_match/43114/0x594D5519c2BCBFd5D21aa9FA6755312caA31CFd4/sources/contracts/liquid-yield/LyLptHolder.sol
unregister a reward token
function removeRewardtoken(address token) external onlyOwnerExec { rewardTokens.remove(token); }
4,513,111
./full_match/1/0xA309c1E54d91b9f45845c4899A7e35999540406B/sources/contracts/staking/StakingPool.sol
Withdraw without caring about rewards. EMERGENCY ONLY. pid The index of the pool. to Receiver of the LP tokens.
function emergencyWithdraw(uint256 pid, address to) external validatePoolByPid(pid) nonReentrant { require(to != address(0), "emergencyWithdraw: receiver is the zero address"); PoolInfo memory pool = poolInfo[pid]; UserInfo storage user = userInfo[pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onAmdxReward(pid, msg.sender, to, 0, 0); } lpToken[pid].safeTransfer(to, amount); pool.totalLp = pool.totalLp.sub(amount); poolInfo[pid] = pool; if(address(lpToken[pid]) == address(AMDX)){ totalAmdxInPools = totalAmdxInPools.sub(amount); } emit EmergencyWithdraw(msg.sender, pid, amount, to); }
17,053,111
// SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../release/extensions/integration-manager/integrations/utils/AdapterBase.sol"; /// @title IMockGenericIntegratee Interface /// @author Enzyme Council <[email protected]> interface IMockGenericIntegratee { function swap( address[] calldata, uint256[] calldata, address[] calldata, uint256[] calldata ) external payable; function swapOnBehalf( address payable, address[] calldata, uint256[] calldata, address[] calldata, uint256[] calldata ) external payable; } /// @title MockGenericAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Provides a generic adapter that: /// 1. Provides swapping functions that use various `SpendAssetsTransferType` values /// 2. Directly parses the _actual_ values to swap from provided call data (e.g., `actualIncomingAssetAmounts`) /// 3. Directly parses values needed by the IntegrationManager from provided call data (e.g., `minIncomingAssetAmounts`) contract MockGenericAdapter is AdapterBase { address public immutable INTEGRATEE; // No need to specify the IntegrationManager constructor(address _integratee) public AdapterBase(address(0)) { INTEGRATEE = _integratee; } function identifier() external pure override returns (string memory) { return "MOCK_GENERIC"; } function parseAssetsForMethod(bytes4 _selector, bytes calldata _callArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory maxSpendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { ( spendAssets_, maxSpendAssetAmounts_, , incomingAssets_, minIncomingAssetAmounts_, ) = __decodeCallArgs(_callArgs); return ( __getSpendAssetsHandleTypeForSelector(_selector), spendAssets_, maxSpendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @dev Assumes SpendAssetsHandleType.Transfer unless otherwise specified function __getSpendAssetsHandleTypeForSelector(bytes4 _selector) private pure returns (IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_) { if (_selector == bytes4(keccak256("removeOnly(address,bytes,bytes)"))) { return IIntegrationManager.SpendAssetsHandleType.Remove; } if (_selector == bytes4(keccak256("swapDirectFromVault(address,bytes,bytes)"))) { return IIntegrationManager.SpendAssetsHandleType.None; } if (_selector == bytes4(keccak256("swapViaApproval(address,bytes,bytes)"))) { return IIntegrationManager.SpendAssetsHandleType.Approve; } return IIntegrationManager.SpendAssetsHandleType.Transfer; } function removeOnly( address, bytes calldata, bytes calldata ) external {} function swapA( address _vaultProxy, bytes calldata _callArgs, bytes calldata _assetTransferArgs ) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) { __decodeCallArgsAndSwap(_callArgs); } function swapB( address _vaultProxy, bytes calldata _callArgs, bytes calldata _assetTransferArgs ) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) { __decodeCallArgsAndSwap(_callArgs); } function swapDirectFromVault( address _vaultProxy, bytes calldata _callArgs, bytes calldata ) external { ( address[] memory spendAssets, , uint256[] memory actualSpendAssetAmounts, address[] memory incomingAssets, , uint256[] memory actualIncomingAssetAmounts ) = __decodeCallArgs(_callArgs); IMockGenericIntegratee(INTEGRATEE).swapOnBehalf( payable(_vaultProxy), spendAssets, actualSpendAssetAmounts, incomingAssets, actualIncomingAssetAmounts ); } function swapViaApproval( address _vaultProxy, bytes calldata _callArgs, bytes calldata _assetTransferArgs ) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) { __decodeCallArgsAndSwap(_callArgs); } function __decodeCallArgs(bytes memory _callArgs) internal pure returns ( address[] memory spendAssets_, uint256[] memory maxSpendAssetAmounts_, uint256[] memory actualSpendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_, uint256[] memory actualIncomingAssetAmounts_ ) { return abi.decode( _callArgs, (address[], uint256[], uint256[], address[], uint256[], uint256[]) ); } function __decodeCallArgsAndSwap(bytes memory _callArgs) internal { ( address[] memory spendAssets, , uint256[] memory actualSpendAssetAmounts, address[] memory incomingAssets, , uint256[] memory actualIncomingAssetAmounts ) = __decodeCallArgs(_callArgs); for (uint256 i; i < spendAssets.length; i++) { ERC20(spendAssets[i]).approve(INTEGRATEE, actualSpendAssetAmounts[i]); } IMockGenericIntegratee(INTEGRATEE).swap( spendAssets, actualSpendAssetAmounts, incomingAssets, actualIncomingAssetAmounts ); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../IIntegrationAdapter.sol"; import "./IntegrationSelectors.sol"; /// @title AdapterBase Contract /// @author Enzyme Council <[email protected]> /// @notice A base contract for integration adapters abstract contract AdapterBase is IIntegrationAdapter, IntegrationSelectors { using SafeERC20 for ERC20; address internal immutable INTEGRATION_MANAGER; /// @dev Provides a standard implementation for transferring assets between /// the fund's VaultProxy and the adapter, by wrapping the adapter action. /// This modifier should be implemented in almost all adapter actions, unless they /// do not move assets or can spend and receive assets directly with the VaultProxy modifier fundAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType, address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); // Take custody of spend assets (if necessary) if (spendAssetsHandleType == IIntegrationManager.SpendAssetsHandleType.Approve) { for (uint256 i = 0; i < spendAssets.length; i++) { ERC20(spendAssets[i]).safeTransferFrom( _vaultProxy, address(this), spendAssetAmounts[i] ); } } // Execute call _; // Transfer remaining assets back to the fund's VaultProxy __transferContractAssetBalancesToFund(_vaultProxy, incomingAssets); __transferContractAssetBalancesToFund(_vaultProxy, spendAssets); } modifier onlyIntegrationManager { require( msg.sender == INTEGRATION_MANAGER, "Only the IntegrationManager can call this function" ); _; } constructor(address _integrationManager) public { INTEGRATION_MANAGER = _integrationManager; } // INTERNAL FUNCTIONS /// @dev Helper for adapters to approve their integratees with the max amount of an asset. /// Since everything is done atomically, and only the balances to-be-used are sent to adapters, /// there is no need to approve exact amounts on every call. function __approveMaxAsNeeded( address _asset, address _target, uint256 _neededAmount ) internal { if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) { ERC20(_asset).safeApprove(_target, type(uint256).max); } } /// @dev Helper to decode the _encodedAssetTransferArgs param passed to adapter call function __decodeEncodedAssetTransferArgs(bytes memory _encodedAssetTransferArgs) internal pure returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_ ) { return abi.decode( _encodedAssetTransferArgs, (IIntegrationManager.SpendAssetsHandleType, address[], uint256[], address[]) ); } /// @dev Helper to transfer full contract balances of assets to the specified VaultProxy function __transferContractAssetBalancesToFund(address _vaultProxy, address[] memory _assets) private { for (uint256 i = 0; i < _assets.length; i++) { uint256 postCallAmount = ERC20(_assets[i]).balanceOf(address(this)); if (postCallAmount > 0) { ERC20(_assets[i]).safeTransfer(_vaultProxy, postCallAmount); } } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `INTEGRATION_MANAGER` variable /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value function getIntegrationManager() external view returns (address integrationManager_) { return INTEGRATION_MANAGER; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../IIntegrationManager.sol"; /// @title Integration Adapter interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all integration adapters interface IIntegrationAdapter { function identifier() external pure returns (string memory identifier_); function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IntegrationSelectors Contract /// @author Enzyme Council <[email protected]> /// @notice Selectors for integration actions /// @dev Selectors are created from their signatures rather than hardcoded for easy verification abstract contract IntegrationSelectors { bytes4 public constant ADD_TRACKED_ASSETS_SELECTOR = bytes4( keccak256("addTrackedAssets(address,bytes,bytes)") ); // Trading bytes4 public constant TAKE_ORDER_SELECTOR = bytes4( keccak256("takeOrder(address,bytes,bytes)") ); // Lending bytes4 public constant LEND_SELECTOR = bytes4(keccak256("lend(address,bytes,bytes)")); bytes4 public constant REDEEM_SELECTOR = bytes4(keccak256("redeem(address,bytes,bytes)")); // Staking bytes4 public constant STAKE_SELECTOR = bytes4(keccak256("stake(address,bytes,bytes)")); bytes4 public constant UNSTAKE_SELECTOR = bytes4(keccak256("unstake(address,bytes,bytes)")); // Combined bytes4 public constant LEND_AND_STAKE_SELECTOR = bytes4( keccak256("lendAndStake(address,bytes,bytes)") ); bytes4 public constant UNSTAKE_AND_REDEEM_SELECTOR = bytes4( keccak256("unstakeAndRedeem(address,bytes,bytes)") ); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IIntegrationManager interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the IntegrationManager interface IIntegrationManager { enum SpendAssetsHandleType {None, Approve, Transfer, Remove} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IZeroExV2.sol"; import "../../../../utils/MathHelpers.sol"; import "../../../../utils/AddressArrayLib.sol"; import "../../../utils/FundDeployerOwnerMixin.sol"; import "../utils/AdapterBase.sol"; /// @title ZeroExV2Adapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter to 0xV2 Exchange Contract contract ZeroExV2Adapter is AdapterBase, FundDeployerOwnerMixin, MathHelpers { using AddressArrayLib for address[]; using SafeMath for uint256; event AllowedMakerAdded(address indexed account); event AllowedMakerRemoved(address indexed account); address private immutable EXCHANGE; mapping(address => bool) private makerToIsAllowed; // Gas could be optimized for the end-user by also storing an immutable ZRX_ASSET_DATA, // for example, but in the narrow OTC use-case of this adapter, taker fees are unlikely. constructor( address _integrationManager, address _exchange, address _fundDeployer, address[] memory _allowedMakers ) public AdapterBase(_integrationManager) FundDeployerOwnerMixin(_fundDeployer) { EXCHANGE = _exchange; if (_allowedMakers.length > 0) { __addAllowedMakers(_allowedMakers); } } // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ZERO_EX_V2"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( bytes memory encodedZeroExOrderArgs, uint256 takerAssetFillAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); IZeroExV2.Order memory order = __constructOrderStruct(encodedZeroExOrderArgs); require( isAllowedMaker(order.makerAddress), "parseAssetsForMethod: Order maker is not allowed" ); require( takerAssetFillAmount <= order.takerAssetAmount, "parseAssetsForMethod: Taker asset fill amount greater than available" ); address makerAsset = __getAssetAddress(order.makerAssetData); address takerAsset = __getAssetAddress(order.takerAssetData); // Format incoming assets incomingAssets_ = new address[](1); incomingAssets_[0] = makerAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = __calcRelativeQuantity( order.takerAssetAmount, order.makerAssetAmount, takerAssetFillAmount ); if (order.takerFee > 0) { address takerFeeAsset = __getAssetAddress(IZeroExV2(EXCHANGE).ZRX_ASSET_DATA()); uint256 takerFeeFillAmount = __calcRelativeQuantity( order.takerAssetAmount, order.takerFee, takerAssetFillAmount ); // fee calculated relative to taker fill amount if (takerFeeAsset == makerAsset) { require( order.takerFee < order.makerAssetAmount, "parseAssetsForMethod: Fee greater than makerAssetAmount" ); spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount; minIncomingAssetAmounts_[0] = minIncomingAssetAmounts_[0].sub(takerFeeFillAmount); } else if (takerFeeAsset == takerAsset) { spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount.add(takerFeeFillAmount); } else { spendAssets_ = new address[](2); spendAssets_[0] = takerAsset; spendAssets_[1] = takerFeeAsset; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = takerAssetFillAmount; spendAssetAmounts_[1] = takerFeeFillAmount; } } else { spendAssets_ = new address[](1); spendAssets_[0] = takerAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = takerAssetFillAmount; } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Take an order on 0x /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( bytes memory encodedZeroExOrderArgs, uint256 takerAssetFillAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); IZeroExV2.Order memory order = __constructOrderStruct(encodedZeroExOrderArgs); // Approve spend assets as needed __approveMaxAsNeeded( __getAssetAddress(order.takerAssetData), __getAssetProxy(order.takerAssetData), takerAssetFillAmount ); // Ignores whether makerAsset or takerAsset overlap with the takerFee asset for simplicity if (order.takerFee > 0) { bytes memory zrxData = IZeroExV2(EXCHANGE).ZRX_ASSET_DATA(); __approveMaxAsNeeded( __getAssetAddress(zrxData), __getAssetProxy(zrxData), __calcRelativeQuantity( order.takerAssetAmount, order.takerFee, takerAssetFillAmount ) // fee calculated relative to taker fill amount ); } // Execute order (, , , bytes memory signature) = __decodeZeroExOrderArgs(encodedZeroExOrderArgs); IZeroExV2(EXCHANGE).fillOrder(order, takerAssetFillAmount, signature); } // PRIVATE FUNCTIONS /// @dev Parses user inputs into a ZeroExV2.Order format function __constructOrderStruct(bytes memory _encodedOrderArgs) private pure returns (IZeroExV2.Order memory order_) { ( address[4] memory orderAddresses, uint256[6] memory orderValues, bytes[2] memory orderData, ) = __decodeZeroExOrderArgs(_encodedOrderArgs); return IZeroExV2.Order({ makerAddress: orderAddresses[0], takerAddress: orderAddresses[1], feeRecipientAddress: orderAddresses[2], senderAddress: orderAddresses[3], makerAssetAmount: orderValues[0], takerAssetAmount: orderValues[1], makerFee: orderValues[2], takerFee: orderValues[3], expirationTimeSeconds: orderValues[4], salt: orderValues[5], makerAssetData: orderData[0], takerAssetData: orderData[1] }); } /// @dev Decode the parameters of a takeOrder call /// @param _encodedCallArgs Encoded parameters passed from client side /// @return encodedZeroExOrderArgs_ Encoded args of the 0x order /// @return takerAssetFillAmount_ Amount of taker asset to fill function __decodeTakeOrderCallArgs(bytes memory _encodedCallArgs) private pure returns (bytes memory encodedZeroExOrderArgs_, uint256 takerAssetFillAmount_) { return abi.decode(_encodedCallArgs, (bytes, uint256)); } /// @dev Decode the parameters of a 0x order /// @param _encodedZeroExOrderArgs Encoded parameters of the 0x order /// @return orderAddresses_ Addresses used in the order /// - [0] 0x Order param: makerAddress /// - [1] 0x Order param: takerAddress /// - [2] 0x Order param: feeRecipientAddress /// - [3] 0x Order param: senderAddress /// @return orderValues_ Values used in the order /// - [0] 0x Order param: makerAssetAmount /// - [1] 0x Order param: takerAssetAmount /// - [2] 0x Order param: makerFee /// - [3] 0x Order param: takerFee /// - [4] 0x Order param: expirationTimeSeconds /// - [5] 0x Order param: salt /// @return orderData_ Bytes data used in the order /// - [0] 0x Order param: makerAssetData /// - [1] 0x Order param: takerAssetData /// @return signature_ Signature of the order function __decodeZeroExOrderArgs(bytes memory _encodedZeroExOrderArgs) private pure returns ( address[4] memory orderAddresses_, uint256[6] memory orderValues_, bytes[2] memory orderData_, bytes memory signature_ ) { return abi.decode(_encodedZeroExOrderArgs, (address[4], uint256[6], bytes[2], bytes)); } /// @dev Parses the asset address from 0x assetData function __getAssetAddress(bytes memory _assetData) private pure returns (address assetAddress_) { assembly { assetAddress_ := mload(add(_assetData, 36)) } } /// @dev Gets the 0x assetProxy address for an ERC20 token function __getAssetProxy(bytes memory _assetData) private view returns (address assetProxy_) { bytes4 assetProxyId; assembly { assetProxyId := and( mload(add(_assetData, 32)), 0xFFFFFFFF00000000000000000000000000000000000000000000000000000000 ) } assetProxy_ = IZeroExV2(EXCHANGE).getAssetProxy(assetProxyId); } ///////////////////////////// // ALLOWED MAKERS REGISTRY // ///////////////////////////// /// @notice Adds accounts to the list of allowed 0x order makers /// @param _accountsToAdd Accounts to add function addAllowedMakers(address[] calldata _accountsToAdd) external onlyFundDeployerOwner { __addAllowedMakers(_accountsToAdd); } /// @notice Removes accounts from the list of allowed 0x order makers /// @param _accountsToRemove Accounts to remove function removeAllowedMakers(address[] calldata _accountsToRemove) external onlyFundDeployerOwner { require(_accountsToRemove.length > 0, "removeAllowedMakers: Empty _accountsToRemove"); for (uint256 i; i < _accountsToRemove.length; i++) { require( isAllowedMaker(_accountsToRemove[i]), "removeAllowedMakers: Account is not an allowed maker" ); makerToIsAllowed[_accountsToRemove[i]] = false; emit AllowedMakerRemoved(_accountsToRemove[i]); } } /// @dev Helper to add accounts to the list of allowed makers function __addAllowedMakers(address[] memory _accountsToAdd) private { require(_accountsToAdd.length > 0, "__addAllowedMakers: Empty _accountsToAdd"); for (uint256 i; i < _accountsToAdd.length; i++) { require(!isAllowedMaker(_accountsToAdd[i]), "__addAllowedMakers: Value already set"); makerToIsAllowed[_accountsToAdd[i]] = true; emit AllowedMakerAdded(_accountsToAdd[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `EXCHANGE` variable value /// @return exchange_ The `EXCHANGE` variable value function getExchange() external view returns (address exchange_) { return EXCHANGE; } /// @notice Checks whether an account is an allowed maker of 0x orders /// @param _who The account to check /// @return isAllowedMaker_ True if _who is an allowed maker function isAllowedMaker(address _who) public view returns (bool isAllowedMaker_) { return makerToIsAllowed[_who]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @dev Minimal interface for our interactions with the ZeroEx Exchange contract interface IZeroExV2 { struct Order { address makerAddress; address takerAddress; address feeRecipientAddress; address senderAddress; uint256 makerAssetAmount; uint256 takerAssetAmount; uint256 makerFee; uint256 takerFee; uint256 expirationTimeSeconds; uint256 salt; bytes makerAssetData; bytes takerAssetData; } struct OrderInfo { uint8 orderStatus; bytes32 orderHash; uint256 orderTakerAssetFilledAmount; } struct FillResults { uint256 makerAssetFilledAmount; uint256 takerAssetFilledAmount; uint256 makerFeePaid; uint256 takerFeePaid; } function ZRX_ASSET_DATA() external view returns (bytes memory); function filled(bytes32) external view returns (uint256); function cancelled(bytes32) external view returns (bool); function getOrderInfo(Order calldata) external view returns (OrderInfo memory); function getAssetProxy(bytes4) external view returns (address); function isValidSignature( bytes32, address, bytes calldata ) external view returns (bool); function preSign( bytes32, address, bytes calldata ) external; function cancelOrder(Order calldata) external; function fillOrder( Order calldata, uint256, bytes calldata ) external returns (FillResults memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; /// @title MathHelpers Contract /// @author Enzyme Council <[email protected]> /// @notice Helper functions for common math operations abstract contract MathHelpers { using SafeMath for uint256; /// @dev Calculates a proportional value relative to a known ratio function __calcRelativeQuantity( uint256 _quantity1, uint256 _quantity2, uint256 _relativeQuantity1 ) internal pure returns (uint256 relativeQuantity2_) { return _relativeQuantity1.mul(_quantity2).div(_quantity1); } /// @dev Calculates a rate normalized to 10^18 precision, /// for given base and quote asset decimals and amounts function __calcNormalizedRate( uint256 _baseAssetDecimals, uint256 _baseAssetAmount, uint256 _quoteAssetDecimals, uint256 _quoteAssetAmount ) internal pure returns (uint256 normalizedRate_) { return _quoteAssetAmount.mul(10**_baseAssetDecimals.add(18)).div( _baseAssetAmount.mul(10**_quoteAssetDecimals) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title AddressArray Library /// @author Enzyme Council <[email protected]> /// @notice A library to extend the address array data type library AddressArrayLib { /// @dev Helper to verify if an array contains a particular value function contains(address[] memory _self, address _target) internal pure returns (bool doesContain_) { for (uint256 i; i < _self.length; i++) { if (_target == _self[i]) { return true; } } return false; } /// @dev Helper to verify if array is a set of unique values. /// Does not assert length > 0. function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) { if (_self.length <= 1) { return true; } uint256 arrayLength = _self.length; for (uint256 i; i < arrayLength; i++) { for (uint256 j = i + 1; j < arrayLength; j++) { if (_self[i] == _self[j]) { return false; } } } return true; } /// @dev Helper to remove items from an array. Removes all matching occurrences of each item. /// Does not assert uniqueness of either array. function removeItems(address[] memory _self, address[] memory _itemsToRemove) internal pure returns (address[] memory nextArray_) { if (_itemsToRemove.length == 0) { return _self; } bool[] memory indexesToRemove = new bool[](_self.length); uint256 remainingItemsCount = _self.length; for (uint256 i; i < _self.length; i++) { if (contains(_itemsToRemove, _self[i])) { indexesToRemove[i] = true; remainingItemsCount--; } } if (remainingItemsCount == _self.length) { nextArray_ = _self; } else if (remainingItemsCount > 0) { nextArray_ = new address[](remainingItemsCount); uint256 nextArrayIndex; for (uint256 i; i < _self.length; i++) { if (!indexesToRemove[i]) { nextArray_[nextArrayIndex] = _self[i]; nextArrayIndex++; } } } return nextArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund-deployer/IFundDeployer.sol"; /// @title FundDeployerOwnerMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract that defers ownership to the owner of FundDeployer abstract contract FundDeployerOwnerMixin { address internal immutable FUND_DEPLOYER; modifier onlyFundDeployerOwner() { require( msg.sender == getOwner(), "onlyFundDeployerOwner: Only the FundDeployer owner can call this function" ); _; } constructor(address _fundDeployer) public { FUND_DEPLOYER = _fundDeployer; } /// @notice Gets the owner of this contract /// @return owner_ The owner /// @dev Ownership is deferred to the owner of the FundDeployer contract function getOwner() public view returns (address owner_) { return IFundDeployer(FUND_DEPLOYER).getOwner(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FUND_DEPLOYER` variable /// @return fundDeployer_ The `FUND_DEPLOYER` variable value function getFundDeployer() external view returns (address fundDeployer_) { return FUND_DEPLOYER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IFundDeployer Interface /// @author Enzyme Council <[email protected]> interface IFundDeployer { enum ReleaseStatus {PreLaunch, Live, Paused} function getOwner() external view returns (address); function getReleaseStatus() external view returns (ReleaseStatus); function isRegisteredVaultCall(address, bytes4) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../../core/fund/vault/IVault.sol"; import "../utils/ExtensionBase.sol"; import "../utils/FundDeployerOwnerMixin.sol"; import "./IPolicy.sol"; import "./IPolicyManager.sol"; /// @title PolicyManager Contract /// @author Enzyme Council <[email protected]> /// @notice Manages policies for funds contract PolicyManager is IPolicyManager, ExtensionBase, FundDeployerOwnerMixin { using EnumerableSet for EnumerableSet.AddressSet; event PolicyDeregistered(address indexed policy, string indexed identifier); event PolicyDisabledForFund(address indexed comptrollerProxy, address indexed policy); event PolicyEnabledForFund( address indexed comptrollerProxy, address indexed policy, bytes settingsData ); event PolicyRegistered( address indexed policy, string indexed identifier, PolicyHook[] implementedHooks ); EnumerableSet.AddressSet private registeredPolicies; mapping(address => mapping(PolicyHook => bool)) private policyToHookToIsImplemented; mapping(address => EnumerableSet.AddressSet) private comptrollerProxyToPolicies; modifier onlyBuySharesHooks(address _policy) { require( !policyImplementsHook(_policy, PolicyHook.PreCallOnIntegration) && !policyImplementsHook(_policy, PolicyHook.PostCallOnIntegration), "onlyBuySharesHooks: Disallowed hook" ); _; } modifier onlyEnabledPolicyForFund(address _comptrollerProxy, address _policy) { require( policyIsEnabledForFund(_comptrollerProxy, _policy), "onlyEnabledPolicyForFund: Policy not enabled" ); _; } constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {} // EXTERNAL FUNCTIONS /// @notice Validates and initializes policies as necessary prior to fund activation /// @param _isMigratedFund True if the fund is migrating to this release /// @dev Caller is expected to be a valid ComptrollerProxy, but there isn't a need to validate. function activateForFund(bool _isMigratedFund) external override { address vaultProxy = __setValidatedVaultProxy(msg.sender); // Policies must assert that they are congruent with migrated vault state if (_isMigratedFund) { address[] memory enabledPolicies = getEnabledPoliciesForFund(msg.sender); for (uint256 i; i < enabledPolicies.length; i++) { __activatePolicyForFund(msg.sender, vaultProxy, enabledPolicies[i]); } } } /// @notice Deactivates policies for a fund by destroying storage function deactivateForFund() external override { delete comptrollerProxyToVaultProxy[msg.sender]; for (uint256 i = comptrollerProxyToPolicies[msg.sender].length(); i > 0; i--) { comptrollerProxyToPolicies[msg.sender].remove( comptrollerProxyToPolicies[msg.sender].at(i - 1) ); } } /// @notice Disables a policy for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The policy address to disable function disablePolicyForFund(address _comptrollerProxy, address _policy) external onlyBuySharesHooks(_policy) onlyEnabledPolicyForFund(_comptrollerProxy, _policy) { __validateIsFundOwner(getVaultProxyForFund(_comptrollerProxy), msg.sender); comptrollerProxyToPolicies[_comptrollerProxy].remove(_policy); emit PolicyDisabledForFund(_comptrollerProxy, _policy); } /// @notice Enables a policy for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The policy address to enable /// @param _settingsData The encoded settings data with which to configure the policy /// @dev Disabling a policy does not delete fund config on the policy, so if a policy is /// disabled and then enabled again, its initial state will be the previous config. It is the /// policy's job to determine how to merge that config with the _settingsData param in this function. function enablePolicyForFund( address _comptrollerProxy, address _policy, bytes calldata _settingsData ) external onlyBuySharesHooks(_policy) { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); __validateIsFundOwner(vaultProxy, msg.sender); __enablePolicyForFund(_comptrollerProxy, _policy, _settingsData); __activatePolicyForFund(_comptrollerProxy, vaultProxy, _policy); } /// @notice Enable policies for use in a fund /// @param _configData Encoded config data /// @dev Only called during init() on ComptrollerProxy deployment function setConfigForFund(bytes calldata _configData) external override { (address[] memory policies, bytes[] memory settingsData) = abi.decode( _configData, (address[], bytes[]) ); // Sanity check require( policies.length == settingsData.length, "setConfigForFund: policies and settingsData array lengths unequal" ); // Enable each policy with settings for (uint256 i; i < policies.length; i++) { __enablePolicyForFund(msg.sender, policies[i], settingsData[i]); } } /// @notice Updates policy settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _policy The Policy contract to update /// @param _settingsData The encoded settings data with which to update the policy config function updatePolicySettingsForFund( address _comptrollerProxy, address _policy, bytes calldata _settingsData ) external onlyBuySharesHooks(_policy) onlyEnabledPolicyForFund(_comptrollerProxy, _policy) { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); __validateIsFundOwner(vaultProxy, msg.sender); IPolicy(_policy).updateFundSettings(_comptrollerProxy, vaultProxy, _settingsData); } /// @notice Validates all policies that apply to a given hook for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _hook The PolicyHook for which to validate policies /// @param _validationData The encoded data with which to validate the filtered policies function validatePolicies( address _comptrollerProxy, PolicyHook _hook, bytes calldata _validationData ) external override { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); address[] memory policies = getEnabledPoliciesForFund(_comptrollerProxy); for (uint256 i; i < policies.length; i++) { if (!policyImplementsHook(policies[i], _hook)) { continue; } require( IPolicy(policies[i]).validateRule( _comptrollerProxy, vaultProxy, _hook, _validationData ), string( abi.encodePacked( "Rule evaluated to false: ", IPolicy(policies[i]).identifier() ) ) ); } } // PRIVATE FUNCTIONS /// @dev Helper to activate a policy for a fund function __activatePolicyForFund( address _comptrollerProxy, address _vaultProxy, address _policy ) private { IPolicy(_policy).activateForFund(_comptrollerProxy, _vaultProxy); } /// @dev Helper to set config and enable policies for a fund function __enablePolicyForFund( address _comptrollerProxy, address _policy, bytes memory _settingsData ) private { require( !policyIsEnabledForFund(_comptrollerProxy, _policy), "__enablePolicyForFund: policy already enabled" ); require(policyIsRegistered(_policy), "__enablePolicyForFund: Policy is not registered"); // Set fund config on policy if (_settingsData.length > 0) { IPolicy(_policy).addFundSettings(_comptrollerProxy, _settingsData); } // Add policy comptrollerProxyToPolicies[_comptrollerProxy].add(_policy); emit PolicyEnabledForFund(_comptrollerProxy, _policy, _settingsData); } /// @dev Helper to validate fund owner. /// Preferred to a modifier because allows gas savings if re-using _vaultProxy. function __validateIsFundOwner(address _vaultProxy, address _who) private view { require( _who == IVault(_vaultProxy).getOwner(), "Only the fund owner can call this function" ); } /////////////////////// // POLICIES REGISTRY // /////////////////////// /// @notice Remove policies from the list of registered policies /// @param _policies Addresses of policies to be registered function deregisterPolicies(address[] calldata _policies) external onlyFundDeployerOwner { require(_policies.length > 0, "deregisterPolicies: _policies cannot be empty"); for (uint256 i; i < _policies.length; i++) { require( policyIsRegistered(_policies[i]), "deregisterPolicies: policy is not registered" ); registeredPolicies.remove(_policies[i]); emit PolicyDeregistered(_policies[i], IPolicy(_policies[i]).identifier()); } } /// @notice Add policies to the list of registered policies /// @param _policies Addresses of policies to be registered function registerPolicies(address[] calldata _policies) external onlyFundDeployerOwner { require(_policies.length > 0, "registerPolicies: _policies cannot be empty"); for (uint256 i; i < _policies.length; i++) { require( !policyIsRegistered(_policies[i]), "registerPolicies: policy already registered" ); registeredPolicies.add(_policies[i]); // Store the hooks that a policy implements for later use. // Fronts the gas for calls to check if a hook is implemented, and guarantees // that the implementsHooks return value does not change post-registration. IPolicy policyContract = IPolicy(_policies[i]); PolicyHook[] memory implementedHooks = policyContract.implementedHooks(); for (uint256 j; j < implementedHooks.length; j++) { policyToHookToIsImplemented[_policies[i]][implementedHooks[j]] = true; } emit PolicyRegistered(_policies[i], policyContract.identifier(), implementedHooks); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Get all registered policies /// @return registeredPoliciesArray_ A list of all registered policy addresses function getRegisteredPolicies() external view returns (address[] memory registeredPoliciesArray_) { registeredPoliciesArray_ = new address[](registeredPolicies.length()); for (uint256 i; i < registeredPoliciesArray_.length; i++) { registeredPoliciesArray_[i] = registeredPolicies.at(i); } } /// @notice Get a list of enabled policies for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return enabledPolicies_ An array of enabled policy addresses function getEnabledPoliciesForFund(address _comptrollerProxy) public view returns (address[] memory enabledPolicies_) { enabledPolicies_ = new address[](comptrollerProxyToPolicies[_comptrollerProxy].length()); for (uint256 i; i < enabledPolicies_.length; i++) { enabledPolicies_[i] = comptrollerProxyToPolicies[_comptrollerProxy].at(i); } } /// @notice Checks if a policy implements a particular hook /// @param _policy The address of the policy to check /// @param _hook The PolicyHook to check /// @return implementsHook_ True if the policy implements the hook function policyImplementsHook(address _policy, PolicyHook _hook) public view returns (bool implementsHook_) { return policyToHookToIsImplemented[_policy][_hook]; } /// @notice Check if a policy is enabled for the fund /// @param _comptrollerProxy The ComptrollerProxy of the fund to check /// @param _policy The address of the policy to check /// @return isEnabled_ True if the policy is enabled for the fund function policyIsEnabledForFund(address _comptrollerProxy, address _policy) public view returns (bool isEnabled_) { return comptrollerProxyToPolicies[_comptrollerProxy].contains(_policy); } /// @notice Check whether a policy is registered /// @param _policy The address of the policy to check /// @return isRegistered_ True if the policy is registered function policyIsRegistered(address _policy) public view returns (bool isRegistered_) { return registeredPolicies.contains(_policy); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../persistent/utils/IMigratableVault.sol"; /// @title IVault Interface /// @author Enzyme Council <[email protected]> interface IVault is IMigratableVault { function addTrackedAsset(address) external; function approveAssetSpender( address, address, uint256 ) external; function burnShares(address, uint256) external; function callOnContract(address, bytes calldata) external; function getAccessor() external view returns (address); function getOwner() external view returns (address); function getTrackedAssets() external view returns (address[] memory); function isTrackedAsset(address) external view returns (bool); function mintShares(address, uint256) external; function removeTrackedAsset(address) external; function transferShares( address, address, uint256 ) external; function withdrawAssetTo( address, address, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund/comptroller/IComptroller.sol"; import "../../core/fund/vault/IVault.sol"; import "../IExtension.sol"; /// @title ExtensionBase Contract /// @author Enzyme Council <[email protected]> /// @notice Base class for an extension abstract contract ExtensionBase is IExtension { mapping(address => address) internal comptrollerProxyToVaultProxy; /// @notice Allows extension to run logic during fund activation /// @dev Unimplemented by default, may be overridden. function activateForFund(bool) external virtual override { return; } /// @notice Allows extension to run logic during fund deactivation (destruct) /// @dev Unimplemented by default, may be overridden. function deactivateForFund() external virtual override { return; } /// @notice Receives calls from ComptrollerLib.callOnExtension() /// and dispatches the appropriate action /// @dev Unimplemented by default, may be overridden. function receiveCallFromComptroller( address, uint256, bytes calldata ) external virtual override { revert("receiveCallFromComptroller: Unimplemented for Extension"); } /// @notice Allows extension to run logic during fund configuration /// @dev Unimplemented by default, may be overridden. function setConfigForFund(bytes calldata) external virtual override { return; } /// @dev Helper to validate a ComptrollerProxy-VaultProxy relation, which we store for both /// gas savings and to guarantee a spoofed ComptrollerProxy does not change getVaultProxy(). /// Will revert without reason if the expected interfaces do not exist. function __setValidatedVaultProxy(address _comptrollerProxy) internal returns (address vaultProxy_) { require( comptrollerProxyToVaultProxy[_comptrollerProxy] == address(0), "__setValidatedVaultProxy: Already set" ); vaultProxy_ = IComptroller(_comptrollerProxy).getVaultProxy(); require(vaultProxy_ != address(0), "__setValidatedVaultProxy: Missing vaultProxy"); require( _comptrollerProxy == IVault(vaultProxy_).getAccessor(), "__setValidatedVaultProxy: Not the VaultProxy accessor" ); comptrollerProxyToVaultProxy[_comptrollerProxy] = vaultProxy_; return vaultProxy_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the verified VaultProxy for a given ComptrollerProxy /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return vaultProxy_ The VaultProxy of the fund function getVaultProxyForFund(address _comptrollerProxy) public view returns (address vaultProxy_) { return comptrollerProxyToVaultProxy[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IPolicyManager.sol"; /// @title Policy Interface /// @author Enzyme Council <[email protected]> interface IPolicy { function activateForFund(address _comptrollerProxy, address _vaultProxy) external; function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external; function identifier() external pure returns (string memory identifier_); function implementedHooks() external view returns (IPolicyManager.PolicyHook[] memory implementedHooks_); function updateFundSettings( address _comptrollerProxy, address _vaultProxy, bytes calldata _encodedSettings ) external; function validateRule( address _comptrollerProxy, address _vaultProxy, IPolicyManager.PolicyHook _hook, bytes calldata _encodedArgs ) external returns (bool isValid_); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title PolicyManager Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the PolicyManager interface IPolicyManager { enum PolicyHook { BuySharesSetup, PreBuyShares, PostBuyShares, BuySharesCompleted, PreCallOnIntegration, PostCallOnIntegration } function validatePolicies( address, PolicyHook, bytes calldata ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigratableVault Interface /// @author Enzyme Council <[email protected]> /// @dev DO NOT EDIT CONTRACT interface IMigratableVault { function canMigrate(address _who) external view returns (bool canMigrate_); function init( address _owner, address _accessor, string calldata _fundName ) external; function setAccessor(address _nextAccessor) external; function setVaultLib(address _nextVaultLib) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IComptroller Interface /// @author Enzyme Council <[email protected]> interface IComptroller { enum VaultAction { None, BurnShares, MintShares, TransferShares, ApproveAssetSpender, WithdrawAssetTo, AddTrackedAsset, RemoveTrackedAsset } function activate(address, bool) external; function calcGav(bool) external returns (uint256, bool); function calcGrossShareValue(bool) external returns (uint256, bool); function callOnExtension( address, uint256, bytes calldata ) external; function configureExtensions(bytes calldata, bytes calldata) external; function destruct() external; function getDenominationAsset() external view returns (address); function getVaultProxy() external view returns (address); function init(address, uint256) external; function permissionedVaultAction(VaultAction, bytes calldata) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IExtension Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all extensions interface IExtension { function activateForFund(bool _isMigration) external; function deactivateForFund() external; function receiveCallFromComptroller( address _comptrollerProxy, uint256 _actionId, bytes calldata _callArgs ) external; function setConfigForFund(bytes calldata _configData) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../IPolicy.sol"; /// @title PolicyBase Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract base contract for all policies abstract contract PolicyBase is IPolicy { address internal immutable POLICY_MANAGER; modifier onlyPolicyManager { require(msg.sender == POLICY_MANAGER, "Only the PolicyManager can make this call"); _; } constructor(address _policyManager) public { POLICY_MANAGER = _policyManager; } /// @notice Validates and initializes a policy as necessary prior to fund activation /// @dev Unimplemented by default, can be overridden by the policy function activateForFund(address, address) external virtual override { return; } /// @notice Updates the policy settings for a fund /// @dev Disallowed by default, can be overridden by the policy function updateFundSettings( address, address, bytes calldata ) external virtual override { revert("updateFundSettings: Updates not allowed for this policy"); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `POLICY_MANAGER` variable value /// @return policyManager_ The `POLICY_MANAGER` variable value function getPolicyManager() external view returns (address policyManager_) { return POLICY_MANAGER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title CallOnIntegrationPostValidatePolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the PostCallOnIntegration policy hook abstract contract PostCallOnIntegrationValidatePolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.PostCallOnIntegration; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedRuleArgs) internal pure returns ( address adapter_, bytes4 selector_, address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_ ) { return abi.decode( _encodedRuleArgs, (address, bytes4, address[], uint256[], address[], uint256[]) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../infrastructure/value-interpreter/ValueInterpreter.sol"; import "./utils/PostCallOnIntegrationValidatePolicyBase.sol"; /// @title MaxConcentration Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that defines a configurable threshold for the concentration of any one asset /// in a fund's holdings contract MaxConcentration is PostCallOnIntegrationValidatePolicyBase { using SafeMath for uint256; event MaxConcentrationSet(address indexed comptrollerProxy, uint256 value); uint256 private constant ONE_HUNDRED_PERCENT = 10**18; // 100% address private immutable VALUE_INTERPRETER; mapping(address => uint256) private comptrollerProxyToMaxConcentration; constructor(address _policyManager, address _valueInterpreter) public PolicyBase(_policyManager) { VALUE_INTERPRETER = _valueInterpreter; } /// @notice Validates and initializes a policy as necessary prior to fund activation /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address /// @dev No need to authenticate access, as there are no state transitions function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyPolicyManager { require( passesRule(_comptrollerProxy, _vaultProxy, VaultLib(_vaultProxy).getTrackedAssets()), "activateForFund: Max concentration exceeded" ); } /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { uint256 maxConcentration = abi.decode(_encodedSettings, (uint256)); require(maxConcentration > 0, "addFundSettings: maxConcentration must be greater than 0"); require( maxConcentration <= ONE_HUNDRED_PERCENT, "addFundSettings: maxConcentration cannot exceed 100%" ); comptrollerProxyToMaxConcentration[_comptrollerProxy] = maxConcentration; emit MaxConcentrationSet(_comptrollerProxy, maxConcentration); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "MAX_CONCENTRATION"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address /// @param _assets The assets with which to check the rule /// @return isValid_ True if the rule passes /// @dev The fund's denomination asset is exempt from the policy limit. function passesRule( address _comptrollerProxy, address _vaultProxy, address[] memory _assets ) public returns (bool isValid_) { uint256 maxConcentration = comptrollerProxyToMaxConcentration[_comptrollerProxy]; ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); address denominationAsset = comptrollerProxyContract.getDenominationAsset(); // Does not require asset finality, otherwise will fail when incoming asset is a Synth (uint256 totalGav, bool gavIsValid) = comptrollerProxyContract.calcGav(false); if (!gavIsValid) { return false; } for (uint256 i = 0; i < _assets.length; i++) { address asset = _assets[i]; if ( !__rulePassesForAsset( _vaultProxy, denominationAsset, maxConcentration, totalGav, asset ) ) { return false; } } return true; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address _vaultProxy, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs); if (incomingAssets.length == 0) { return true; } return passesRule(_comptrollerProxy, _vaultProxy, incomingAssets); } /// @dev Helper to check if the rule holds for a particular asset. /// Avoids the stack-too-deep error. function __rulePassesForAsset( address _vaultProxy, address _denominationAsset, uint256 _maxConcentration, uint256 _totalGav, address _incomingAsset ) private returns (bool isValid_) { if (_incomingAsset == _denominationAsset) return true; uint256 assetBalance = ERC20(_incomingAsset).balanceOf(_vaultProxy); (uint256 assetGav, bool assetGavIsValid) = ValueInterpreter(VALUE_INTERPRETER) .calcLiveAssetValue(_incomingAsset, assetBalance, _denominationAsset); if ( !assetGavIsValid || assetGav.mul(ONE_HUNDRED_PERCENT).div(_totalGav) > _maxConcentration ) { return false; } return true; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the maxConcentration for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return maxConcentration_ The maxConcentration function getMaxConcentrationForFund(address _comptrollerProxy) external view returns (uint256 maxConcentration_) { return comptrollerProxyToMaxConcentration[_comptrollerProxy]; } /// @notice Gets the `VALUE_INTERPRETER` variable /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getValueInterpreter() external view returns (address valueInterpreter_) { return VALUE_INTERPRETER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../extensions/IExtension.sol"; import "../../../extensions/fee-manager/IFeeManager.sol"; import "../../../extensions/policy-manager/IPolicyManager.sol"; import "../../../infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol"; import "../../../infrastructure/value-interpreter/IValueInterpreter.sol"; import "../../../utils/AddressArrayLib.sol"; import "../../../utils/AssetFinalityResolver.sol"; import "../../fund-deployer/IFundDeployer.sol"; import "../vault/IVault.sol"; import "./IComptroller.sol"; /// @title ComptrollerLib Contract /// @author Enzyme Council <[email protected]> /// @notice The core logic library shared by all funds contract ComptrollerLib is IComptroller, AssetFinalityResolver { using AddressArrayLib for address[]; using SafeMath for uint256; using SafeERC20 for ERC20; event MigratedSharesDuePaid(uint256 sharesDue); event OverridePauseSet(bool indexed overridePause); event PreRedeemSharesHookFailed( bytes failureReturnData, address redeemer, uint256 sharesQuantity ); event SharesBought( address indexed caller, address indexed buyer, uint256 investmentAmount, uint256 sharesIssued, uint256 sharesReceived ); event SharesRedeemed( address indexed redeemer, uint256 sharesQuantity, address[] receivedAssets, uint256[] receivedAssetQuantities ); event VaultProxySet(address vaultProxy); // Constants and immutables - shared by all proxies uint256 private constant SHARES_UNIT = 10**18; address private immutable DISPATCHER; address private immutable FUND_DEPLOYER; address private immutable FEE_MANAGER; address private immutable INTEGRATION_MANAGER; address private immutable PRIMITIVE_PRICE_FEED; address private immutable POLICY_MANAGER; address private immutable VALUE_INTERPRETER; // Pseudo-constants (can only be set once) address internal denominationAsset; address internal vaultProxy; // True only for the one non-proxy bool internal isLib; // Storage // Allows a fund owner to override a release-level pause bool internal overridePause; // A reverse-mutex, granting atomic permission for particular contracts to make vault calls bool internal permissionedVaultActionAllowed; // A mutex to protect against reentrancy bool internal reentranceLocked; // A timelock between any "shares actions" (i.e., buy and redeem shares), per-account uint256 internal sharesActionTimelock; mapping(address => uint256) internal acctToLastSharesAction; /////////////// // MODIFIERS // /////////////// modifier allowsPermissionedVaultAction { __assertPermissionedVaultActionNotAllowed(); permissionedVaultActionAllowed = true; _; permissionedVaultActionAllowed = false; } modifier locksReentrance() { __assertNotReentranceLocked(); reentranceLocked = true; _; reentranceLocked = false; } modifier onlyActive() { __assertIsActive(vaultProxy); _; } modifier onlyNotPaused() { __assertNotPaused(); _; } modifier onlyFundDeployer() { __assertIsFundDeployer(msg.sender); _; } modifier onlyOwner() { __assertIsOwner(msg.sender); _; } modifier timelockedSharesAction(address _account) { __assertSharesActionNotTimelocked(_account); _; acctToLastSharesAction[_account] = block.timestamp; } // ASSERTION HELPERS // Modifiers are inefficient in terms of contract size, // so we use helper functions to prevent repetitive inlining of expensive string values. /// @dev Since vaultProxy is set during activate(), /// we can check that var rather than storing additional state function __assertIsActive(address _vaultProxy) private pure { require(_vaultProxy != address(0), "Fund not active"); } function __assertIsFundDeployer(address _who) private view { require(_who == FUND_DEPLOYER, "Only FundDeployer callable"); } function __assertIsOwner(address _who) private view { require(_who == IVault(vaultProxy).getOwner(), "Only fund owner callable"); } function __assertLowLevelCall(bool _success, bytes memory _returnData) private pure { require(_success, string(_returnData)); } function __assertNotPaused() private view { require(!__fundIsPaused(), "Fund is paused"); } function __assertNotReentranceLocked() private view { require(!reentranceLocked, "Re-entrance"); } function __assertPermissionedVaultActionNotAllowed() private view { require(!permissionedVaultActionAllowed, "Vault action re-entrance"); } function __assertSharesActionNotTimelocked(address _account) private view { require( block.timestamp.sub(acctToLastSharesAction[_account]) >= sharesActionTimelock, "Shares action timelocked" ); } constructor( address _dispatcher, address _fundDeployer, address _valueInterpreter, address _feeManager, address _integrationManager, address _policyManager, address _primitivePriceFeed, address _synthetixPriceFeed, address _synthetixAddressResolver ) public AssetFinalityResolver(_synthetixPriceFeed, _synthetixAddressResolver) { DISPATCHER = _dispatcher; FEE_MANAGER = _feeManager; FUND_DEPLOYER = _fundDeployer; INTEGRATION_MANAGER = _integrationManager; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; POLICY_MANAGER = _policyManager; VALUE_INTERPRETER = _valueInterpreter; isLib = true; } ///////////// // GENERAL // ///////////// /// @notice Calls a specified action on an Extension /// @param _extension The Extension contract to call (e.g., FeeManager) /// @param _actionId An ID representing the action to take on the extension (see extension) /// @param _callArgs The encoded data for the call /// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy /// (for access control). Uses a mutex of sorts that allows "permissioned vault actions" /// during calls originating from this function. function callOnExtension( address _extension, uint256 _actionId, bytes calldata _callArgs ) external override onlyNotPaused onlyActive locksReentrance allowsPermissionedVaultAction { require( _extension == FEE_MANAGER || _extension == INTEGRATION_MANAGER, "callOnExtension: _extension invalid" ); IExtension(_extension).receiveCallFromComptroller(msg.sender, _actionId, _callArgs); } /// @notice Sets or unsets an override on a release-wide pause /// @param _nextOverridePause True if the pause should be overrode function setOverridePause(bool _nextOverridePause) external onlyOwner { require(_nextOverridePause != overridePause, "setOverridePause: Value already set"); overridePause = _nextOverridePause; emit OverridePauseSet(_nextOverridePause); } /// @notice Makes an arbitrary call with the VaultProxy contract as the sender /// @param _contract The contract to call /// @param _selector The selector to call /// @param _encodedArgs The encoded arguments for the call function vaultCallOnContract( address _contract, bytes4 _selector, bytes calldata _encodedArgs ) external onlyNotPaused onlyActive onlyOwner { require( IFundDeployer(FUND_DEPLOYER).isRegisteredVaultCall(_contract, _selector), "vaultCallOnContract: Unregistered" ); IVault(vaultProxy).callOnContract(_contract, abi.encodePacked(_selector, _encodedArgs)); } /// @dev Helper to check whether the release is paused, and that there is no local override function __fundIsPaused() private view returns (bool) { return IFundDeployer(FUND_DEPLOYER).getReleaseStatus() == IFundDeployer.ReleaseStatus.Paused && !overridePause; } //////////////////////////////// // PERMISSIONED VAULT ACTIONS // //////////////////////////////// /// @notice Makes a permissioned, state-changing call on the VaultProxy contract /// @param _action The enum representing the VaultAction to perform on the VaultProxy /// @param _actionData The call data for the action to perform function permissionedVaultAction(VaultAction _action, bytes calldata _actionData) external override onlyNotPaused onlyActive { __assertPermissionedVaultAction(msg.sender, _action); if (_action == VaultAction.AddTrackedAsset) { __vaultActionAddTrackedAsset(_actionData); } else if (_action == VaultAction.ApproveAssetSpender) { __vaultActionApproveAssetSpender(_actionData); } else if (_action == VaultAction.BurnShares) { __vaultActionBurnShares(_actionData); } else if (_action == VaultAction.MintShares) { __vaultActionMintShares(_actionData); } else if (_action == VaultAction.RemoveTrackedAsset) { __vaultActionRemoveTrackedAsset(_actionData); } else if (_action == VaultAction.TransferShares) { __vaultActionTransferShares(_actionData); } else if (_action == VaultAction.WithdrawAssetTo) { __vaultActionWithdrawAssetTo(_actionData); } } /// @dev Helper to assert that a caller is allowed to perform a particular VaultAction function __assertPermissionedVaultAction(address _caller, VaultAction _action) private view { require( permissionedVaultActionAllowed, "__assertPermissionedVaultAction: No action allowed" ); if (_caller == INTEGRATION_MANAGER) { require( _action == VaultAction.ApproveAssetSpender || _action == VaultAction.AddTrackedAsset || _action == VaultAction.RemoveTrackedAsset || _action == VaultAction.WithdrawAssetTo, "__assertPermissionedVaultAction: Not valid for IntegrationManager" ); } else if (_caller == FEE_MANAGER) { require( _action == VaultAction.BurnShares || _action == VaultAction.MintShares || _action == VaultAction.TransferShares, "__assertPermissionedVaultAction: Not valid for FeeManager" ); } else { revert("__assertPermissionedVaultAction: Not a valid actor"); } } /// @dev Helper to add a tracked asset to the fund function __vaultActionAddTrackedAsset(bytes memory _actionData) private { address asset = abi.decode(_actionData, (address)); IVault(vaultProxy).addTrackedAsset(asset); } /// @dev Helper to grant a spender an allowance for a fund's asset function __vaultActionApproveAssetSpender(bytes memory _actionData) private { (address asset, address target, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); IVault(vaultProxy).approveAssetSpender(asset, target, amount); } /// @dev Helper to burn fund shares for a particular account function __vaultActionBurnShares(bytes memory _actionData) private { (address target, uint256 amount) = abi.decode(_actionData, (address, uint256)); IVault(vaultProxy).burnShares(target, amount); } /// @dev Helper to mint fund shares to a particular account function __vaultActionMintShares(bytes memory _actionData) private { (address target, uint256 amount) = abi.decode(_actionData, (address, uint256)); IVault(vaultProxy).mintShares(target, amount); } /// @dev Helper to remove a tracked asset from the fund function __vaultActionRemoveTrackedAsset(bytes memory _actionData) private { address asset = abi.decode(_actionData, (address)); // Allowing this to fail silently makes it cheaper and simpler // for Extensions to not query for the denomination asset if (asset != denominationAsset) { IVault(vaultProxy).removeTrackedAsset(asset); } } /// @dev Helper to transfer fund shares from one account to another function __vaultActionTransferShares(bytes memory _actionData) private { (address from, address to, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); IVault(vaultProxy).transferShares(from, to, amount); } /// @dev Helper to withdraw an asset from the VaultProxy to a given account function __vaultActionWithdrawAssetTo(bytes memory _actionData) private { (address asset, address target, uint256 amount) = abi.decode( _actionData, (address, address, uint256) ); IVault(vaultProxy).withdrawAssetTo(asset, target, amount); } /////////////// // LIFECYCLE // /////////////// /// @notice Initializes a fund with its core config /// @param _denominationAsset The asset in which the fund's value should be denominated /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @dev Pseudo-constructor per proxy. /// No need to assert access because this is called atomically on deployment, /// and once it's called, it cannot be called again. function init(address _denominationAsset, uint256 _sharesActionTimelock) external override { require(denominationAsset == address(0), "init: Already initialized"); require( IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_denominationAsset), "init: Bad denomination asset" ); denominationAsset = _denominationAsset; sharesActionTimelock = _sharesActionTimelock; } /// @notice Configure the extensions of a fund /// @param _feeManagerConfigData Encoded config for fees to enable /// @param _policyManagerConfigData Encoded config for policies to enable /// @dev No need to assert anything beyond FundDeployer access. /// Called atomically with init(), but after ComptrollerLib has been deployed, /// giving access to its state and interface function configureExtensions( bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external override onlyFundDeployer { if (_feeManagerConfigData.length > 0) { IExtension(FEE_MANAGER).setConfigForFund(_feeManagerConfigData); } if (_policyManagerConfigData.length > 0) { IExtension(POLICY_MANAGER).setConfigForFund(_policyManagerConfigData); } } /// @notice Activates the fund by attaching a VaultProxy and activating all Extensions /// @param _vaultProxy The VaultProxy to attach to the fund /// @param _isMigration True if a migrated fund is being activated /// @dev No need to assert anything beyond FundDeployer access. function activate(address _vaultProxy, bool _isMigration) external override onlyFundDeployer { vaultProxy = _vaultProxy; emit VaultProxySet(_vaultProxy); if (_isMigration) { // Distribute any shares in the VaultProxy to the fund owner. // This is a mechanism to ensure that even in the edge case of a fund being unable // to payout fee shares owed during migration, these shares are not lost. uint256 sharesDue = ERC20(_vaultProxy).balanceOf(_vaultProxy); if (sharesDue > 0) { IVault(_vaultProxy).transferShares( _vaultProxy, IVault(_vaultProxy).getOwner(), sharesDue ); emit MigratedSharesDuePaid(sharesDue); } } // Note: a future release could consider forcing the adding of a tracked asset here, // just in case a fund is migrating from an old configuration where they are not able // to remove an asset to get under the tracked assets limit IVault(_vaultProxy).addTrackedAsset(denominationAsset); // Activate extensions IExtension(FEE_MANAGER).activateForFund(_isMigration); IExtension(INTEGRATION_MANAGER).activateForFund(_isMigration); IExtension(POLICY_MANAGER).activateForFund(_isMigration); } /// @notice Remove the config for a fund /// @dev No need to assert anything beyond FundDeployer access. /// Calling onlyNotPaused here rather than in the FundDeployer allows /// the owner to potentially override the pause and rescue unpaid fees. function destruct() external override onlyFundDeployer onlyNotPaused allowsPermissionedVaultAction { // Failsafe to protect the libs against selfdestruct require(!isLib, "destruct: Only delegate callable"); // Deactivate the extensions IExtension(FEE_MANAGER).deactivateForFund(); IExtension(INTEGRATION_MANAGER).deactivateForFund(); IExtension(POLICY_MANAGER).deactivateForFund(); // Delete storage of ComptrollerProxy // There should never be ETH in the ComptrollerLib, so no need to waste gas // to get the fund owner selfdestruct(address(0)); } //////////////// // ACCOUNTING // //////////////// /// @notice Calculates the gross asset value (GAV) of the fund /// @param _requireFinality True if all assets must have exact final balances settled /// @return gav_ The fund GAV /// @return isValid_ True if the conversion rates used to derive the GAV are all valid function calcGav(bool _requireFinality) public override returns (uint256 gav_, bool isValid_) { address vaultProxyAddress = vaultProxy; address[] memory assets = IVault(vaultProxyAddress).getTrackedAssets(); if (assets.length == 0) { return (0, true); } uint256[] memory balances = new uint256[](assets.length); for (uint256 i; i < assets.length; i++) { balances[i] = __finalizeIfSynthAndGetAssetBalance( vaultProxyAddress, assets[i], _requireFinality ); } (gav_, isValid_) = IValueInterpreter(VALUE_INTERPRETER).calcCanonicalAssetsTotalValue( assets, balances, denominationAsset ); return (gav_, isValid_); } /// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset /// @param _requireFinality True if all assets must have exact final balances settled /// @return grossShareValue_ The amount of the denomination asset per share /// @return isValid_ True if the conversion rates to derive the value are all valid /// @dev Does not account for any fees outstanding. function calcGrossShareValue(bool _requireFinality) external override returns (uint256 grossShareValue_, bool isValid_) { uint256 gav; (gav, isValid_) = calcGav(_requireFinality); grossShareValue_ = __calcGrossShareValue( gav, ERC20(vaultProxy).totalSupply(), 10**uint256(ERC20(denominationAsset).decimals()) ); return (grossShareValue_, isValid_); } /// @dev Helper for calculating the gross share value function __calcGrossShareValue( uint256 _gav, uint256 _sharesSupply, uint256 _denominationAssetUnit ) private pure returns (uint256 grossShareValue_) { if (_sharesSupply == 0) { return _denominationAssetUnit; } return _gav.mul(SHARES_UNIT).div(_sharesSupply); } /////////////////// // PARTICIPATION // /////////////////// // BUY SHARES /// @notice Buys shares in the fund for multiple sets of criteria /// @param _buyers The accounts for which to buy shares /// @param _investmentAmounts The amounts of the fund's denomination asset /// with which to buy shares for the corresponding _buyers /// @param _minSharesQuantities The minimum quantities of shares to buy /// with the corresponding _investmentAmounts /// @return sharesReceivedAmounts_ The actual amounts of shares received /// by the corresponding _buyers /// @dev Param arrays have indexes corresponding to individual __buyShares() orders. function buyShares( address[] calldata _buyers, uint256[] calldata _investmentAmounts, uint256[] calldata _minSharesQuantities ) external onlyNotPaused locksReentrance allowsPermissionedVaultAction returns (uint256[] memory sharesReceivedAmounts_) { require(_buyers.length > 0, "buyShares: Empty _buyers"); require( _buyers.length == _investmentAmounts.length && _buyers.length == _minSharesQuantities.length, "buyShares: Unequal arrays" ); address vaultProxyCopy = vaultProxy; __assertIsActive(vaultProxyCopy); require( !IDispatcher(DISPATCHER).hasMigrationRequest(vaultProxyCopy), "buyShares: Pending migration" ); (uint256 gav, bool gavIsValid) = calcGav(true); require(gavIsValid, "buyShares: Invalid GAV"); __buySharesSetupHook(msg.sender, _investmentAmounts, gav); address denominationAssetCopy = denominationAsset; uint256 sharePrice = __calcGrossShareValue( gav, ERC20(vaultProxyCopy).totalSupply(), 10**uint256(ERC20(denominationAssetCopy).decimals()) ); sharesReceivedAmounts_ = new uint256[](_buyers.length); for (uint256 i; i < _buyers.length; i++) { sharesReceivedAmounts_[i] = __buyShares( _buyers[i], _investmentAmounts[i], _minSharesQuantities[i], vaultProxyCopy, sharePrice, gav, denominationAssetCopy ); gav = gav.add(_investmentAmounts[i]); } __buySharesCompletedHook(msg.sender, sharesReceivedAmounts_, gav); return sharesReceivedAmounts_; } /// @dev Helper to buy shares function __buyShares( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity, address _vaultProxy, uint256 _sharePrice, uint256 _preBuySharesGav, address _denominationAsset ) private timelockedSharesAction(_buyer) returns (uint256 sharesReceived_) { require(_investmentAmount > 0, "__buyShares: Empty _investmentAmount"); // Gives Extensions a chance to run logic prior to the minting of bought shares __preBuySharesHook(_buyer, _investmentAmount, _minSharesQuantity, _preBuySharesGav); // Calculate the amount of shares to issue with the investment amount uint256 sharesIssued = _investmentAmount.mul(SHARES_UNIT).div(_sharePrice); // Mint shares to the buyer uint256 prevBuyerShares = ERC20(_vaultProxy).balanceOf(_buyer); IVault(_vaultProxy).mintShares(_buyer, sharesIssued); // Transfer the investment asset to the fund. // Does not follow the checks-effects-interactions pattern, but it is preferred // to have the final state of the VaultProxy prior to running __postBuySharesHook(). ERC20(_denominationAsset).safeTransferFrom(msg.sender, _vaultProxy, _investmentAmount); // Gives Extensions a chance to run logic after shares are issued __postBuySharesHook(_buyer, _investmentAmount, sharesIssued, _preBuySharesGav); // The number of actual shares received may differ from shares issued due to // how the PostBuyShares hooks are invoked by Extensions (i.e., fees) sharesReceived_ = ERC20(_vaultProxy).balanceOf(_buyer).sub(prevBuyerShares); require( sharesReceived_ >= _minSharesQuantity, "__buyShares: Shares received < _minSharesQuantity" ); emit SharesBought(msg.sender, _buyer, _investmentAmount, sharesIssued, sharesReceived_); return sharesReceived_; } /// @dev Helper for Extension actions after all __buyShares() calls are made function __buySharesCompletedHook( address _caller, uint256[] memory _sharesReceivedAmounts, uint256 _gav ) private { IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.BuySharesCompleted, abi.encode(_caller, _sharesReceivedAmounts, _gav) ); IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.BuySharesCompleted, abi.encode(_caller, _sharesReceivedAmounts), _gav ); } /// @dev Helper for Extension actions before any __buyShares() calls are made function __buySharesSetupHook( address _caller, uint256[] memory _investmentAmounts, uint256 _gav ) private { IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.BuySharesSetup, abi.encode(_caller, _investmentAmounts, _gav) ); IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.BuySharesSetup, abi.encode(_caller, _investmentAmounts), _gav ); } /// @dev Helper for Extension actions immediately prior to issuing shares. /// This could be cleaned up so both Extensions take the same encoded args and handle GAV /// in the same way, but there is not the obvious need for gas savings of recycling /// the GAV value for the current policies as there is for the fees. function __preBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity, uint256 _gav ) private { IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.PreBuyShares, abi.encode(_buyer, _investmentAmount, _minSharesQuantity), _gav ); IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.PreBuyShares, abi.encode(_buyer, _investmentAmount, _minSharesQuantity, _gav) ); } /// @dev Helper for Extension actions immediately after issuing shares. /// Same comment applies from __preBuySharesHook() above. function __postBuySharesHook( address _buyer, uint256 _investmentAmount, uint256 _sharesIssued, uint256 _preBuySharesGav ) private { uint256 gav = _preBuySharesGav.add(_investmentAmount); IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued), gav ); IPolicyManager(POLICY_MANAGER).validatePolicies( address(this), IPolicyManager.PolicyHook.PostBuyShares, abi.encode(_buyer, _investmentAmount, _sharesIssued, gav) ); } // REDEEM SHARES /// @notice Redeem all of the sender's shares for a proportionate slice of the fund's assets /// @return payoutAssets_ The assets paid out to the redeemer /// @return payoutAmounts_ The amount of each asset paid out to the redeemer /// @dev See __redeemShares() for further detail function redeemShares() external returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { return __redeemShares( msg.sender, ERC20(vaultProxy).balanceOf(msg.sender), new address[](0), new address[](0) ); } /// @notice Redeem a specified quantity of the sender's shares for a proportionate slice of /// the fund's assets, optionally specifying additional assets and assets to skip. /// @param _sharesQuantity The quantity of shares to redeem /// @param _additionalAssets Additional (non-tracked) assets to claim /// @param _assetsToSkip Tracked assets to forfeit /// @return payoutAssets_ The assets paid out to the redeemer /// @return payoutAmounts_ The amount of each asset paid out to the redeemer /// @dev Any claim to passed _assetsToSkip will be forfeited entirely. This should generally /// only be exercised if a bad asset is causing redemption to fail. function redeemSharesDetailed( uint256 _sharesQuantity, address[] calldata _additionalAssets, address[] calldata _assetsToSkip ) external returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { return __redeemShares(msg.sender, _sharesQuantity, _additionalAssets, _assetsToSkip); } /// @dev Helper to parse an array of payout assets during redemption, taking into account /// additional assets and assets to skip. _assetsToSkip ignores _additionalAssets. /// All input arrays are assumed to be unique. function __parseRedemptionPayoutAssets( address[] memory _trackedAssets, address[] memory _additionalAssets, address[] memory _assetsToSkip ) private pure returns (address[] memory payoutAssets_) { address[] memory trackedAssetsToPayout = _trackedAssets.removeItems(_assetsToSkip); if (_additionalAssets.length == 0) { return trackedAssetsToPayout; } // Add additional assets. Duplicates of trackedAssets are ignored. bool[] memory indexesToAdd = new bool[](_additionalAssets.length); uint256 additionalItemsCount; for (uint256 i; i < _additionalAssets.length; i++) { if (!trackedAssetsToPayout.contains(_additionalAssets[i])) { indexesToAdd[i] = true; additionalItemsCount++; } } if (additionalItemsCount == 0) { return trackedAssetsToPayout; } payoutAssets_ = new address[](trackedAssetsToPayout.length.add(additionalItemsCount)); for (uint256 i; i < trackedAssetsToPayout.length; i++) { payoutAssets_[i] = trackedAssetsToPayout[i]; } uint256 payoutAssetsIndex = trackedAssetsToPayout.length; for (uint256 i; i < _additionalAssets.length; i++) { if (indexesToAdd[i]) { payoutAssets_[payoutAssetsIndex] = _additionalAssets[i]; payoutAssetsIndex++; } } return payoutAssets_; } /// @dev Helper for system actions immediately prior to redeeming shares. /// Policy validation is not currently allowed on redemption, to ensure continuous redeemability. function __preRedeemSharesHook(address _redeemer, uint256 _sharesQuantity) private allowsPermissionedVaultAction { try IFeeManager(FEE_MANAGER).invokeHook( IFeeManager.FeeHook.PreRedeemShares, abi.encode(_redeemer, _sharesQuantity), 0 ) {} catch (bytes memory reason) { emit PreRedeemSharesHookFailed(reason, _redeemer, _sharesQuantity); } } /// @dev Helper to redeem shares. /// This function should never fail without a way to bypass the failure, which is assured /// through two mechanisms: /// 1. The FeeManager is called with the try/catch pattern to assure that calls to it /// can never block redemption. /// 2. If a token fails upon transfer(), that token can be skipped (and its balance forfeited) /// by explicitly specifying _assetsToSkip. /// Because of these assurances, shares should always be redeemable, with the exception /// of the timelock period on shares actions that must be respected. function __redeemShares( address _redeemer, uint256 _sharesQuantity, address[] memory _additionalAssets, address[] memory _assetsToSkip ) private locksReentrance returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) { require(_sharesQuantity > 0, "__redeemShares: _sharesQuantity must be >0"); require( _additionalAssets.isUniqueSet(), "__redeemShares: _additionalAssets contains duplicates" ); require(_assetsToSkip.isUniqueSet(), "__redeemShares: _assetsToSkip contains duplicates"); IVault vaultProxyContract = IVault(vaultProxy); // Only apply the sharesActionTimelock when a migration is not pending if (!IDispatcher(DISPATCHER).hasMigrationRequest(address(vaultProxyContract))) { __assertSharesActionNotTimelocked(_redeemer); acctToLastSharesAction[_redeemer] = block.timestamp; } // When a fund is paused, settling fees will be skipped if (!__fundIsPaused()) { // Note that if a fee with `SettlementType.Direct` is charged here (i.e., not `Mint`), // then those fee shares will be transferred from the user's balance rather // than reallocated from the sharesQuantity being redeemed. __preRedeemSharesHook(_redeemer, _sharesQuantity); } // Check the shares quantity against the user's balance after settling fees ERC20 sharesContract = ERC20(address(vaultProxyContract)); require( _sharesQuantity <= sharesContract.balanceOf(_redeemer), "__redeemShares: Insufficient shares" ); // Parse the payout assets given optional params to add or skip assets. // Note that there is no validation that the _additionalAssets are known assets to // the protocol. This means that the redeemer could specify a malicious asset, // but since all state-changing, user-callable functions on this contract share the // non-reentrant modifier, there is nowhere to perform a reentrancy attack. payoutAssets_ = __parseRedemptionPayoutAssets( vaultProxyContract.getTrackedAssets(), _additionalAssets, _assetsToSkip ); require(payoutAssets_.length > 0, "__redeemShares: No payout assets"); // Destroy the shares. // Must get the shares supply before doing so. uint256 sharesSupply = sharesContract.totalSupply(); vaultProxyContract.burnShares(_redeemer, _sharesQuantity); // Calculate and transfer payout asset amounts due to redeemer payoutAmounts_ = new uint256[](payoutAssets_.length); address denominationAssetCopy = denominationAsset; for (uint256 i; i < payoutAssets_.length; i++) { uint256 assetBalance = __finalizeIfSynthAndGetAssetBalance( address(vaultProxyContract), payoutAssets_[i], true ); // If all remaining shares are being redeemed, the logic changes slightly if (_sharesQuantity == sharesSupply) { payoutAmounts_[i] = assetBalance; // Remove every tracked asset, except the denomination asset if (payoutAssets_[i] != denominationAssetCopy) { vaultProxyContract.removeTrackedAsset(payoutAssets_[i]); } } else { payoutAmounts_[i] = assetBalance.mul(_sharesQuantity).div(sharesSupply); } // Transfer payout asset to redeemer if (payoutAmounts_[i] > 0) { vaultProxyContract.withdrawAssetTo(payoutAssets_[i], _redeemer, payoutAmounts_[i]); } } emit SharesRedeemed(_redeemer, _sharesQuantity, payoutAssets_, payoutAmounts_); return (payoutAssets_, payoutAmounts_); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `denominationAsset` variable /// @return denominationAsset_ The `denominationAsset` variable value function getDenominationAsset() external view override returns (address denominationAsset_) { return denominationAsset; } /// @notice Gets the routes for the various contracts used by all funds /// @return dispatcher_ The `DISPATCHER` variable value /// @return feeManager_ The `FEE_MANAGER` variable value /// @return fundDeployer_ The `FUND_DEPLOYER` variable value /// @return integrationManager_ The `INTEGRATION_MANAGER` variable value /// @return policyManager_ The `POLICY_MANAGER` variable value /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getLibRoutes() external view returns ( address dispatcher_, address feeManager_, address fundDeployer_, address integrationManager_, address policyManager_, address primitivePriceFeed_, address valueInterpreter_ ) { return ( DISPATCHER, FEE_MANAGER, FUND_DEPLOYER, INTEGRATION_MANAGER, POLICY_MANAGER, PRIMITIVE_PRICE_FEED, VALUE_INTERPRETER ); } /// @notice Gets the `overridePause` variable /// @return overridePause_ The `overridePause` variable value function getOverridePause() external view returns (bool overridePause_) { return overridePause; } /// @notice Gets the `sharesActionTimelock` variable /// @return sharesActionTimelock_ The `sharesActionTimelock` variable value function getSharesActionTimelock() external view returns (uint256 sharesActionTimelock_) { return sharesActionTimelock; } /// @notice Gets the `vaultProxy` variable /// @return vaultProxy_ The `vaultProxy` variable value function getVaultProxy() external view override returns (address vaultProxy_) { return vaultProxy; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../persistent/dispatcher/IDispatcher.sol"; import "../../../../persistent/vault/VaultLibBase1.sol"; import "./IVault.sol"; /// @title VaultLib Contract /// @author Enzyme Council <[email protected]> /// @notice The per-release proxiable library contract for VaultProxy /// @dev The difference in terminology between "asset" and "trackedAsset" is intentional. /// A fund might actually have asset balances of un-tracked assets, /// but only tracked assets are used in gav calculations. /// Note that this contract inherits VaultLibSafeMath (a verbatim Open Zeppelin SafeMath copy) /// from SharesTokenBase via VaultLibBase1 contract VaultLib is VaultLibBase1, IVault { using SafeERC20 for ERC20; // Before updating TRACKED_ASSETS_LIMIT in the future, it is important to consider: // 1. The highest tracked assets limit ever allowed in the protocol // 2. That the next value will need to be respected by all future releases uint256 private constant TRACKED_ASSETS_LIMIT = 20; modifier onlyAccessor() { require(msg.sender == accessor, "Only the designated accessor can make this call"); _; } ///////////// // GENERAL // ///////////// /// @notice Sets the account that is allowed to migrate a fund to new releases /// @param _nextMigrator The account to set as the allowed migrator /// @dev Set to address(0) to remove the migrator. function setMigrator(address _nextMigrator) external { require(msg.sender == owner, "setMigrator: Only the owner can call this function"); address prevMigrator = migrator; require(_nextMigrator != prevMigrator, "setMigrator: Value already set"); migrator = _nextMigrator; emit MigratorSet(prevMigrator, _nextMigrator); } /////////// // VAULT // /////////// /// @notice Adds a tracked asset to the fund /// @param _asset The asset to add /// @dev Allows addition of already tracked assets to fail silently. function addTrackedAsset(address _asset) external override onlyAccessor { if (!isTrackedAsset(_asset)) { require( trackedAssets.length < TRACKED_ASSETS_LIMIT, "addTrackedAsset: Limit exceeded" ); assetToIsTracked[_asset] = true; trackedAssets.push(_asset); emit TrackedAssetAdded(_asset); } } /// @notice Grants an allowance to a spender to use the fund's asset /// @param _asset The asset for which to grant an allowance /// @param _target The spender of the allowance /// @param _amount The amount of the allowance function approveAssetSpender( address _asset, address _target, uint256 _amount ) external override onlyAccessor { ERC20(_asset).approve(_target, _amount); } /// @notice Makes an arbitrary call with this contract as the sender /// @param _contract The contract to call /// @param _callData The call data for the call function callOnContract(address _contract, bytes calldata _callData) external override onlyAccessor { (bool success, bytes memory returnData) = _contract.call(_callData); require(success, string(returnData)); } /// @notice Removes a tracked asset from the fund /// @param _asset The asset to remove function removeTrackedAsset(address _asset) external override onlyAccessor { __removeTrackedAsset(_asset); } /// @notice Withdraws an asset from the VaultProxy to a given account /// @param _asset The asset to withdraw /// @param _target The account to which to withdraw the asset /// @param _amount The amount of asset to withdraw function withdrawAssetTo( address _asset, address _target, uint256 _amount ) external override onlyAccessor { ERC20(_asset).safeTransfer(_target, _amount); emit AssetWithdrawn(_asset, _target, _amount); } /// @dev Helper to the get the Vault's balance of a given asset function __getAssetBalance(address _asset) private view returns (uint256 balance_) { return ERC20(_asset).balanceOf(address(this)); } /// @dev Helper to remove an asset from a fund's tracked assets. /// Allows removal of non-tracked asset to fail silently. function __removeTrackedAsset(address _asset) private { if (isTrackedAsset(_asset)) { assetToIsTracked[_asset] = false; uint256 trackedAssetsCount = trackedAssets.length; for (uint256 i = 0; i < trackedAssetsCount; i++) { if (trackedAssets[i] == _asset) { if (i < trackedAssetsCount - 1) { trackedAssets[i] = trackedAssets[trackedAssetsCount - 1]; } trackedAssets.pop(); break; } } emit TrackedAssetRemoved(_asset); } } //////////// // SHARES // //////////// /// @notice Burns fund shares from a particular account /// @param _target The account for which to burn shares /// @param _amount The amount of shares to burn function burnShares(address _target, uint256 _amount) external override onlyAccessor { __burn(_target, _amount); } /// @notice Mints fund shares to a particular account /// @param _target The account for which to burn shares /// @param _amount The amount of shares to mint function mintShares(address _target, uint256 _amount) external override onlyAccessor { __mint(_target, _amount); } /// @notice Transfers fund shares from one account to another /// @param _from The account from which to transfer shares /// @param _to The account to which to transfer shares /// @param _amount The amount of shares to transfer function transferShares( address _from, address _to, uint256 _amount ) external override onlyAccessor { __transfer(_from, _to, _amount); } // ERC20 overrides /// @dev Disallows the standard ERC20 approve() function function approve(address, uint256) public override returns (bool) { revert("Unimplemented"); } /// @notice Gets the `symbol` value of the shares token /// @return symbol_ The `symbol` value /// @dev Defers the shares symbol value to the Dispatcher contract function symbol() public view override returns (string memory symbol_) { return IDispatcher(creator).getSharesTokenSymbol(); } /// @dev Disallows the standard ERC20 transfer() function function transfer(address, uint256) public override returns (bool) { revert("Unimplemented"); } /// @dev Disallows the standard ERC20 transferFrom() function function transferFrom( address, address, uint256 ) public override returns (bool) { revert("Unimplemented"); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `accessor` variable /// @return accessor_ The `accessor` variable value function getAccessor() external view override returns (address accessor_) { return accessor; } /// @notice Gets the `creator` variable /// @return creator_ The `creator` variable value function getCreator() external view returns (address creator_) { return creator; } /// @notice Gets the `migrator` variable /// @return migrator_ The `migrator` variable value function getMigrator() external view returns (address migrator_) { return migrator; } /// @notice Gets the `owner` variable /// @return owner_ The `owner` variable value function getOwner() external view override returns (address owner_) { return owner; } /// @notice Gets the `trackedAssets` variable /// @return trackedAssets_ The `trackedAssets` variable value function getTrackedAssets() external view override returns (address[] memory trackedAssets_) { return trackedAssets; } /// @notice Check whether an address is a tracked asset of the fund /// @param _asset The address to check /// @return isTrackedAsset_ True if the address is a tracked asset of the fund function isTrackedAsset(address _asset) public view override returns (bool isTrackedAsset_) { return assetToIsTracked[_asset]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../price-feeds/derivatives/IAggregatedDerivativePriceFeed.sol"; import "../price-feeds/derivatives/IDerivativePriceFeed.sol"; import "../price-feeds/primitives/IPrimitivePriceFeed.sol"; import "./IValueInterpreter.sol"; /// @title ValueInterpreter Contract /// @author Enzyme Council <[email protected]> /// @notice Interprets price feeds to provide covert value between asset pairs /// @dev This contract contains several "live" value calculations, which for this release are simply /// aliases to their "canonical" value counterparts since the only primitive price feed (Chainlink) /// is immutable in this contract and only has one type of value. Including the "live" versions of /// functions only serves as a placeholder for infrastructural components and plugins (e.g., policies) /// to explicitly define the types of values that they should (and will) be using in a future release. contract ValueInterpreter is IValueInterpreter { using SafeMath for uint256; address private immutable AGGREGATED_DERIVATIVE_PRICE_FEED; address private immutable PRIMITIVE_PRICE_FEED; constructor(address _primitivePriceFeed, address _aggregatedDerivativePriceFeed) public { AGGREGATED_DERIVATIVE_PRICE_FEED = _aggregatedDerivativePriceFeed; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; } // EXTERNAL FUNCTIONS /// @notice An alias of calcCanonicalAssetsTotalValue function calcLiveAssetsTotalValue( address[] calldata _baseAssets, uint256[] calldata _amounts, address _quoteAsset ) external override returns (uint256 value_, bool isValid_) { return calcCanonicalAssetsTotalValue(_baseAssets, _amounts, _quoteAsset); } /// @notice An alias of calcCanonicalAssetValue function calcLiveAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) external override returns (uint256 value_, bool isValid_) { return calcCanonicalAssetValue(_baseAsset, _amount, _quoteAsset); } // PUBLIC FUNCTIONS /// @notice Calculates the total value of given amounts of assets in a single quote asset /// @param _baseAssets The assets to convert /// @param _amounts The amounts of the _baseAssets to convert /// @param _quoteAsset The asset to which to convert /// @return value_ The sum value of _baseAssets, denominated in the _quoteAsset /// @return isValid_ True if the price feed rates used to derive value are all valid /// @dev Does not alter protocol state, /// but not a view because calls to price feeds can potentially update third party state function calcCanonicalAssetsTotalValue( address[] memory _baseAssets, uint256[] memory _amounts, address _quoteAsset ) public override returns (uint256 value_, bool isValid_) { require( _baseAssets.length == _amounts.length, "calcCanonicalAssetsTotalValue: Arrays unequal lengths" ); require( IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_quoteAsset), "calcCanonicalAssetsTotalValue: Unsupported _quoteAsset" ); isValid_ = true; for (uint256 i; i < _baseAssets.length; i++) { (uint256 assetValue, bool assetValueIsValid) = __calcAssetValue( _baseAssets[i], _amounts[i], _quoteAsset ); value_ = value_.add(assetValue); if (!assetValueIsValid) { isValid_ = false; } } return (value_, isValid_); } /// @notice Calculates the value of a given amount of one asset in terms of another asset /// @param _baseAsset The asset from which to convert /// @param _amount The amount of the _baseAsset to convert /// @param _quoteAsset The asset to which to convert /// @return value_ The equivalent quantity in the _quoteAsset /// @return isValid_ True if the price feed rates used to derive value are all valid /// @dev Does not alter protocol state, /// but not a view because calls to price feeds can potentially update third party state function calcCanonicalAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) public override returns (uint256 value_, bool isValid_) { if (_baseAsset == _quoteAsset || _amount == 0) { return (_amount, true); } require( IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_quoteAsset), "calcCanonicalAssetValue: Unsupported _quoteAsset" ); return __calcAssetValue(_baseAsset, _amount, _quoteAsset); } // PRIVATE FUNCTIONS /// @dev Helper to differentially calculate an asset value /// based on if it is a primitive or derivative asset. function __calcAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) private returns (uint256 value_, bool isValid_) { if (_baseAsset == _quoteAsset || _amount == 0) { return (_amount, true); } // Handle case that asset is a primitive if (IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_baseAsset)) { return IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).calcCanonicalValue( _baseAsset, _amount, _quoteAsset ); } // Handle case that asset is a derivative address derivativePriceFeed = IAggregatedDerivativePriceFeed( AGGREGATED_DERIVATIVE_PRICE_FEED ) .getPriceFeedForDerivative(_baseAsset); if (derivativePriceFeed != address(0)) { return __calcDerivativeValue(derivativePriceFeed, _baseAsset, _amount, _quoteAsset); } revert("__calcAssetValue: Unsupported _baseAsset"); } /// @dev Helper to calculate the value of a derivative in an arbitrary asset. /// Handles multiple underlying assets (e.g., Uniswap and Balancer pool tokens). /// Handles underlying assets that are also derivatives (e.g., a cDAI-ETH LP) function __calcDerivativeValue( address _derivativePriceFeed, address _derivative, uint256 _amount, address _quoteAsset ) private returns (uint256 value_, bool isValid_) { (address[] memory underlyings, uint256[] memory underlyingAmounts) = IDerivativePriceFeed( _derivativePriceFeed ) .calcUnderlyingValues(_derivative, _amount); require(underlyings.length > 0, "__calcDerivativeValue: No underlyings"); require( underlyings.length == underlyingAmounts.length, "__calcDerivativeValue: Arrays unequal lengths" ); // Let validity be negated if any of the underlying value calculations are invalid isValid_ = true; for (uint256 i = 0; i < underlyings.length; i++) { (uint256 underlyingValue, bool underlyingValueIsValid) = __calcAssetValue( underlyings[i], underlyingAmounts[i], _quoteAsset ); if (!underlyingValueIsValid) { isValid_ = false; } value_ = value_.add(underlyingValue); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `AGGREGATED_DERIVATIVE_PRICE_FEED` variable /// @return aggregatedDerivativePriceFeed_ The `AGGREGATED_DERIVATIVE_PRICE_FEED` variable value function getAggregatedDerivativePriceFeed() external view returns (address aggregatedDerivativePriceFeed_) { return AGGREGATED_DERIVATIVE_PRICE_FEED; } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDispatcher Interface /// @author Enzyme Council <[email protected]> interface IDispatcher { function cancelMigration(address _vaultProxy, bool _bypassFailure) external; function claimOwnership() external; function deployVaultProxy( address _vaultLib, address _owner, address _vaultAccessor, string calldata _fundName ) external returns (address vaultProxy_); function executeMigration(address _vaultProxy, bool _bypassFailure) external; function getCurrentFundDeployer() external view returns (address currentFundDeployer_); function getFundDeployerForVaultProxy(address _vaultProxy) external view returns (address fundDeployer_); function getMigrationRequestDetailsForVaultProxy(address _vaultProxy) external view returns ( address nextFundDeployer_, address nextVaultAccessor_, address nextVaultLib_, uint256 executableTimestamp_ ); function getMigrationTimelock() external view returns (uint256 migrationTimelock_); function getNominatedOwner() external view returns (address nominatedOwner_); function getOwner() external view returns (address owner_); function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_); function getTimelockRemainingForMigrationRequest(address _vaultProxy) external view returns (uint256 secondsRemaining_); function hasExecutableMigrationRequest(address _vaultProxy) external view returns (bool hasExecutableRequest_); function hasMigrationRequest(address _vaultProxy) external view returns (bool hasMigrationRequest_); function removeNominatedOwner() external; function setCurrentFundDeployer(address _nextFundDeployer) external; function setMigrationTimelock(uint256 _nextTimelock) external; function setNominatedOwner(address _nextNominatedOwner) external; function setSharesTokenSymbol(string calldata _nextSymbol) external; function signalMigration( address _vaultProxy, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title FeeManager Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for the FeeManager interface IFeeManager { // No fees for the current release are implemented post-redeemShares enum FeeHook { Continuous, BuySharesSetup, PreBuyShares, PostBuyShares, BuySharesCompleted, PreRedeemShares } enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding} function invokeHook( FeeHook, bytes calldata, uint256 ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IPrimitivePriceFeed Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for primitive price feeds interface IPrimitivePriceFeed { function calcCanonicalValue( address, uint256, address ) external view returns (uint256, bool); function calcLiveValue( address, uint256, address ) external view returns (uint256, bool); function isSupportedAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IValueInterpreter interface /// @author Enzyme Council <[email protected]> /// @notice Interface for ValueInterpreter interface IValueInterpreter { function calcCanonicalAssetValue( address, uint256, address ) external returns (uint256, bool); function calcCanonicalAssetsTotalValue( address[] calldata, uint256[] calldata, address ) external returns (uint256, bool); function calcLiveAssetValue( address, uint256, address ) external returns (uint256, bool); function calcLiveAssetsTotalValue( address[] calldata, uint256[] calldata, address ) external returns (uint256, bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../infrastructure/price-feeds/derivatives/feeds/SynthetixPriceFeed.sol"; import "../interfaces/ISynthetixAddressResolver.sol"; import "../interfaces/ISynthetixExchanger.sol"; /// @title AssetFinalityResolver Contract /// @author Enzyme Council <[email protected]> /// @notice A contract that helps achieve asset finality abstract contract AssetFinalityResolver { address internal immutable SYNTHETIX_ADDRESS_RESOLVER; address internal immutable SYNTHETIX_PRICE_FEED; constructor(address _synthetixPriceFeed, address _synthetixAddressResolver) public { SYNTHETIX_ADDRESS_RESOLVER = _synthetixAddressResolver; SYNTHETIX_PRICE_FEED = _synthetixPriceFeed; } /// @dev Helper to finalize a Synth balance at a given target address and return its balance function __finalizeIfSynthAndGetAssetBalance( address _target, address _asset, bool _requireFinality ) internal returns (uint256 assetBalance_) { bytes32 currencyKey = SynthetixPriceFeed(SYNTHETIX_PRICE_FEED).getCurrencyKeyForSynth( _asset ); if (currencyKey != 0) { address synthetixExchanger = ISynthetixAddressResolver(SYNTHETIX_ADDRESS_RESOLVER) .requireAndGetAddress( "Exchanger", "finalizeAndGetAssetBalance: Missing Exchanger" ); try ISynthetixExchanger(synthetixExchanger).settle(_target, currencyKey) {} catch { require(!_requireFinality, "finalizeAndGetAssetBalance: Cannot settle Synth"); } } return ERC20(_asset).balanceOf(_target); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `SYNTHETIX_ADDRESS_RESOLVER` variable /// @return synthetixAddressResolver_ The `SYNTHETIX_ADDRESS_RESOLVER` variable value function getSynthetixAddressResolver() external view returns (address synthetixAddressResolver_) { return SYNTHETIX_ADDRESS_RESOLVER; } /// @notice Gets the `SYNTHETIX_PRICE_FEED` variable /// @return synthetixPriceFeed_ The `SYNTHETIX_PRICE_FEED` variable value function getSynthetixPriceFeed() external view returns (address synthetixPriceFeed_) { return SYNTHETIX_PRICE_FEED; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/ISynthetix.sol"; import "../../../../interfaces/ISynthetixAddressResolver.sol"; import "../../../../interfaces/ISynthetixExchangeRates.sol"; import "../../../../interfaces/ISynthetixProxyERC20.sol"; import "../../../../interfaces/ISynthetixSynth.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../IDerivativePriceFeed.sol"; /// @title SynthetixPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice A price feed that uses Synthetix oracles as price sources contract SynthetixPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event SynthAdded(address indexed synth, bytes32 currencyKey); event SynthCurrencyKeyUpdated( address indexed synth, bytes32 prevCurrencyKey, bytes32 nextCurrencyKey ); uint256 private constant SYNTH_UNIT = 10**18; address private immutable ADDRESS_RESOLVER; address private immutable SUSD; mapping(address => bytes32) private synthToCurrencyKey; constructor( address _dispatcher, address _addressResolver, address _sUSD, address[] memory _synths ) public DispatcherOwnerMixin(_dispatcher) { ADDRESS_RESOLVER = _addressResolver; SUSD = _sUSD; address[] memory sUSDSynths = new address[](1); sUSDSynths[0] = _sUSD; __addSynths(sUSDSynths); __addSynths(_synths); } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { underlyings_ = new address[](1); underlyings_[0] = SUSD; underlyingAmounts_ = new uint256[](1); bytes32 currencyKey = getCurrencyKeyForSynth(_derivative); require(currencyKey != 0, "calcUnderlyingValues: _derivative is not supported"); address exchangeRates = ISynthetixAddressResolver(ADDRESS_RESOLVER).requireAndGetAddress( "ExchangeRates", "calcUnderlyingValues: Missing ExchangeRates" ); (uint256 rate, bool isInvalid) = ISynthetixExchangeRates(exchangeRates).rateAndInvalid( currencyKey ); require(!isInvalid, "calcUnderlyingValues: _derivative rate is not valid"); underlyingAmounts_[0] = _derivativeAmount.mul(rate).div(SYNTH_UNIT); return (underlyings_, underlyingAmounts_); } /// @notice Checks whether an asset is a supported primitive of the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported primitive function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return getCurrencyKeyForSynth(_asset) != 0; } ///////////////////// // SYNTHS REGISTRY // ///////////////////// /// @notice Adds Synths to the price feed /// @param _synths Synths to add function addSynths(address[] calldata _synths) external onlyDispatcherOwner { require(_synths.length > 0, "addSynths: Empty _synths"); __addSynths(_synths); } /// @notice Updates the cached currencyKey value for specified Synths /// @param _synths Synths to update /// @dev Anybody can call this function function updateSynthCurrencyKeys(address[] calldata _synths) external { require(_synths.length > 0, "updateSynthCurrencyKeys: Empty _synths"); for (uint256 i; i < _synths.length; i++) { bytes32 prevCurrencyKey = synthToCurrencyKey[_synths[i]]; require(prevCurrencyKey != 0, "updateSynthCurrencyKeys: Synth not set"); bytes32 nextCurrencyKey = __getCurrencyKey(_synths[i]); require( nextCurrencyKey != prevCurrencyKey, "updateSynthCurrencyKeys: Synth has correct currencyKey" ); synthToCurrencyKey[_synths[i]] = nextCurrencyKey; emit SynthCurrencyKeyUpdated(_synths[i], prevCurrencyKey, nextCurrencyKey); } } /// @dev Helper to add Synths function __addSynths(address[] memory _synths) private { for (uint256 i; i < _synths.length; i++) { require(synthToCurrencyKey[_synths[i]] == 0, "__addSynths: Value already set"); bytes32 currencyKey = __getCurrencyKey(_synths[i]); require(currencyKey != 0, "__addSynths: No currencyKey"); synthToCurrencyKey[_synths[i]] = currencyKey; emit SynthAdded(_synths[i], currencyKey); } } /// @dev Helper to query a currencyKey from Synthetix function __getCurrencyKey(address _synthProxy) private view returns (bytes32 currencyKey_) { return ISynthetixSynth(ISynthetixProxyERC20(_synthProxy).target()).currencyKey(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_RESOLVER` variable /// @return addressResolver_ The `ADDRESS_RESOLVER` variable value function getAddressResolver() external view returns (address) { return ADDRESS_RESOLVER; } /// @notice Gets the currencyKey for multiple given Synths /// @return currencyKeys_ The currencyKey values function getCurrencyKeysForSynths(address[] calldata _synths) external view returns (bytes32[] memory currencyKeys_) { currencyKeys_ = new bytes32[](_synths.length); for (uint256 i; i < _synths.length; i++) { currencyKeys_[i] = synthToCurrencyKey[_synths[i]]; } return currencyKeys_; } /// @notice Gets the `SUSD` variable /// @return susd_ The `SUSD` variable value function getSUSD() external view returns (address susd_) { return SUSD; } /// @notice Gets the currencyKey for a given Synth /// @return currencyKey_ The currencyKey value function getCurrencyKeyForSynth(address _synth) public view returns (bytes32 currencyKey_) { return synthToCurrencyKey[_synth]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixAddressResolver Interface /// @author Enzyme Council <[email protected]> interface ISynthetixAddressResolver { function requireAndGetAddress(bytes32, string calldata) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixExchanger Interface /// @author Enzyme Council <[email protected]> interface ISynthetixExchanger { function getAmountsForExchange( uint256, bytes32, bytes32 ) external view returns ( uint256, uint256, uint256 ); function settle(address, bytes32) external returns ( uint256, uint256, uint256 ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetix Interface /// @author Enzyme Council <[email protected]> interface ISynthetix { function exchangeOnBehalfWithTracking( address, bytes32, uint256, bytes32, address, bytes32 ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixExchangeRates Interface /// @author Enzyme Council <[email protected]> interface ISynthetixExchangeRates { function rateAndInvalid(bytes32) external view returns (uint256, bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixProxyERC20 Interface /// @author Enzyme Council <[email protected]> interface ISynthetixProxyERC20 { function target() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ISynthetixSynth Interface /// @author Enzyme Council <[email protected]> interface ISynthetixSynth { function currencyKey() external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../persistent/dispatcher/IDispatcher.sol"; /// @title DispatcherOwnerMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract that defers ownership to the owner of Dispatcher abstract contract DispatcherOwnerMixin { address internal immutable DISPATCHER; modifier onlyDispatcherOwner() { require( msg.sender == getOwner(), "onlyDispatcherOwner: Only the Dispatcher owner can call this function" ); _; } constructor(address _dispatcher) public { DISPATCHER = _dispatcher; } /// @notice Gets the owner of this contract /// @return owner_ The owner /// @dev Ownership is deferred to the owner of the Dispatcher contract function getOwner() public view returns (address owner_) { return IDispatcher(DISPATCHER).getOwner(); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `DISPATCHER` variable /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() external view returns (address dispatcher_) { return DISPATCHER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IDerivativePriceFeed Interface /// @author Enzyme Council <[email protected]> /// @notice Simple interface for derivative price source oracle implementations interface IDerivativePriceFeed { function calcUnderlyingValues(address, uint256) external returns (address[] memory, uint256[] memory); function isSupportedAsset(address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./VaultLibBaseCore.sol"; /// @title VaultLibBase1 Contract /// @author Enzyme Council <[email protected]> /// @notice The first implementation of VaultLibBaseCore, with additional events and storage /// @dev All subsequent implementations should inherit the previous implementation, /// e.g., `VaultLibBase2 is VaultLibBase1` /// DO NOT EDIT CONTRACT. abstract contract VaultLibBase1 is VaultLibBaseCore { event AssetWithdrawn(address indexed asset, address indexed target, uint256 amount); event TrackedAssetAdded(address asset); event TrackedAssetRemoved(address asset); address[] internal trackedAssets; mapping(address => bool) internal assetToIsTracked; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/IMigratableVault.sol"; import "./utils/ProxiableVaultLib.sol"; import "./utils/SharesTokenBase.sol"; /// @title VaultLibBaseCore Contract /// @author Enzyme Council <[email protected]> /// @notice A persistent contract containing all required storage variables and /// required functions for a VaultLib implementation /// @dev DO NOT EDIT CONTRACT. If new events or storage are necessary, they should be added to /// a numbered VaultLibBaseXXX that inherits the previous base. See VaultLibBase1. abstract contract VaultLibBaseCore is IMigratableVault, ProxiableVaultLib, SharesTokenBase { event AccessorSet(address prevAccessor, address nextAccessor); event MigratorSet(address prevMigrator, address nextMigrator); event OwnerSet(address prevOwner, address nextOwner); event VaultLibSet(address prevVaultLib, address nextVaultLib); address internal accessor; address internal creator; address internal migrator; address internal owner; // EXTERNAL FUNCTIONS /// @notice Initializes the VaultProxy with core configuration /// @param _owner The address to set as the fund owner /// @param _accessor The address to set as the permissioned accessor of the VaultLib /// @param _fundName The name of the fund /// @dev Serves as a per-proxy pseudo-constructor function init( address _owner, address _accessor, string calldata _fundName ) external override { require(creator == address(0), "init: Proxy already initialized"); creator = msg.sender; sharesName = _fundName; __setAccessor(_accessor); __setOwner(_owner); emit VaultLibSet(address(0), getVaultLib()); } /// @notice Sets the permissioned accessor of the VaultLib /// @param _nextAccessor The address to set as the permissioned accessor of the VaultLib function setAccessor(address _nextAccessor) external override { require(msg.sender == creator, "setAccessor: Only callable by the contract creator"); __setAccessor(_nextAccessor); } /// @notice Sets the VaultLib target for the VaultProxy /// @param _nextVaultLib The address to set as the VaultLib /// @dev This function is absolutely critical. __updateCodeAddress() validates that the /// target is a valid Proxiable contract instance. /// Does not block _nextVaultLib from being the same as the current VaultLib function setVaultLib(address _nextVaultLib) external override { require(msg.sender == creator, "setVaultLib: Only callable by the contract creator"); address prevVaultLib = getVaultLib(); __updateCodeAddress(_nextVaultLib); emit VaultLibSet(prevVaultLib, _nextVaultLib); } // PUBLIC FUNCTIONS /// @notice Checks whether an account is allowed to migrate the VaultProxy /// @param _who The account to check /// @return canMigrate_ True if the account is allowed to migrate the VaultProxy function canMigrate(address _who) public view virtual override returns (bool canMigrate_) { return _who == owner || _who == migrator; } /// @notice Gets the VaultLib target for the VaultProxy /// @return vaultLib_ The address of the VaultLib target function getVaultLib() public view returns (address vaultLib_) { assembly { // solium-disable-line vaultLib_ := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc) } return vaultLib_; } // INTERNAL FUNCTIONS /// @dev Helper to set the permissioned accessor of the VaultProxy. /// Does not prevent the prevAccessor from being the _nextAccessor. function __setAccessor(address _nextAccessor) internal { require(_nextAccessor != address(0), "__setAccessor: _nextAccessor cannot be empty"); address prevAccessor = accessor; accessor = _nextAccessor; emit AccessorSet(prevAccessor, _nextAccessor); } /// @dev Helper to set the owner of the VaultProxy function __setOwner(address _nextOwner) internal { require(_nextOwner != address(0), "__setOwner: _nextOwner cannot be empty"); address prevOwner = owner; require(_nextOwner != prevOwner, "__setOwner: _nextOwner is the current owner"); owner = _nextOwner; emit OwnerSet(prevOwner, _nextOwner); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ProxiableVaultLib Contract /// @author Enzyme Council <[email protected]> /// @notice A contract that defines the upgrade behavior for VaultLib instances /// @dev The recommended implementation of the target of a proxy according to EIP-1822 and EIP-1967 /// Code position in storage is `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, /// which is "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc". abstract contract ProxiableVaultLib { /// @dev Updates the target of the proxy to be the contract at _nextVaultLib function __updateCodeAddress(address _nextVaultLib) internal { require( bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) == ProxiableVaultLib(_nextVaultLib).proxiableUUID(), "__updateCodeAddress: _nextVaultLib not compatible" ); assembly { // solium-disable-line sstore( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _nextVaultLib ) } } /// @notice Returns a unique bytes32 hash for VaultLib instances /// @return uuid_ The bytes32 hash representing the UUID /// @dev The UUID is `bytes32(keccak256('mln.proxiable.vaultlib'))` function proxiableUUID() public pure returns (bytes32 uuid_) { return 0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./VaultLibSafeMath.sol"; /// @title StandardERC20 Contract /// @author Enzyme Council <[email protected]> /// @notice Contains the storage, events, and default logic of an ERC20-compliant contract. /// @dev The logic can be overridden by VaultLib implementations. /// Adapted from OpenZeppelin 3.2.0. /// DO NOT EDIT THIS CONTRACT. abstract contract SharesTokenBase { using VaultLibSafeMath for uint256; event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed from, address indexed to, uint256 value); string internal sharesName; string internal sharesSymbol; uint256 internal sharesTotalSupply; mapping(address => uint256) internal sharesBalances; mapping(address => mapping(address => uint256)) internal sharesAllowances; // EXTERNAL FUNCTIONS /// @dev Standard implementation of ERC20's approve(). Can be overridden. function approve(address _spender, uint256 _amount) public virtual returns (bool) { __approve(msg.sender, _spender, _amount); return true; } /// @dev Standard implementation of ERC20's transfer(). Can be overridden. function transfer(address _recipient, uint256 _amount) public virtual returns (bool) { __transfer(msg.sender, _recipient, _amount); return true; } /// @dev Standard implementation of ERC20's transferFrom(). Can be overridden. function transferFrom( address _sender, address _recipient, uint256 _amount ) public virtual returns (bool) { __transfer(_sender, _recipient, _amount); __approve( _sender, msg.sender, sharesAllowances[_sender][msg.sender].sub( _amount, "ERC20: transfer amount exceeds allowance" ) ); return true; } // EXTERNAL FUNCTIONS - VIEW /// @dev Standard implementation of ERC20's allowance(). Can be overridden. function allowance(address _owner, address _spender) public view virtual returns (uint256) { return sharesAllowances[_owner][_spender]; } /// @dev Standard implementation of ERC20's balanceOf(). Can be overridden. function balanceOf(address _account) public view virtual returns (uint256) { return sharesBalances[_account]; } /// @dev Standard implementation of ERC20's decimals(). Can not be overridden. function decimals() public pure returns (uint8) { return 18; } /// @dev Standard implementation of ERC20's name(). Can be overridden. function name() public view virtual returns (string memory) { return sharesName; } /// @dev Standard implementation of ERC20's symbol(). Can be overridden. function symbol() public view virtual returns (string memory) { return sharesSymbol; } /// @dev Standard implementation of ERC20's totalSupply(). Can be overridden. function totalSupply() public view virtual returns (uint256) { return sharesTotalSupply; } // INTERNAL FUNCTIONS /// @dev Helper for approve(). Can be overridden. function __approve( address _owner, address _spender, uint256 _amount ) internal virtual { require(_owner != address(0), "ERC20: approve from the zero address"); require(_spender != address(0), "ERC20: approve to the zero address"); sharesAllowances[_owner][_spender] = _amount; emit Approval(_owner, _spender, _amount); } /// @dev Helper to burn tokens from an account. Can be overridden. function __burn(address _account, uint256 _amount) internal virtual { require(_account != address(0), "ERC20: burn from the zero address"); sharesBalances[_account] = sharesBalances[_account].sub( _amount, "ERC20: burn amount exceeds balance" ); sharesTotalSupply = sharesTotalSupply.sub(_amount); emit Transfer(_account, address(0), _amount); } /// @dev Helper to mint tokens to an account. Can be overridden. function __mint(address _account, uint256 _amount) internal virtual { require(_account != address(0), "ERC20: mint to the zero address"); sharesTotalSupply = sharesTotalSupply.add(_amount); sharesBalances[_account] = sharesBalances[_account].add(_amount); emit Transfer(address(0), _account, _amount); } /// @dev Helper to transfer tokens between accounts. Can be overridden. function __transfer( address _sender, address _recipient, uint256 _amount ) internal virtual { require(_sender != address(0), "ERC20: transfer from the zero address"); require(_recipient != address(0), "ERC20: transfer to the zero address"); sharesBalances[_sender] = sharesBalances[_sender].sub( _amount, "ERC20: transfer amount exceeds balance" ); sharesBalances[_recipient] = sharesBalances[_recipient].add(_amount); emit Transfer(_sender, _recipient, _amount); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title VaultLibSafeMath library /// @notice A narrowed, verbatim implementation of OpenZeppelin 3.2.0 SafeMath /// for use with VaultLib /// @dev Preferred to importing from npm to guarantee consistent logic and revert reasons /// between VaultLib implementations /// DO NOT EDIT THIS CONTRACT library VaultLibSafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "VaultLibSafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "VaultLibSafeMath: subtraction overflow"); } function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "VaultLibSafeMath: multiplication overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "VaultLibSafeMath: division by zero"); } function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "VaultLibSafeMath: modulo by zero"); } function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IDerivativePriceFeed.sol"; /// @title IDerivativePriceFeed Interface /// @author Enzyme Council <[email protected]> interface IAggregatedDerivativePriceFeed is IDerivativePriceFeed { function getPriceFeedForDerivative(address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/IUniswapV2Pair.sol"; import "../../../../utils/MathHelpers.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../../../value-interpreter/ValueInterpreter.sol"; import "../../primitives/IPrimitivePriceFeed.sol"; import "../../utils/UniswapV2PoolTokenValueCalculator.sol"; import "../IDerivativePriceFeed.sol"; /// @title UniswapV2PoolPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed for Uniswap lending pool tokens contract UniswapV2PoolPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin, MathHelpers, UniswapV2PoolTokenValueCalculator { event PoolTokenAdded(address indexed poolToken, address token0, address token1); struct PoolTokenInfo { address token0; address token1; uint8 token0Decimals; uint8 token1Decimals; } uint256 private constant POOL_TOKEN_UNIT = 10**18; address private immutable DERIVATIVE_PRICE_FEED; address private immutable FACTORY; address private immutable PRIMITIVE_PRICE_FEED; address private immutable VALUE_INTERPRETER; mapping(address => PoolTokenInfo) private poolTokenToInfo; constructor( address _dispatcher, address _derivativePriceFeed, address _primitivePriceFeed, address _valueInterpreter, address _factory, address[] memory _poolTokens ) public DispatcherOwnerMixin(_dispatcher) { DERIVATIVE_PRICE_FEED = _derivativePriceFeed; FACTORY = _factory; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; VALUE_INTERPRETER = _valueInterpreter; __addPoolTokens(_poolTokens, _derivativePriceFeed, _primitivePriceFeed); } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { PoolTokenInfo memory poolTokenInfo = poolTokenToInfo[_derivative]; underlyings_ = new address[](2); underlyings_[0] = poolTokenInfo.token0; underlyings_[1] = poolTokenInfo.token1; // Calculate the amounts underlying one unit of a pool token, // taking into account the known, trusted rate between the two underlyings (uint256 token0TrustedRateAmount, uint256 token1TrustedRateAmount) = __calcTrustedRate( poolTokenInfo.token0, poolTokenInfo.token1, poolTokenInfo.token0Decimals, poolTokenInfo.token1Decimals ); ( uint256 token0DenormalizedRate, uint256 token1DenormalizedRate ) = __calcTrustedPoolTokenValue( FACTORY, _derivative, token0TrustedRateAmount, token1TrustedRateAmount ); // Define normalized rates for each underlying underlyingAmounts_ = new uint256[](2); underlyingAmounts_[0] = _derivativeAmount.mul(token0DenormalizedRate).div(POOL_TOKEN_UNIT); underlyingAmounts_[1] = _derivativeAmount.mul(token1DenormalizedRate).div(POOL_TOKEN_UNIT); return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return poolTokenToInfo[_asset].token0 != address(0); } // PRIVATE FUNCTIONS /// @dev Calculates the trusted rate of two assets based on our price feeds. /// Uses the decimals-derived unit for whichever asset is used as the quote asset. function __calcTrustedRate( address _token0, address _token1, uint256 _token0Decimals, uint256 _token1Decimals ) private returns (uint256 token0RateAmount_, uint256 token1RateAmount_) { bool rateIsValid; // The quote asset of the value lookup must be a supported primitive asset, // so we cycle through the tokens until reaching a primitive. // If neither is a primitive, will revert at the ValueInterpreter if (IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_token0)) { token1RateAmount_ = 10**_token1Decimals; (token0RateAmount_, rateIsValid) = ValueInterpreter(VALUE_INTERPRETER) .calcCanonicalAssetValue(_token1, token1RateAmount_, _token0); } else { token0RateAmount_ = 10**_token0Decimals; (token1RateAmount_, rateIsValid) = ValueInterpreter(VALUE_INTERPRETER) .calcCanonicalAssetValue(_token0, token0RateAmount_, _token1); } require(rateIsValid, "__calcTrustedRate: Invalid rate"); return (token0RateAmount_, token1RateAmount_); } ////////////////////////// // POOL TOKENS REGISTRY // ////////////////////////// /// @notice Adds Uniswap pool tokens to the price feed /// @param _poolTokens Uniswap pool tokens to add function addPoolTokens(address[] calldata _poolTokens) external onlyDispatcherOwner { require(_poolTokens.length > 0, "addPoolTokens: Empty _poolTokens"); __addPoolTokens(_poolTokens, DERIVATIVE_PRICE_FEED, PRIMITIVE_PRICE_FEED); } /// @dev Helper to add Uniswap pool tokens function __addPoolTokens( address[] memory _poolTokens, address _derivativePriceFeed, address _primitivePriceFeed ) private { for (uint256 i; i < _poolTokens.length; i++) { require(_poolTokens[i] != address(0), "__addPoolTokens: Empty poolToken"); require( poolTokenToInfo[_poolTokens[i]].token0 == address(0), "__addPoolTokens: Value already set" ); IUniswapV2Pair uniswapV2Pair = IUniswapV2Pair(_poolTokens[i]); address token0 = uniswapV2Pair.token0(); address token1 = uniswapV2Pair.token1(); require( __poolTokenIsSupportable( _derivativePriceFeed, _primitivePriceFeed, token0, token1 ), "__addPoolTokens: Unsupported pool token" ); poolTokenToInfo[_poolTokens[i]] = PoolTokenInfo({ token0: token0, token1: token1, token0Decimals: ERC20(token0).decimals(), token1Decimals: ERC20(token1).decimals() }); emit PoolTokenAdded(_poolTokens[i], token0, token1); } } /// @dev Helper to determine if a pool token is supportable, based on whether price feeds are /// available for its underlying feeds. At least one of the underlying tokens must be /// a supported primitive asset, and the other must be a primitive or derivative. function __poolTokenIsSupportable( address _derivativePriceFeed, address _primitivePriceFeed, address _token0, address _token1 ) private view returns (bool isSupportable_) { IDerivativePriceFeed derivativePriceFeedContract = IDerivativePriceFeed( _derivativePriceFeed ); IPrimitivePriceFeed primitivePriceFeedContract = IPrimitivePriceFeed(_primitivePriceFeed); if (primitivePriceFeedContract.isSupportedAsset(_token0)) { if ( primitivePriceFeedContract.isSupportedAsset(_token1) || derivativePriceFeedContract.isSupportedAsset(_token1) ) { return true; } } else if ( derivativePriceFeedContract.isSupportedAsset(_token0) && primitivePriceFeedContract.isSupportedAsset(_token1) ) { return true; } return false; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `DERIVATIVE_PRICE_FEED` variable value /// @return derivativePriceFeed_ The `DERIVATIVE_PRICE_FEED` variable value function getDerivativePriceFeed() external view returns (address derivativePriceFeed_) { return DERIVATIVE_PRICE_FEED; } /// @notice Gets the `FACTORY` variable value /// @return factory_ The `FACTORY` variable value function getFactory() external view returns (address factory_) { return FACTORY; } /// @notice Gets the `PoolTokenInfo` for a given pool token /// @param _poolToken The pool token for which to get the `PoolTokenInfo` /// @return poolTokenInfo_ The `PoolTokenInfo` value function getPoolTokenInfo(address _poolToken) external view returns (PoolTokenInfo memory poolTokenInfo_) { return poolTokenToInfo[_poolToken]; } /// @notice Gets the underlyings for a given pool token /// @param _poolToken The pool token for which to get its underlyings /// @return token0_ The UniswapV2Pair.token0 value /// @return token1_ The UniswapV2Pair.token1 value function getPoolTokenUnderlyings(address _poolToken) external view returns (address token0_, address token1_) { return (poolTokenToInfo[_poolToken].token0, poolTokenToInfo[_poolToken].token1); } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable value /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } /// @notice Gets the `VALUE_INTERPRETER` variable value /// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value function getValueInterpreter() external view returns (address valueInterpreter_) { return VALUE_INTERPRETER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IUniswapV2Pair Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for our interactions with the Uniswap V2's Pair contract interface IUniswapV2Pair { function getReserves() external view returns ( uint112, uint112, uint32 ); function kLast() external view returns (uint256); function token0() external view returns (address); function token1() external view returns (address); function totalSupply() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../interfaces/IUniswapV2Factory.sol"; import "../../../interfaces/IUniswapV2Pair.sol"; /// @title UniswapV2PoolTokenValueCalculator Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract contract for computing the value of Uniswap liquidity pool tokens /// @dev Unless otherwise noted, these functions are adapted to our needs and style guide from /// an un-merged Uniswap branch: /// https://github.com/Uniswap/uniswap-v2-periphery/blob/267ba44471f3357071a2fe2573fe4da42d5ad969/contracts/libraries/UniswapV2LiquidityMathLibrary.sol abstract contract UniswapV2PoolTokenValueCalculator { using SafeMath for uint256; uint256 private constant POOL_TOKEN_UNIT = 10**18; // INTERNAL FUNCTIONS /// @dev Given a Uniswap pool with token0 and token1 and their trusted rate, /// returns the value of one pool token unit in terms of token0 and token1. /// This is the only function used outside of this contract. function __calcTrustedPoolTokenValue( address _factory, address _pair, uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount ) internal view returns (uint256 token0Amount_, uint256 token1Amount_) { (uint256 reserve0, uint256 reserve1) = __calcReservesAfterArbitrage( _pair, _token0TrustedRateAmount, _token1TrustedRateAmount ); return __calcPoolTokenValue(_factory, _pair, reserve0, reserve1); } // PRIVATE FUNCTIONS /// @dev Computes liquidity value given all the parameters of the pair function __calcPoolTokenValue( address _factory, address _pair, uint256 _reserve0, uint256 _reserve1 ) private view returns (uint256 token0Amount_, uint256 token1Amount_) { IUniswapV2Pair pairContract = IUniswapV2Pair(_pair); uint256 totalSupply = pairContract.totalSupply(); if (IUniswapV2Factory(_factory).feeTo() != address(0)) { uint256 kLast = pairContract.kLast(); if (kLast > 0) { uint256 rootK = __uniswapSqrt(_reserve0.mul(_reserve1)); uint256 rootKLast = __uniswapSqrt(kLast); if (rootK > rootKLast) { uint256 numerator = totalSupply.mul(rootK.sub(rootKLast)); uint256 denominator = rootK.mul(5).add(rootKLast); uint256 feeLiquidity = numerator.div(denominator); totalSupply = totalSupply.add(feeLiquidity); } } } return ( _reserve0.mul(POOL_TOKEN_UNIT).div(totalSupply), _reserve1.mul(POOL_TOKEN_UNIT).div(totalSupply) ); } /// @dev Calculates the direction and magnitude of the profit-maximizing trade function __calcProfitMaximizingTrade( uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount, uint256 _reserve0, uint256 _reserve1 ) private pure returns (bool token0ToToken1_, uint256 amountIn_) { token0ToToken1_ = _reserve0.mul(_token1TrustedRateAmount).div(_reserve1) < _token0TrustedRateAmount; uint256 leftSide; uint256 rightSide; if (token0ToToken1_) { leftSide = __uniswapSqrt( _reserve0.mul(_reserve1).mul(_token0TrustedRateAmount).mul(1000).div( _token1TrustedRateAmount.mul(997) ) ); rightSide = _reserve0.mul(1000).div(997); } else { leftSide = __uniswapSqrt( _reserve0.mul(_reserve1).mul(_token1TrustedRateAmount).mul(1000).div( _token0TrustedRateAmount.mul(997) ) ); rightSide = _reserve1.mul(1000).div(997); } if (leftSide < rightSide) { return (false, 0); } // Calculate the amount that must be sent to move the price to the profit-maximizing price amountIn_ = leftSide.sub(rightSide); return (token0ToToken1_, amountIn_); } /// @dev Calculates the pool reserves after an arbitrage moves the price to /// the profit-maximizing rate, given an externally-observed trusted rate /// between the two pooled assets function __calcReservesAfterArbitrage( address _pair, uint256 _token0TrustedRateAmount, uint256 _token1TrustedRateAmount ) private view returns (uint256 reserve0_, uint256 reserve1_) { (reserve0_, reserve1_, ) = IUniswapV2Pair(_pair).getReserves(); // Skip checking whether the reserve is 0, as this is extremely unlikely given how // initial pool liquidity is locked, and since we maintain a list of registered pool tokens // Calculate how much to swap to arb to the trusted price (bool token0ToToken1, uint256 amountIn) = __calcProfitMaximizingTrade( _token0TrustedRateAmount, _token1TrustedRateAmount, reserve0_, reserve1_ ); if (amountIn == 0) { return (reserve0_, reserve1_); } // Adjust the reserves to account for the arb trade to the trusted price if (token0ToToken1) { uint256 amountOut = __uniswapV2GetAmountOut(amountIn, reserve0_, reserve1_); reserve0_ = reserve0_.add(amountIn); reserve1_ = reserve1_.sub(amountOut); } else { uint256 amountOut = __uniswapV2GetAmountOut(amountIn, reserve1_, reserve0_); reserve1_ = reserve1_.add(amountIn); reserve0_ = reserve0_.sub(amountOut); } return (reserve0_, reserve1_); } /// @dev Uniswap square root function. See: /// https://github.com/Uniswap/uniswap-lib/blob/6ddfedd5716ba85b905bf34d7f1f3c659101a1bc/contracts/libraries/Babylonian.sol function __uniswapSqrt(uint256 _y) private pure returns (uint256 z_) { if (_y > 3) { z_ = _y; uint256 x = _y / 2 + 1; while (x < z_) { z_ = x; x = (_y / x + x) / 2; } } else if (_y != 0) { z_ = 1; } // else z_ = 0 return z_; } /// @dev Simplified version of UniswapV2Library's getAmountOut() function. See: /// https://github.com/Uniswap/uniswap-v2-periphery/blob/87edfdcaf49ccc52591502993db4c8c08ea9eec0/contracts/libraries/UniswapV2Library.sol#L42-L50 function __uniswapV2GetAmountOut( uint256 _amountIn, uint256 _reserveIn, uint256 _reserveOut ) private pure returns (uint256 amountOut_) { uint256 amountInWithFee = _amountIn.mul(997); uint256 numerator = amountInWithFee.mul(_reserveOut); uint256 denominator = _reserveIn.mul(1000).add(amountInWithFee); return numerator.div(denominator); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IUniswapV2Factory Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for our interactions with the Uniswap V2's Factory contract interface IUniswapV2Factory { function feeTo() external view returns (address); function getPair(address, address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IChainlinkAggregator.sol"; import "../../../../utils/MakerDaoMath.sol"; import "../IDerivativePriceFeed.sol"; /// @title WdgldPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for WDGLD <https://dgld.ch/> contract WdgldPriceFeed is IDerivativePriceFeed, MakerDaoMath { using SafeMath for uint256; address private immutable XAU_AGGREGATOR; address private immutable ETH_AGGREGATOR; address private immutable WDGLD; address private immutable WETH; // GTR_CONSTANT aggregates all the invariants in the GTR formula to save gas uint256 private constant GTR_CONSTANT = 999990821653213975346065101; uint256 private constant GTR_PRECISION = 10**27; uint256 private constant WDGLD_GENESIS_TIMESTAMP = 1568700000; constructor( address _wdgld, address _weth, address _ethAggregator, address _xauAggregator ) public { WDGLD = _wdgld; WETH = _weth; ETH_AGGREGATOR = _ethAggregator; XAU_AGGREGATOR = _xauAggregator; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only WDGLD is supported"); underlyings_ = new address[](1); underlyings_[0] = WETH; underlyingAmounts_ = new uint256[](1); // Get price rates from xau and eth aggregators int256 xauToUsdRate = IChainlinkAggregator(XAU_AGGREGATOR).latestAnswer(); int256 ethToUsdRate = IChainlinkAggregator(ETH_AGGREGATOR).latestAnswer(); require(xauToUsdRate > 0 && ethToUsdRate > 0, "calcUnderlyingValues: rate invalid"); uint256 wdgldToXauRate = calcWdgldToXauRate(); // 10**17 is a combination of ETH_UNIT / WDGLD_UNIT * GTR_PRECISION underlyingAmounts_[0] = _derivativeAmount .mul(wdgldToXauRate) .mul(uint256(xauToUsdRate)) .div(uint256(ethToUsdRate)) .div(10**17); return (underlyings_, underlyingAmounts_); } /// @notice Calculates the rate of WDGLD to XAU. /// @return wdgldToXauRate_ The current rate of WDGLD to XAU /// @dev Full formula available <https://dgld.ch/assets/documents/dgld-whitepaper.pdf> function calcWdgldToXauRate() public view returns (uint256 wdgldToXauRate_) { return __rpow( GTR_CONSTANT, ((block.timestamp).sub(WDGLD_GENESIS_TIMESTAMP)).div(28800), // 60 * 60 * 8 (8 hour periods) GTR_PRECISION ) .div(10); } /// @notice Checks if an asset is supported by this price feed /// @param _asset The asset to check /// @return isSupported_ True if supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == WDGLD; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ETH_AGGREGATOR` address /// @return ethAggregatorAddress_ The `ETH_AGGREGATOR` address function getEthAggregator() external view returns (address ethAggregatorAddress_) { return ETH_AGGREGATOR; } /// @notice Gets the `WDGLD` token address /// @return wdgld_ The `WDGLD` token address function getWdgld() external view returns (address wdgld_) { return WDGLD; } /// @notice Gets the `WETH` token address /// @return weth_ The `WETH` token address function getWeth() external view returns (address weth_) { return WETH; } /// @notice Gets the `XAU_AGGREGATOR` address /// @return xauAggregatorAddress_ The `XAU_AGGREGATOR` address function getXauAggregator() external view returns (address xauAggregatorAddress_) { return XAU_AGGREGATOR; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IChainlinkAggregator Interface /// @author Enzyme Council <[email protected]> interface IChainlinkAggregator { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); } // SPDX-License-Identifier: AGPL-3.0-or-later // Copyright (C) 2018 Rain <[email protected]> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pragma solidity 0.6.12; /// @title MakerDaoMath Contract /// @author Enzyme Council <[email protected]> /// @notice Helper functions for math operations adapted from MakerDao contracts abstract contract MakerDaoMath { /// @dev Performs scaled, fixed-point exponentiation. /// Verbatim code, adapted to our style guide for variable naming only, see: /// https://github.com/makerdao/dss/blob/master/src/pot.sol#L83-L105 // prettier-ignore function __rpow(uint256 _x, uint256 _n, uint256 _base) internal pure returns (uint256 z_) { assembly { switch _x case 0 {switch _n case 0 {z_ := _base} default {z_ := 0}} default { switch mod(_n, 2) case 0 { z_ := _base } default { z_ := _x } let half := div(_base, 2) for { _n := div(_n, 2) } _n { _n := div(_n,2) } { let xx := mul(_x, _x) if iszero(eq(div(xx, _x), _x)) { revert(0,0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0,0) } _x := div(xxRound, _base) if mod(_n,2) { let zx := mul(z_, _x) if and(iszero(iszero(_x)), iszero(eq(div(zx, _x), z_))) { revert(0,0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0,0) } z_ := div(zxRound, _base) } } } } return z_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../core/fund/vault/VaultLib.sol"; import "../../../utils/MakerDaoMath.sol"; import "./utils/FeeBase.sol"; /// @title ManagementFee Contract /// @author Enzyme Council <[email protected]> /// @notice A management fee with a configurable annual rate contract ManagementFee is FeeBase, MakerDaoMath { using SafeMath for uint256; event FundSettingsAdded(address indexed comptrollerProxy, uint256 scaledPerSecondRate); event Settled( address indexed comptrollerProxy, uint256 sharesQuantity, uint256 secondsSinceSettlement ); struct FeeInfo { uint256 scaledPerSecondRate; uint256 lastSettled; } uint256 private constant RATE_SCALE_BASE = 10**27; mapping(address => FeeInfo) private comptrollerProxyToFeeInfo; constructor(address _feeManager) public FeeBase(_feeManager) {} // EXTERNAL FUNCTIONS /// @notice Activates the fee for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyFeeManager { // It is only necessary to set `lastSettled` for a migrated fund if (VaultLib(_vaultProxy).totalSupply() > 0) { comptrollerProxyToFeeInfo[_comptrollerProxy].lastSettled = block.timestamp; } } /// @notice Add the initial fee settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settingsData Encoded settings to apply to the fee for a fund function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external override onlyFeeManager { uint256 scaledPerSecondRate = abi.decode(_settingsData, (uint256)); require( scaledPerSecondRate > 0, "addFundSettings: scaledPerSecondRate must be greater than 0" ); comptrollerProxyToFeeInfo[_comptrollerProxy] = FeeInfo({ scaledPerSecondRate: scaledPerSecondRate, lastSettled: 0 }); emit FundSettingsAdded(_comptrollerProxy, scaledPerSecondRate); } /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "MANAGEMENT"; } /// @notice Gets the hooks that are implemented by the fee /// @return implementedHooksForSettle_ The hooks during which settle() is implemented /// @return implementedHooksForUpdate_ The hooks during which update() is implemented /// @return usesGavOnSettle_ True if GAV is used during the settle() implementation /// @return usesGavOnUpdate_ True if GAV is used during the update() implementation /// @dev Used only during fee registration function implementedHooks() external view override returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ) { implementedHooksForSettle_ = new IFeeManager.FeeHook[](3); implementedHooksForSettle_[0] = IFeeManager.FeeHook.Continuous; implementedHooksForSettle_[1] = IFeeManager.FeeHook.BuySharesSetup; implementedHooksForSettle_[2] = IFeeManager.FeeHook.PreRedeemShares; return (implementedHooksForSettle_, new IFeeManager.FeeHook[](0), false, false); } /// @notice Settle the fee and calculate shares due /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @return settlementType_ The type of settlement /// @return (unused) The payer of shares due /// @return sharesDue_ The amount of shares due function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook, bytes calldata, uint256 ) external override onlyFeeManager returns ( IFeeManager.SettlementType settlementType_, address, uint256 sharesDue_ ) { FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; // If this fee was settled in the current block, we can return early uint256 secondsSinceSettlement = block.timestamp.sub(feeInfo.lastSettled); if (secondsSinceSettlement == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } // If there are shares issued for the fund, calculate the shares due VaultLib vaultProxyContract = VaultLib(_vaultProxy); uint256 sharesSupply = vaultProxyContract.totalSupply(); if (sharesSupply > 0) { // This assumes that all shares in the VaultProxy are shares outstanding, // which is fine for this release. Even if they are not, they are still shares that // are only claimable by the fund owner. uint256 netSharesSupply = sharesSupply.sub(vaultProxyContract.balanceOf(_vaultProxy)); if (netSharesSupply > 0) { sharesDue_ = netSharesSupply .mul( __rpow(feeInfo.scaledPerSecondRate, secondsSinceSettlement, RATE_SCALE_BASE) .sub(RATE_SCALE_BASE) ) .div(RATE_SCALE_BASE); } } // Must settle even when no shares are due, for the case that settlement is being // done when there are no shares in the fund (i.e. at the first investment, or at the // first investment after all shares have been redeemed) comptrollerProxyToFeeInfo[_comptrollerProxy].lastSettled = block.timestamp; emit Settled(_comptrollerProxy, sharesDue_, secondsSinceSettlement); if (sharesDue_ == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } return (IFeeManager.SettlementType.Mint, address(0), sharesDue_); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the feeInfo for a given fund /// @param _comptrollerProxy The ComptrollerProxy contract of the fund /// @return feeInfo_ The feeInfo function getFeeInfoForFund(address _comptrollerProxy) external view returns (FeeInfo memory feeInfo_) { return comptrollerProxyToFeeInfo[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../IFee.sol"; /// @title FeeBase Contract /// @author Enzyme Council <[email protected]> /// @notice Abstract base contract for all fees abstract contract FeeBase is IFee { address internal immutable FEE_MANAGER; modifier onlyFeeManager { require(msg.sender == FEE_MANAGER, "Only the FeeManger can make this call"); _; } constructor(address _feeManager) public { FEE_MANAGER = _feeManager; } /// @notice Allows Fee to run logic during fund activation /// @dev Unimplemented by default, may be overrode. function activateForFund(address, address) external virtual override { return; } /// @notice Runs payout logic for a fee that utilizes shares outstanding as its settlement type /// @dev Returns false by default, can be overridden by fee function payout(address, address) external virtual override returns (bool) { return false; } /// @notice Update fee state after all settlement has occurred during a given fee hook /// @dev Unimplemented by default, can be overridden by fee function update( address, address, IFeeManager.FeeHook, bytes calldata, uint256 ) external virtual override { return; } /// @notice Helper to parse settlement arguments from encoded data for PreBuyShares fee hook function __decodePreBuySharesSettlementData(bytes memory _settlementData) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 minSharesQuantity_ ) { return abi.decode(_settlementData, (address, uint256, uint256)); } /// @notice Helper to parse settlement arguments from encoded data for PreRedeemShares fee hook function __decodePreRedeemSharesSettlementData(bytes memory _settlementData) internal pure returns (address redeemer_, uint256 sharesQuantity_) { return abi.decode(_settlementData, (address, uint256)); } /// @notice Helper to parse settlement arguments from encoded data for PostBuyShares fee hook function __decodePostBuySharesSettlementData(bytes memory _settlementData) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 sharesBought_ ) { return abi.decode(_settlementData, (address, uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FEE_MANAGER` variable /// @return feeManager_ The `FEE_MANAGER` variable value function getFeeManager() external view returns (address feeManager_) { return FEE_MANAGER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./IFeeManager.sol"; /// @title Fee Interface /// @author Enzyme Council <[email protected]> /// @notice Interface for all fees interface IFee { function activateForFund(address _comptrollerProxy, address _vaultProxy) external; function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external; function identifier() external pure returns (string memory identifier_); function implementedHooks() external view returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ); function payout(address _comptrollerProxy, address _vaultProxy) external returns (bool isPayable_); function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external returns ( IFeeManager.SettlementType settlementType_, address payer_, uint256 sharesDue_ ); function update( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/math/SignedSafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../core/fund/comptroller/ComptrollerLib.sol"; import "../FeeManager.sol"; import "./utils/FeeBase.sol"; /// @title PerformanceFee Contract /// @author Enzyme Council <[email protected]> /// @notice A performance-based fee with configurable rate and crystallization period, using /// a high watermark /// @dev This contract assumes that all shares in the VaultProxy are shares outstanding, /// which is fine for this release. Even if they are not, they are still shares that /// are only claimable by the fund owner. contract PerformanceFee is FeeBase { using SafeMath for uint256; using SignedSafeMath for int256; event ActivatedForFund(address indexed comptrollerProxy, uint256 highWaterMark); event FundSettingsAdded(address indexed comptrollerProxy, uint256 rate, uint256 period); event LastSharePriceUpdated( address indexed comptrollerProxy, uint256 prevSharePrice, uint256 nextSharePrice ); event PaidOut( address indexed comptrollerProxy, uint256 prevHighWaterMark, uint256 nextHighWaterMark, uint256 aggregateValueDue ); event PerformanceUpdated( address indexed comptrollerProxy, uint256 prevAggregateValueDue, uint256 nextAggregateValueDue, int256 sharesOutstandingDiff ); struct FeeInfo { uint256 rate; uint256 period; uint256 activated; uint256 lastPaid; uint256 highWaterMark; uint256 lastSharePrice; uint256 aggregateValueDue; } uint256 private constant RATE_DIVISOR = 10**18; uint256 private constant SHARE_UNIT = 10**18; mapping(address => FeeInfo) private comptrollerProxyToFeeInfo; constructor(address _feeManager) public FeeBase(_feeManager) {} // EXTERNAL FUNCTIONS /// @notice Activates the fee for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund function activateForFund(address _comptrollerProxy, address) external override onlyFeeManager { FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; // We must not force asset finality, otherwise funds that have Synths as tracked assets // would be susceptible to a DoS attack when attempting to migrate to a release that uses // this fee: an attacker trades a negligible amount of a tracked Synth with the VaultProxy // as the recipient, thus causing `calcGrossShareValue(true)` to fail. (uint256 grossSharePrice, bool sharePriceIsValid) = ComptrollerLib(_comptrollerProxy) .calcGrossShareValue(false); require(sharePriceIsValid, "activateForFund: Invalid share price"); feeInfo.highWaterMark = grossSharePrice; feeInfo.lastSharePrice = grossSharePrice; feeInfo.activated = block.timestamp; emit ActivatedForFund(_comptrollerProxy, grossSharePrice); } /// @notice Add the initial fee settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settingsData Encoded settings to apply to the policy for the fund /// @dev `highWaterMark`, `lastSharePrice`, and `activated` are set during activation function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external override onlyFeeManager { (uint256 feeRate, uint256 feePeriod) = abi.decode(_settingsData, (uint256, uint256)); require(feeRate > 0, "addFundSettings: feeRate must be greater than 0"); require(feePeriod > 0, "addFundSettings: feePeriod must be greater than 0"); comptrollerProxyToFeeInfo[_comptrollerProxy] = FeeInfo({ rate: feeRate, period: feePeriod, activated: 0, lastPaid: 0, highWaterMark: 0, lastSharePrice: 0, aggregateValueDue: 0 }); emit FundSettingsAdded(_comptrollerProxy, feeRate, feePeriod); } /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "PERFORMANCE"; } /// @notice Gets the hooks that are implemented by the fee /// @return implementedHooksForSettle_ The hooks during which settle() is implemented /// @return implementedHooksForUpdate_ The hooks during which update() is implemented /// @return usesGavOnSettle_ True if GAV is used during the settle() implementation /// @return usesGavOnUpdate_ True if GAV is used during the update() implementation /// @dev Used only during fee registration function implementedHooks() external view override returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ) { implementedHooksForSettle_ = new IFeeManager.FeeHook[](3); implementedHooksForSettle_[0] = IFeeManager.FeeHook.Continuous; implementedHooksForSettle_[1] = IFeeManager.FeeHook.BuySharesSetup; implementedHooksForSettle_[2] = IFeeManager.FeeHook.PreRedeemShares; implementedHooksForUpdate_ = new IFeeManager.FeeHook[](3); implementedHooksForUpdate_[0] = IFeeManager.FeeHook.Continuous; implementedHooksForUpdate_[1] = IFeeManager.FeeHook.BuySharesCompleted; implementedHooksForUpdate_[2] = IFeeManager.FeeHook.PreRedeemShares; return (implementedHooksForSettle_, implementedHooksForUpdate_, true, true); } /// @notice Checks whether the shares outstanding for the fee can be paid out, and updates /// the info for the fee's last payout /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return isPayable_ True if shares outstanding can be paid out function payout(address _comptrollerProxy, address) external override onlyFeeManager returns (bool isPayable_) { if (!payoutAllowed(_comptrollerProxy)) { return false; } FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; feeInfo.lastPaid = block.timestamp; uint256 prevHighWaterMark = feeInfo.highWaterMark; uint256 nextHighWaterMark = __calcUint256Max(feeInfo.lastSharePrice, prevHighWaterMark); uint256 prevAggregateValueDue = feeInfo.aggregateValueDue; // Update state as necessary if (prevAggregateValueDue > 0) { feeInfo.aggregateValueDue = 0; } if (nextHighWaterMark > prevHighWaterMark) { feeInfo.highWaterMark = nextHighWaterMark; } emit PaidOut( _comptrollerProxy, prevHighWaterMark, nextHighWaterMark, prevAggregateValueDue ); return true; } /// @notice Settles the fee and calculates shares due /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @param _gav The GAV of the fund /// @return settlementType_ The type of settlement /// @return (unused) The payer of shares due /// @return sharesDue_ The amount of shares due function settle( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook, bytes calldata, uint256 _gav ) external override onlyFeeManager returns ( IFeeManager.SettlementType settlementType_, address, uint256 sharesDue_ ) { if (_gav == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } int256 settlementSharesDue = __settleAndUpdatePerformance( _comptrollerProxy, _vaultProxy, _gav ); if (settlementSharesDue == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } else if (settlementSharesDue > 0) { // Settle by minting shares outstanding for custody return ( IFeeManager.SettlementType.MintSharesOutstanding, address(0), uint256(settlementSharesDue) ); } else { // Settle by burning from shares outstanding return ( IFeeManager.SettlementType.BurnSharesOutstanding, address(0), uint256(-settlementSharesDue) ); } } /// @notice Updates the fee state after all fees have finished settle() /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _vaultProxy The VaultProxy of the fund /// @param _hook The FeeHook being executed /// @param _settlementData Encoded args to use in calculating the settlement /// @param _gav The GAV of the fund function update( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external override onlyFeeManager { uint256 prevSharePrice = comptrollerProxyToFeeInfo[_comptrollerProxy].lastSharePrice; uint256 nextSharePrice = __calcNextSharePrice( _comptrollerProxy, _vaultProxy, _hook, _settlementData, _gav ); if (nextSharePrice == prevSharePrice) { return; } comptrollerProxyToFeeInfo[_comptrollerProxy].lastSharePrice = nextSharePrice; emit LastSharePriceUpdated(_comptrollerProxy, prevSharePrice, nextSharePrice); } // PUBLIC FUNCTIONS /// @notice Checks whether the shares outstanding can be paid out /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return payoutAllowed_ True if the fee payment is due /// @dev Payout is allowed if fees have not yet been settled in a crystallization period, /// and at least 1 crystallization period has passed since activation function payoutAllowed(address _comptrollerProxy) public view returns (bool payoutAllowed_) { FeeInfo memory feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; uint256 period = feeInfo.period; uint256 timeSinceActivated = block.timestamp.sub(feeInfo.activated); // Check if at least 1 crystallization period has passed since activation if (timeSinceActivated < period) { return false; } // Check that a full crystallization period has passed since the last payout uint256 timeSincePeriodStart = timeSinceActivated % period; uint256 periodStart = block.timestamp.sub(timeSincePeriodStart); return feeInfo.lastPaid < periodStart; } // PRIVATE FUNCTIONS /// @dev Helper to calculate the aggregated value accumulated to a fund since the last /// settlement (happening at investment/redemption) /// Validated: /// _netSharesSupply > 0 /// _sharePriceWithoutPerformance != _prevSharePrice function __calcAggregateValueDue( uint256 _netSharesSupply, uint256 _sharePriceWithoutPerformance, uint256 _prevSharePrice, uint256 _prevAggregateValueDue, uint256 _feeRate, uint256 _highWaterMark ) private pure returns (uint256) { int256 superHWMValueSinceLastSettled = ( int256(__calcUint256Max(_highWaterMark, _sharePriceWithoutPerformance)).sub( int256(__calcUint256Max(_highWaterMark, _prevSharePrice)) ) ) .mul(int256(_netSharesSupply)) .div(int256(SHARE_UNIT)); int256 valueDueSinceLastSettled = superHWMValueSinceLastSettled.mul(int256(_feeRate)).div( int256(RATE_DIVISOR) ); return uint256( __calcInt256Max(0, int256(_prevAggregateValueDue).add(valueDueSinceLastSettled)) ); } /// @dev Helper to calculate the max of two int values function __calcInt256Max(int256 _a, int256 _b) private pure returns (int256) { if (_a >= _b) { return _a; } return _b; } /// @dev Helper to calculate the next `lastSharePrice` value function __calcNextSharePrice( address _comptrollerProxy, address _vaultProxy, IFeeManager.FeeHook _hook, bytes memory _settlementData, uint256 _gav ) private view returns (uint256 nextSharePrice_) { uint256 denominationAssetUnit = 10 ** uint256(ERC20(ComptrollerLib(_comptrollerProxy).getDenominationAsset()).decimals()); if (_gav == 0) { return denominationAssetUnit; } // Get shares outstanding via VaultProxy balance and calc shares supply to get net shares supply ERC20 vaultProxyContract = ERC20(_vaultProxy); uint256 totalSharesSupply = vaultProxyContract.totalSupply(); uint256 nextNetSharesSupply = totalSharesSupply.sub( vaultProxyContract.balanceOf(_vaultProxy) ); if (nextNetSharesSupply == 0) { return denominationAssetUnit; } uint256 nextGav = _gav; // For both Continuous and BuySharesCompleted hooks, _gav and shares supply will not change, // we only need additional calculations for PreRedeemShares if (_hook == IFeeManager.FeeHook.PreRedeemShares) { (, uint256 sharesDecrease) = __decodePreRedeemSharesSettlementData(_settlementData); // Shares have not yet been burned nextNetSharesSupply = nextNetSharesSupply.sub(sharesDecrease); if (nextNetSharesSupply == 0) { return denominationAssetUnit; } // Assets have not yet been withdrawn uint256 gavDecrease = sharesDecrease .mul(_gav) .mul(SHARE_UNIT) .div(totalSharesSupply) .div(denominationAssetUnit); nextGav = nextGav.sub(gavDecrease); if (nextGav == 0) { return denominationAssetUnit; } } return nextGav.mul(SHARE_UNIT).div(nextNetSharesSupply); } /// @dev Helper to calculate the performance metrics for a fund. /// Validated: /// _totalSharesSupply > 0 /// _gav > 0 /// _totalSharesSupply != _totalSharesOutstanding function __calcPerformance( address _comptrollerProxy, uint256 _totalSharesSupply, uint256 _totalSharesOutstanding, uint256 _prevAggregateValueDue, FeeInfo memory feeInfo, uint256 _gav ) private view returns (uint256 nextAggregateValueDue_, int256 sharesDue_) { // Use the 'shares supply net shares outstanding' for performance calcs. // Cannot be 0, as _totalSharesSupply != _totalSharesOutstanding uint256 netSharesSupply = _totalSharesSupply.sub(_totalSharesOutstanding); uint256 sharePriceWithoutPerformance = _gav.mul(SHARE_UNIT).div(netSharesSupply); // If gross share price has not changed, can exit early uint256 prevSharePrice = feeInfo.lastSharePrice; if (sharePriceWithoutPerformance == prevSharePrice) { return (_prevAggregateValueDue, 0); } nextAggregateValueDue_ = __calcAggregateValueDue( netSharesSupply, sharePriceWithoutPerformance, prevSharePrice, _prevAggregateValueDue, feeInfo.rate, feeInfo.highWaterMark ); sharesDue_ = __calcSharesDue( _comptrollerProxy, netSharesSupply, _gav, nextAggregateValueDue_ ); return (nextAggregateValueDue_, sharesDue_); } /// @dev Helper to calculate sharesDue during settlement. /// Validated: /// _netSharesSupply > 0 /// _gav > 0 function __calcSharesDue( address _comptrollerProxy, uint256 _netSharesSupply, uint256 _gav, uint256 _nextAggregateValueDue ) private view returns (int256 sharesDue_) { // If _nextAggregateValueDue > _gav, then no shares can be created. // This is a known limitation of the model, which is only reached for unrealistically // high performance fee rates (> 100%). A revert is allowed in such a case. uint256 sharesDueForAggregateValueDue = _nextAggregateValueDue.mul(_netSharesSupply).div( _gav.sub(_nextAggregateValueDue) ); // Shares due is the +/- diff or the total shares outstanding already minted return int256(sharesDueForAggregateValueDue).sub( int256( FeeManager(FEE_MANAGER).getFeeSharesOutstandingForFund( _comptrollerProxy, address(this) ) ) ); } /// @dev Helper to calculate the max of two uint values function __calcUint256Max(uint256 _a, uint256 _b) private pure returns (uint256) { if (_a >= _b) { return _a; } return _b; } /// @dev Helper to settle the fee and update performance state. /// Validated: /// _gav > 0 function __settleAndUpdatePerformance( address _comptrollerProxy, address _vaultProxy, uint256 _gav ) private returns (int256 sharesDue_) { ERC20 sharesTokenContract = ERC20(_vaultProxy); uint256 totalSharesSupply = sharesTokenContract.totalSupply(); if (totalSharesSupply == 0) { return 0; } uint256 totalSharesOutstanding = sharesTokenContract.balanceOf(_vaultProxy); if (totalSharesOutstanding == totalSharesSupply) { return 0; } FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy]; uint256 prevAggregateValueDue = feeInfo.aggregateValueDue; uint256 nextAggregateValueDue; (nextAggregateValueDue, sharesDue_) = __calcPerformance( _comptrollerProxy, totalSharesSupply, totalSharesOutstanding, prevAggregateValueDue, feeInfo, _gav ); if (nextAggregateValueDue == prevAggregateValueDue) { return 0; } // Update fee state feeInfo.aggregateValueDue = nextAggregateValueDue; emit PerformanceUpdated( _comptrollerProxy, prevAggregateValueDue, nextAggregateValueDue, sharesDue_ ); return sharesDue_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the feeInfo for a given fund /// @param _comptrollerProxy The ComptrollerProxy contract of the fund /// @return feeInfo_ The feeInfo function getFeeInfoForFund(address _comptrollerProxy) external view returns (FeeInfo memory feeInfo_) { return comptrollerProxyToFeeInfo[_comptrollerProxy]; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../../core/fund/comptroller/IComptroller.sol"; import "../../core/fund/vault/IVault.sol"; import "../../utils/AddressArrayLib.sol"; import "../utils/ExtensionBase.sol"; import "../utils/FundDeployerOwnerMixin.sol"; import "../utils/PermissionedVaultActionMixin.sol"; import "./IFee.sol"; import "./IFeeManager.sol"; /// @title FeeManager Contract /// @author Enzyme Council <[email protected]> /// @notice Manages fees for funds contract FeeManager is IFeeManager, ExtensionBase, FundDeployerOwnerMixin, PermissionedVaultActionMixin { using AddressArrayLib for address[]; using EnumerableSet for EnumerableSet.AddressSet; using SafeMath for uint256; event AllSharesOutstandingForcePaidForFund( address indexed comptrollerProxy, address payee, uint256 sharesDue ); event FeeDeregistered(address indexed fee, string indexed identifier); event FeeEnabledForFund( address indexed comptrollerProxy, address indexed fee, bytes settingsData ); event FeeRegistered( address indexed fee, string indexed identifier, FeeHook[] implementedHooksForSettle, FeeHook[] implementedHooksForUpdate, bool usesGavOnSettle, bool usesGavOnUpdate ); event FeeSettledForFund( address indexed comptrollerProxy, address indexed fee, SettlementType indexed settlementType, address payer, address payee, uint256 sharesDue ); event SharesOutstandingPaidForFund( address indexed comptrollerProxy, address indexed fee, uint256 sharesDue ); event FeesRecipientSetForFund( address indexed comptrollerProxy, address prevFeesRecipient, address nextFeesRecipient ); EnumerableSet.AddressSet private registeredFees; mapping(address => bool) private feeToUsesGavOnSettle; mapping(address => bool) private feeToUsesGavOnUpdate; mapping(address => mapping(FeeHook => bool)) private feeToHookToImplementsSettle; mapping(address => mapping(FeeHook => bool)) private feeToHookToImplementsUpdate; mapping(address => address[]) private comptrollerProxyToFees; mapping(address => mapping(address => uint256)) private comptrollerProxyToFeeToSharesOutstanding; constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {} // EXTERNAL FUNCTIONS /// @notice Activate already-configured fees for use in the calling fund function activateForFund(bool) external override { address vaultProxy = __setValidatedVaultProxy(msg.sender); address[] memory enabledFees = comptrollerProxyToFees[msg.sender]; for (uint256 i; i < enabledFees.length; i++) { IFee(enabledFees[i]).activateForFund(msg.sender, vaultProxy); } } /// @notice Deactivate fees for a fund /// @dev msg.sender is validated during __invokeHook() function deactivateForFund() external override { // Settle continuous fees one last time, but without calling Fee.update() __invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, false); // Force payout of remaining shares outstanding __forcePayoutAllSharesOutstanding(msg.sender); // Clean up storage __deleteFundStorage(msg.sender); } /// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy /// @param _actionId An ID representing the desired action /// @param _callArgs Encoded arguments specific to the _actionId /// @dev This is the only way to call a function on this contract that updates VaultProxy state. /// For both of these actions, any caller is allowed, so we don't use the caller param. function receiveCallFromComptroller( address, uint256 _actionId, bytes calldata _callArgs ) external override { if (_actionId == 0) { // Settle and update all continuous fees __invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, true); } else if (_actionId == 1) { __payoutSharesOutstandingForFees(msg.sender, _callArgs); } else { revert("receiveCallFromComptroller: Invalid _actionId"); } } /// @notice Enable and configure fees for use in the calling fund /// @param _configData Encoded config data /// @dev Caller is expected to be a valid ComptrollerProxy, but there isn't a need to validate. /// The order of `fees` determines the order in which fees of the same FeeHook will be applied. /// It is recommended to run ManagementFee before PerformanceFee in order to achieve precise /// PerformanceFee calcs. function setConfigForFund(bytes calldata _configData) external override { (address[] memory fees, bytes[] memory settingsData) = abi.decode( _configData, (address[], bytes[]) ); // Sanity checks require( fees.length == settingsData.length, "setConfigForFund: fees and settingsData array lengths unequal" ); require(fees.isUniqueSet(), "setConfigForFund: fees cannot include duplicates"); // Enable each fee with settings for (uint256 i; i < fees.length; i++) { require(isRegisteredFee(fees[i]), "setConfigForFund: Fee is not registered"); // Set fund config on fee IFee(fees[i]).addFundSettings(msg.sender, settingsData[i]); // Enable fee for fund comptrollerProxyToFees[msg.sender].push(fees[i]); emit FeeEnabledForFund(msg.sender, fees[i], settingsData[i]); } } /// @notice Allows all fees for a particular FeeHook to implement settle() and update() logic /// @param _hook The FeeHook to invoke /// @param _settlementData The encoded settlement parameters specific to the FeeHook /// @param _gav The GAV for a fund if known in the invocating code, otherwise 0 function invokeHook( FeeHook _hook, bytes calldata _settlementData, uint256 _gav ) external override { __invokeHook(msg.sender, _hook, _settlementData, _gav, true); } // PRIVATE FUNCTIONS /// @dev Helper to destroy local storage to get gas refund, /// and to prevent further calls to fee manager function __deleteFundStorage(address _comptrollerProxy) private { delete comptrollerProxyToFees[_comptrollerProxy]; delete comptrollerProxyToVaultProxy[_comptrollerProxy]; } /// @dev Helper to force the payout of shares outstanding across all fees. /// For the current release, all shares in the VaultProxy are assumed to be /// shares outstanding from fees. If not, then they were sent there by mistake /// and are otherwise unrecoverable. We can therefore take the VaultProxy's /// shares balance as the totalSharesOutstanding to payout to the fund owner. function __forcePayoutAllSharesOutstanding(address _comptrollerProxy) private { address vaultProxy = getVaultProxyForFund(_comptrollerProxy); uint256 totalSharesOutstanding = ERC20(vaultProxy).balanceOf(vaultProxy); if (totalSharesOutstanding == 0) { return; } // Destroy any shares outstanding storage address[] memory fees = comptrollerProxyToFees[_comptrollerProxy]; for (uint256 i; i < fees.length; i++) { delete comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]]; } // Distribute all shares outstanding to the fees recipient address payee = IVault(vaultProxy).getOwner(); __transferShares(_comptrollerProxy, vaultProxy, payee, totalSharesOutstanding); emit AllSharesOutstandingForcePaidForFund( _comptrollerProxy, payee, totalSharesOutstanding ); } /// @dev Helper to get the canonical value of GAV if not yet set and required by fee function __getGavAsNecessary( address _comptrollerProxy, address _fee, uint256 _gavOrZero ) private returns (uint256 gav_) { if (_gavOrZero == 0 && feeUsesGavOnUpdate(_fee)) { // Assumes that any fee that requires GAV would need to revert if invalid or not final bool gavIsValid; (gav_, gavIsValid) = IComptroller(_comptrollerProxy).calcGav(true); require(gavIsValid, "__getGavAsNecessary: Invalid GAV"); } else { gav_ = _gavOrZero; } return gav_; } /// @dev Helper to run settle() on all enabled fees for a fund that implement a given hook, and then to /// optionally run update() on the same fees. This order allows fees an opportunity to update /// their local state after all VaultProxy state transitions (i.e., minting, burning, /// transferring shares) have finished. To optimize for the expensive operation of calculating /// GAV, once one fee requires GAV, we recycle that `gav` value for subsequent fees. /// Assumes that _gav is either 0 or has already been validated. function __invokeHook( address _comptrollerProxy, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero, bool _updateFees ) private { address[] memory fees = comptrollerProxyToFees[_comptrollerProxy]; if (fees.length == 0) { return; } address vaultProxy = getVaultProxyForFund(_comptrollerProxy); // This check isn't strictly necessary, but its cost is insignificant, // and helps to preserve data integrity. require(vaultProxy != address(0), "__invokeHook: Fund is not active"); // First, allow all fees to implement settle() uint256 gav = __settleFees( _comptrollerProxy, vaultProxy, fees, _hook, _settlementData, _gavOrZero ); // Second, allow fees to implement update() // This function does not allow any further altering of VaultProxy state // (i.e., burning, minting, or transferring shares) if (_updateFees) { __updateFees(_comptrollerProxy, vaultProxy, fees, _hook, _settlementData, gav); } } /// @dev Helper to payout the shares outstanding for the specified fees. /// Does not call settle() on fees. /// Only callable via ComptrollerProxy.callOnExtension(). function __payoutSharesOutstandingForFees(address _comptrollerProxy, bytes memory _callArgs) private { address[] memory fees = abi.decode(_callArgs, (address[])); address vaultProxy = getVaultProxyForFund(msg.sender); uint256 sharesOutstandingDue; for (uint256 i; i < fees.length; i++) { if (!IFee(fees[i]).payout(_comptrollerProxy, vaultProxy)) { continue; } uint256 sharesOutstandingForFee = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]]; if (sharesOutstandingForFee == 0) { continue; } sharesOutstandingDue = sharesOutstandingDue.add(sharesOutstandingForFee); // Delete shares outstanding and distribute from VaultProxy to the fees recipient comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]] = 0; emit SharesOutstandingPaidForFund(_comptrollerProxy, fees[i], sharesOutstandingForFee); } if (sharesOutstandingDue > 0) { __transferShares( _comptrollerProxy, vaultProxy, IVault(vaultProxy).getOwner(), sharesOutstandingDue ); } } /// @dev Helper to settle a fee function __settleFee( address _comptrollerProxy, address _vaultProxy, address _fee, FeeHook _hook, bytes memory _settlementData, uint256 _gav ) private { (SettlementType settlementType, address payer, uint256 sharesDue) = IFee(_fee).settle( _comptrollerProxy, _vaultProxy, _hook, _settlementData, _gav ); if (settlementType == SettlementType.None) { return; } address payee; if (settlementType == SettlementType.Direct) { payee = IVault(_vaultProxy).getOwner(); __transferShares(_comptrollerProxy, payer, payee, sharesDue); } else if (settlementType == SettlementType.Mint) { payee = IVault(_vaultProxy).getOwner(); __mintShares(_comptrollerProxy, payee, sharesDue); } else if (settlementType == SettlementType.Burn) { __burnShares(_comptrollerProxy, payer, sharesDue); } else if (settlementType == SettlementType.MintSharesOutstanding) { comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] .add(sharesDue); payee = _vaultProxy; __mintShares(_comptrollerProxy, payee, sharesDue); } else if (settlementType == SettlementType.BurnSharesOutstanding) { comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] .sub(sharesDue); payer = _vaultProxy; __burnShares(_comptrollerProxy, payer, sharesDue); } else { revert("__settleFee: Invalid SettlementType"); } emit FeeSettledForFund(_comptrollerProxy, _fee, settlementType, payer, payee, sharesDue); } /// @dev Helper to settle fees that implement a given fee hook function __settleFees( address _comptrollerProxy, address _vaultProxy, address[] memory _fees, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero ) private returns (uint256 gav_) { gav_ = _gavOrZero; for (uint256 i; i < _fees.length; i++) { if (!feeSettlesOnHook(_fees[i], _hook)) { continue; } gav_ = __getGavAsNecessary(_comptrollerProxy, _fees[i], gav_); __settleFee(_comptrollerProxy, _vaultProxy, _fees[i], _hook, _settlementData, gav_); } return gav_; } /// @dev Helper to update fees that implement a given fee hook function __updateFees( address _comptrollerProxy, address _vaultProxy, address[] memory _fees, FeeHook _hook, bytes memory _settlementData, uint256 _gavOrZero ) private { uint256 gav = _gavOrZero; for (uint256 i; i < _fees.length; i++) { if (!feeUpdatesOnHook(_fees[i], _hook)) { continue; } gav = __getGavAsNecessary(_comptrollerProxy, _fees[i], gav); IFee(_fees[i]).update(_comptrollerProxy, _vaultProxy, _hook, _settlementData, gav); } } /////////////////// // FEES REGISTRY // /////////////////// /// @notice Remove fees from the list of registered fees /// @param _fees Addresses of fees to be deregistered function deregisterFees(address[] calldata _fees) external onlyFundDeployerOwner { require(_fees.length > 0, "deregisterFees: _fees cannot be empty"); for (uint256 i; i < _fees.length; i++) { require(isRegisteredFee(_fees[i]), "deregisterFees: fee is not registered"); registeredFees.remove(_fees[i]); emit FeeDeregistered(_fees[i], IFee(_fees[i]).identifier()); } } /// @notice Add fees to the list of registered fees /// @param _fees Addresses of fees to be registered /// @dev Stores the hooks that a fee implements and whether each implementation uses GAV, /// which fronts the gas for calls to check if a hook is implemented, and guarantees /// that these hook implementation return values do not change post-registration. function registerFees(address[] calldata _fees) external onlyFundDeployerOwner { require(_fees.length > 0, "registerFees: _fees cannot be empty"); for (uint256 i; i < _fees.length; i++) { require(!isRegisteredFee(_fees[i]), "registerFees: fee already registered"); registeredFees.add(_fees[i]); IFee feeContract = IFee(_fees[i]); ( FeeHook[] memory implementedHooksForSettle, FeeHook[] memory implementedHooksForUpdate, bool usesGavOnSettle, bool usesGavOnUpdate ) = feeContract.implementedHooks(); // Stores the hooks for which each fee implements settle() and update() for (uint256 j; j < implementedHooksForSettle.length; j++) { feeToHookToImplementsSettle[_fees[i]][implementedHooksForSettle[j]] = true; } for (uint256 j; j < implementedHooksForUpdate.length; j++) { feeToHookToImplementsUpdate[_fees[i]][implementedHooksForUpdate[j]] = true; } // Stores whether each fee requires GAV during its implementations for settle() and update() if (usesGavOnSettle) { feeToUsesGavOnSettle[_fees[i]] = true; } if (usesGavOnUpdate) { feeToUsesGavOnUpdate[_fees[i]] = true; } emit FeeRegistered( _fees[i], feeContract.identifier(), implementedHooksForSettle, implementedHooksForUpdate, usesGavOnSettle, usesGavOnUpdate ); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Get a list of enabled fees for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return enabledFees_ An array of enabled fee addresses function getEnabledFeesForFund(address _comptrollerProxy) external view returns (address[] memory enabledFees_) { return comptrollerProxyToFees[_comptrollerProxy]; } /// @notice Get the amount of shares outstanding for a particular fee for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _fee The fee address /// @return sharesOutstanding_ The amount of shares outstanding function getFeeSharesOutstandingForFund(address _comptrollerProxy, address _fee) external view returns (uint256 sharesOutstanding_) { return comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee]; } /// @notice Get all registered fees /// @return registeredFees_ A list of all registered fee addresses function getRegisteredFees() external view returns (address[] memory registeredFees_) { registeredFees_ = new address[](registeredFees.length()); for (uint256 i; i < registeredFees_.length; i++) { registeredFees_[i] = registeredFees.at(i); } return registeredFees_; } /// @notice Checks if a fee implements settle() on a particular hook /// @param _fee The address of the fee to check /// @param _hook The FeeHook to check /// @return settlesOnHook_ True if the fee settles on the given hook function feeSettlesOnHook(address _fee, FeeHook _hook) public view returns (bool settlesOnHook_) { return feeToHookToImplementsSettle[_fee][_hook]; } /// @notice Checks if a fee implements update() on a particular hook /// @param _fee The address of the fee to check /// @param _hook The FeeHook to check /// @return updatesOnHook_ True if the fee updates on the given hook function feeUpdatesOnHook(address _fee, FeeHook _hook) public view returns (bool updatesOnHook_) { return feeToHookToImplementsUpdate[_fee][_hook]; } /// @notice Checks if a fee uses GAV in its settle() implementation /// @param _fee The address of the fee to check /// @return usesGav_ True if the fee uses GAV during settle() implementation function feeUsesGavOnSettle(address _fee) public view returns (bool usesGav_) { return feeToUsesGavOnSettle[_fee]; } /// @notice Checks if a fee uses GAV in its update() implementation /// @param _fee The address of the fee to check /// @return usesGav_ True if the fee uses GAV during update() implementation function feeUsesGavOnUpdate(address _fee) public view returns (bool usesGav_) { return feeToUsesGavOnUpdate[_fee]; } /// @notice Check whether a fee is registered /// @param _fee The address of the fee to check /// @return isRegisteredFee_ True if the fee is registered function isRegisteredFee(address _fee) public view returns (bool isRegisteredFee_) { return registeredFees.contains(_fee); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund/comptroller/IComptroller.sol"; /// @title PermissionedVaultActionMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for extensions that can make permissioned vault calls abstract contract PermissionedVaultActionMixin { /// @notice Adds a tracked asset to the fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to add function __addTrackedAsset(address _comptrollerProxy, address _asset) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.AddTrackedAsset, abi.encode(_asset) ); } /// @notice Grants an allowance to a spender to use a fund's asset /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset for which to grant an allowance /// @param _target The spender of the allowance /// @param _amount The amount of the allowance function __approveAssetSpender( address _comptrollerProxy, address _asset, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.ApproveAssetSpender, abi.encode(_asset, _target, _amount) ); } /// @notice Burns fund shares for a particular account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _target The account for which to burn shares /// @param _amount The amount of shares to burn function __burnShares( address _comptrollerProxy, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.BurnShares, abi.encode(_target, _amount) ); } /// @notice Mints fund shares to a particular account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _target The account to which to mint shares /// @param _amount The amount of shares to mint function __mintShares( address _comptrollerProxy, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.MintShares, abi.encode(_target, _amount) ); } /// @notice Removes a tracked asset from the fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to remove function __removeTrackedAsset(address _comptrollerProxy, address _asset) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.RemoveTrackedAsset, abi.encode(_asset) ); } /// @notice Transfers fund shares from one account to another /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _from The account from which to transfer shares /// @param _to The account to which to transfer shares /// @param _amount The amount of shares to transfer function __transferShares( address _comptrollerProxy, address _from, address _to, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.TransferShares, abi.encode(_from, _to, _amount) ); } /// @notice Withdraws an asset from the VaultProxy to a given account /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _asset The asset to withdraw /// @param _target The account to which to withdraw the asset /// @param _amount The amount of asset to withdraw function __withdrawAssetTo( address _comptrollerProxy, address _asset, address _target, uint256 _amount ) internal { IComptroller(_comptrollerProxy).permissionedVaultAction( IComptroller.VaultAction.WithdrawAssetTo, abi.encode(_asset, _target, _amount) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/IWETH.sol"; import "../core/fund/comptroller/ComptrollerLib.sol"; import "../extensions/fee-manager/FeeManager.sol"; /// @title FundActionsWrapper Contract /// @author Enzyme Council <[email protected]> /// @notice Logic related to wrapping fund actions, not necessary in the core protocol contract FundActionsWrapper { using SafeERC20 for ERC20; address private immutable FEE_MANAGER; address private immutable WETH_TOKEN; mapping(address => bool) private accountToHasMaxWethAllowance; constructor(address _feeManager, address _weth) public { FEE_MANAGER = _feeManager; WETH_TOKEN = _weth; } /// @dev Needed in case WETH not fully used during exchangeAndBuyShares, /// to unwrap into ETH and refund receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Calculates the net value of 1 unit of shares in the fund's denomination asset /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return netShareValue_ The amount of the denomination asset per share /// @return isValid_ True if the conversion rates to derive the value are all valid /// @dev Accounts for fees outstanding. This is a convenience function for external consumption /// that can be used to determine the cost of purchasing shares at any given point in time. /// It essentially just bundles settling all fees that implement the Continuous hook and then /// looking up the gross share value. function calcNetShareValueForFund(address _comptrollerProxy) external returns (uint256 netShareValue_, bool isValid_) { ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); comptrollerProxyContract.callOnExtension(FEE_MANAGER, 0, ""); return comptrollerProxyContract.calcGrossShareValue(false); } /// @notice Exchanges ETH into a fund's denomination asset and then buys shares /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _buyer The account for which to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy with the sent ETH /// @param _exchange The exchange on which to execute the swap to the denomination asset /// @param _exchangeApproveTarget The address that should be given an allowance of WETH /// for the given _exchange /// @param _exchangeData The data with which to call the exchange to execute the swap /// to the denomination asset /// @param _minInvestmentAmount The minimum amount of the denomination asset /// to receive in the trade for investment (not necessary for WETH) /// @return sharesReceivedAmount_ The actual amount of shares received /// @dev Use a reasonable _minInvestmentAmount always, in case the exchange /// does not perform as expected (low incoming asset amount, blend of assets, etc). /// If the fund's denomination asset is WETH, _exchange, _exchangeApproveTarget, _exchangeData, /// and _minInvestmentAmount will be ignored. function exchangeAndBuyShares( address _comptrollerProxy, address _denominationAsset, address _buyer, uint256 _minSharesQuantity, address _exchange, address _exchangeApproveTarget, bytes calldata _exchangeData, uint256 _minInvestmentAmount ) external payable returns (uint256 sharesReceivedAmount_) { // Wrap ETH into WETH IWETH(payable(WETH_TOKEN)).deposit{value: msg.value}(); // If denominationAsset is WETH, can just buy shares directly if (_denominationAsset == WETH_TOKEN) { __approveMaxWethAsNeeded(_comptrollerProxy); return __buyShares(_comptrollerProxy, _buyer, msg.value, _minSharesQuantity); } // Exchange ETH to the fund's denomination asset __approveMaxWethAsNeeded(_exchangeApproveTarget); (bool success, bytes memory returnData) = _exchange.call(_exchangeData); require(success, string(returnData)); // Confirm the amount received in the exchange is above the min acceptable amount uint256 investmentAmount = ERC20(_denominationAsset).balanceOf(address(this)); require( investmentAmount >= _minInvestmentAmount, "exchangeAndBuyShares: _minInvestmentAmount not met" ); // Give the ComptrollerProxy max allowance for its denomination asset as necessary __approveMaxAsNeeded(_denominationAsset, _comptrollerProxy, investmentAmount); // Buy fund shares sharesReceivedAmount_ = __buyShares( _comptrollerProxy, _buyer, investmentAmount, _minSharesQuantity ); // Unwrap and refund any remaining WETH not used in the exchange uint256 remainingWeth = ERC20(WETH_TOKEN).balanceOf(address(this)); if (remainingWeth > 0) { IWETH(payable(WETH_TOKEN)).withdraw(remainingWeth); (success, returnData) = msg.sender.call{value: remainingWeth}(""); require(success, string(returnData)); } return sharesReceivedAmount_; } /// @notice Invokes the Continuous fee hook on all specified fees, and then attempts to payout /// any shares outstanding on those fees /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _fees The fees for which to run these actions /// @dev This is just a wrapper to execute two callOnExtension() actions atomically, in sequence. /// The caller must pass in the fees that they want to run this logic on. function invokeContinuousFeeHookAndPayoutSharesOutstandingForFund( address _comptrollerProxy, address[] calldata _fees ) external { ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); comptrollerProxyContract.callOnExtension(FEE_MANAGER, 0, ""); comptrollerProxyContract.callOnExtension(FEE_MANAGER, 1, abi.encode(_fees)); } // PUBLIC FUNCTIONS /// @notice Gets all fees that implement the `Continuous` fee hook for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return continuousFees_ The fees that implement the `Continuous` fee hook function getContinuousFeesForFund(address _comptrollerProxy) public view returns (address[] memory continuousFees_) { FeeManager feeManagerContract = FeeManager(FEE_MANAGER); address[] memory fees = feeManagerContract.getEnabledFeesForFund(_comptrollerProxy); // Count the continuous fees uint256 continuousFeesCount; bool[] memory implementsContinuousHook = new bool[](fees.length); for (uint256 i; i < fees.length; i++) { if (feeManagerContract.feeSettlesOnHook(fees[i], IFeeManager.FeeHook.Continuous)) { continuousFeesCount++; implementsContinuousHook[i] = true; } } // Return early if no continuous fees if (continuousFeesCount == 0) { return new address[](0); } // Create continuous fees array continuousFees_ = new address[](continuousFeesCount); uint256 continuousFeesIndex; for (uint256 i; i < fees.length; i++) { if (implementsContinuousHook[i]) { continuousFees_[continuousFeesIndex] = fees[i]; continuousFeesIndex++; } } return continuousFees_; } // PRIVATE FUNCTIONS /// @dev Helper to approve a target with the max amount of an asset, only when necessary function __approveMaxAsNeeded( address _asset, address _target, uint256 _neededAmount ) internal { if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) { ERC20(_asset).safeApprove(_target, type(uint256).max); } } /// @dev Helper to approve a target with the max amount of weth, only when necessary. /// Since WETH does not decrease the allowance if it uint256(-1), only ever need to do this /// once per target. function __approveMaxWethAsNeeded(address _target) internal { if (!accountHasMaxWethAllowance(_target)) { ERC20(WETH_TOKEN).safeApprove(_target, type(uint256).max); accountToHasMaxWethAllowance[_target] = true; } } /// @dev Helper for buying shares function __buyShares( address _comptrollerProxy, address _buyer, uint256 _investmentAmount, uint256 _minSharesQuantity ) private returns (uint256 sharesReceivedAmount_) { address[] memory buyers = new address[](1); buyers[0] = _buyer; uint256[] memory investmentAmounts = new uint256[](1); investmentAmounts[0] = _investmentAmount; uint256[] memory minSharesQuantities = new uint256[](1); minSharesQuantities[0] = _minSharesQuantity; return ComptrollerLib(_comptrollerProxy).buyShares( buyers, investmentAmounts, minSharesQuantities )[0]; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FEE_MANAGER` variable /// @return feeManager_ The `FEE_MANAGER` variable value function getFeeManager() external view returns (address feeManager_) { return FEE_MANAGER; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } /// @notice Checks whether an account has the max allowance for WETH /// @param _who The account to check /// @return hasMaxWethAllowance_ True if the account has the max allowance function accountHasMaxWethAllowance(address _who) public view returns (bool hasMaxWethAllowance_) { return accountToHasMaxWethAllowance[_who]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title WETH Interface /// @author Enzyme Council <[email protected]> interface IWETH { function deposit() external payable; function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../core/fund/comptroller/ComptrollerLib.sol"; import "../../core/fund/vault/VaultLib.sol"; import "./IAuthUserExecutedSharesRequestor.sol"; /// @title AuthUserExecutedSharesRequestorLib Contract /// @author Enzyme Council <[email protected]> /// @notice Provides the logic for AuthUserExecutedSharesRequestorProxy instances, /// in which shares requests are manually executed by a permissioned user /// @dev This will not work with a `denominationAsset` that does not transfer /// the exact expected amount or has an elastic supply. contract AuthUserExecutedSharesRequestorLib is IAuthUserExecutedSharesRequestor { using SafeERC20 for ERC20; using SafeMath for uint256; event RequestCanceled( address indexed requestOwner, uint256 investmentAmount, uint256 minSharesQuantity ); event RequestCreated( address indexed requestOwner, uint256 investmentAmount, uint256 minSharesQuantity ); event RequestExecuted( address indexed caller, address indexed requestOwner, uint256 investmentAmount, uint256 minSharesQuantity ); event RequestExecutorAdded(address indexed account); event RequestExecutorRemoved(address indexed account); struct RequestInfo { uint256 investmentAmount; uint256 minSharesQuantity; } uint256 private constant CANCELLATION_COOLDOWN_TIMELOCK = 10 minutes; address private comptrollerProxy; address private denominationAsset; address private fundOwner; mapping(address => RequestInfo) private ownerToRequestInfo; mapping(address => bool) private acctToIsRequestExecutor; mapping(address => uint256) private ownerToLastRequestCancellation; modifier onlyFundOwner() { require(msg.sender == fundOwner, "Only fund owner callable"); _; } /// @notice Initializes a proxy instance that uses this library /// @dev Serves as a per-proxy pseudo-constructor function init(address _comptrollerProxy) external override { require(comptrollerProxy == address(0), "init: Already initialized"); comptrollerProxy = _comptrollerProxy; // Cache frequently-used values that require external calls ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy); denominationAsset = comptrollerProxyContract.getDenominationAsset(); fundOwner = VaultLib(comptrollerProxyContract.getVaultProxy()).getOwner(); } /// @notice Cancels the shares request of the caller function cancelRequest() external { RequestInfo memory request = ownerToRequestInfo[msg.sender]; require(request.investmentAmount > 0, "cancelRequest: Request does not exist"); // Delete the request, start the cooldown period, and return the investment asset delete ownerToRequestInfo[msg.sender]; ownerToLastRequestCancellation[msg.sender] = block.timestamp; ERC20(denominationAsset).safeTransfer(msg.sender, request.investmentAmount); emit RequestCanceled(msg.sender, request.investmentAmount, request.minSharesQuantity); } /// @notice Creates a shares request for the caller /// @param _investmentAmount The amount of the fund's denomination asset to use to buy shares /// @param _minSharesQuantity The minimum quantity of shares to buy with the _investmentAmount function createRequest(uint256 _investmentAmount, uint256 _minSharesQuantity) external { require(_investmentAmount > 0, "createRequest: _investmentAmount must be > 0"); require( ownerToRequestInfo[msg.sender].investmentAmount == 0, "createRequest: The request owner can only create one request before executed or canceled" ); require( ownerToLastRequestCancellation[msg.sender] < block.timestamp.sub(CANCELLATION_COOLDOWN_TIMELOCK), "createRequest: Cannot create request during cancellation cooldown period" ); // Create the Request and take custody of investment asset ownerToRequestInfo[msg.sender] = RequestInfo({ investmentAmount: _investmentAmount, minSharesQuantity: _minSharesQuantity }); ERC20(denominationAsset).safeTransferFrom(msg.sender, address(this), _investmentAmount); emit RequestCreated(msg.sender, _investmentAmount, _minSharesQuantity); } /// @notice Executes multiple shares requests /// @param _requestOwners The owners of the pending shares requests function executeRequests(address[] calldata _requestOwners) external { require( msg.sender == fundOwner || isRequestExecutor(msg.sender), "executeRequests: Invalid caller" ); require(_requestOwners.length > 0, "executeRequests: _requestOwners can not be empty"); ( address[] memory buyers, uint256[] memory investmentAmounts, uint256[] memory minSharesQuantities, uint256 totalInvestmentAmount ) = __convertRequestsToBuySharesParams(_requestOwners); // Since ComptrollerProxy instances are fully trusted, // we can approve them with the max amount of the denomination asset, // and only top the approval back to max if ever necessary. address comptrollerProxyCopy = comptrollerProxy; ERC20 denominationAssetContract = ERC20(denominationAsset); if ( denominationAssetContract.allowance(address(this), comptrollerProxyCopy) < totalInvestmentAmount ) { denominationAssetContract.safeApprove(comptrollerProxyCopy, type(uint256).max); } ComptrollerLib(comptrollerProxyCopy).buyShares( buyers, investmentAmounts, minSharesQuantities ); } /// @dev Helper to convert raw shares requests into the format required by buyShares(). /// It also removes any empty requests, which is necessary to prevent a DoS attack where a user /// cancels their request earlier in the same block (can be repeated from multiple accounts). /// This function also removes shares requests and fires success events as it loops through them. function __convertRequestsToBuySharesParams(address[] memory _requestOwners) private returns ( address[] memory buyers_, uint256[] memory investmentAmounts_, uint256[] memory minSharesQuantities_, uint256 totalInvestmentAmount_ ) { uint256 existingRequestsCount = _requestOwners.length; uint256[] memory allInvestmentAmounts = new uint256[](_requestOwners.length); // Loop through once to get the count of existing requests for (uint256 i; i < _requestOwners.length; i++) { allInvestmentAmounts[i] = ownerToRequestInfo[_requestOwners[i]].investmentAmount; if (allInvestmentAmounts[i] == 0) { existingRequestsCount--; } } // Loop through a second time to format requests for buyShares(), // and to delete the requests and emit events early so no further looping is needed. buyers_ = new address[](existingRequestsCount); investmentAmounts_ = new uint256[](existingRequestsCount); minSharesQuantities_ = new uint256[](existingRequestsCount); uint256 existingRequestsIndex; for (uint256 i; i < _requestOwners.length; i++) { if (allInvestmentAmounts[i] == 0) { continue; } buyers_[existingRequestsIndex] = _requestOwners[i]; investmentAmounts_[existingRequestsIndex] = allInvestmentAmounts[i]; minSharesQuantities_[existingRequestsIndex] = ownerToRequestInfo[_requestOwners[i]] .minSharesQuantity; totalInvestmentAmount_ = totalInvestmentAmount_.add(allInvestmentAmounts[i]); delete ownerToRequestInfo[_requestOwners[i]]; emit RequestExecuted( msg.sender, buyers_[existingRequestsIndex], investmentAmounts_[existingRequestsIndex], minSharesQuantities_[existingRequestsIndex] ); existingRequestsIndex++; } return (buyers_, investmentAmounts_, minSharesQuantities_, totalInvestmentAmount_); } /////////////////////////////// // REQUEST EXECUTOR REGISTRY // /////////////////////////////// /// @notice Adds accounts to request executors /// @param _requestExecutors Accounts to add function addRequestExecutors(address[] calldata _requestExecutors) external onlyFundOwner { require(_requestExecutors.length > 0, "addRequestExecutors: Empty _requestExecutors"); for (uint256 i; i < _requestExecutors.length; i++) { require( !isRequestExecutor(_requestExecutors[i]), "addRequestExecutors: Value already set" ); require( _requestExecutors[i] != fundOwner, "addRequestExecutors: The fund owner cannot be added" ); acctToIsRequestExecutor[_requestExecutors[i]] = true; emit RequestExecutorAdded(_requestExecutors[i]); } } /// @notice Removes accounts from request executors /// @param _requestExecutors Accounts to remove function removeRequestExecutors(address[] calldata _requestExecutors) external onlyFundOwner { require(_requestExecutors.length > 0, "removeRequestExecutors: Empty _requestExecutors"); for (uint256 i; i < _requestExecutors.length; i++) { require( isRequestExecutor(_requestExecutors[i]), "removeRequestExecutors: Account is not a request executor" ); acctToIsRequestExecutor[_requestExecutors[i]] = false; emit RequestExecutorRemoved(_requestExecutors[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the value of `comptrollerProxy` variable /// @return comptrollerProxy_ The `comptrollerProxy` variable value function getComptrollerProxy() external view returns (address comptrollerProxy_) { return comptrollerProxy; } /// @notice Gets the value of `denominationAsset` variable /// @return denominationAsset_ The `denominationAsset` variable value function getDenominationAsset() external view returns (address denominationAsset_) { return denominationAsset; } /// @notice Gets the value of `fundOwner` variable /// @return fundOwner_ The `fundOwner` variable value function getFundOwner() external view returns (address fundOwner_) { return fundOwner; } /// @notice Gets the request info of a user /// @param _requestOwner The address of the user that creates the request /// @return requestInfo_ The request info created by the user function getSharesRequestInfoForOwner(address _requestOwner) external view returns (RequestInfo memory requestInfo_) { return ownerToRequestInfo[_requestOwner]; } /// @notice Checks whether an account is a request executor /// @param _who The account to check /// @return isRequestExecutor_ True if _who is a request executor function isRequestExecutor(address _who) public view returns (bool isRequestExecutor_) { return acctToIsRequestExecutor[_who]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAuthUserExecutedSharesRequestor Interface /// @author Enzyme Council <[email protected]> interface IAuthUserExecutedSharesRequestor { function init(address) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../core/fund/comptroller/ComptrollerLib.sol"; import "../../core/fund/vault/VaultLib.sol"; import "./AuthUserExecutedSharesRequestorProxy.sol"; import "./IAuthUserExecutedSharesRequestor.sol"; /// @title AuthUserExecutedSharesRequestorFactory Contract /// @author Enzyme Council <[email protected]> /// @notice Deploys and maintains a record of AuthUserExecutedSharesRequestorProxy instances contract AuthUserExecutedSharesRequestorFactory { event SharesRequestorProxyDeployed( address indexed comptrollerProxy, address sharesRequestorProxy ); address private immutable AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB; address private immutable DISPATCHER; mapping(address => address) private comptrollerProxyToSharesRequestorProxy; constructor(address _dispatcher, address _authUserExecutedSharesRequestorLib) public { AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB = _authUserExecutedSharesRequestorLib; DISPATCHER = _dispatcher; } /// @notice Deploys a shares requestor proxy instance for a given ComptrollerProxy instance /// @param _comptrollerProxy The ComptrollerProxy for which to deploy the shares requestor proxy /// @return sharesRequestorProxy_ The address of the newly-deployed shares requestor proxy function deploySharesRequestorProxy(address _comptrollerProxy) external returns (address sharesRequestorProxy_) { // Confirm fund is genuine VaultLib vaultProxyContract = VaultLib(ComptrollerLib(_comptrollerProxy).getVaultProxy()); require( vaultProxyContract.getAccessor() == _comptrollerProxy, "deploySharesRequestorProxy: Invalid VaultProxy for ComptrollerProxy" ); require( IDispatcher(DISPATCHER).getFundDeployerForVaultProxy(address(vaultProxyContract)) != address(0), "deploySharesRequestorProxy: Not a genuine fund" ); // Validate that the caller is the fund owner require( msg.sender == vaultProxyContract.getOwner(), "deploySharesRequestorProxy: Only fund owner callable" ); // Validate that a proxy does not already exist require( comptrollerProxyToSharesRequestorProxy[_comptrollerProxy] == address(0), "deploySharesRequestorProxy: Proxy already exists" ); // Deploy the proxy bytes memory constructData = abi.encodeWithSelector( IAuthUserExecutedSharesRequestor.init.selector, _comptrollerProxy ); sharesRequestorProxy_ = address( new AuthUserExecutedSharesRequestorProxy( constructData, AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB ) ); comptrollerProxyToSharesRequestorProxy[_comptrollerProxy] = sharesRequestorProxy_; emit SharesRequestorProxyDeployed(_comptrollerProxy, sharesRequestorProxy_); return sharesRequestorProxy_; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the value of the `AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB` variable /// @return authUserExecutedSharesRequestorLib_ The `AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB` variable value function getAuthUserExecutedSharesRequestorLib() external view returns (address authUserExecutedSharesRequestorLib_) { return AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB; } /// @notice Gets the value of the `DISPATCHER` variable /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() external view returns (address dispatcher_) { return DISPATCHER; } /// @notice Gets the AuthUserExecutedSharesRequestorProxy associated with the given ComptrollerProxy /// @param _comptrollerProxy The ComptrollerProxy for which to get the associated AuthUserExecutedSharesRequestorProxy /// @return sharesRequestorProxy_ The associated AuthUserExecutedSharesRequestorProxy address function getSharesRequestorProxyForComptrollerProxy(address _comptrollerProxy) external view returns (address sharesRequestorProxy_) { return comptrollerProxyToSharesRequestorProxy[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/Proxy.sol"; contract AuthUserExecutedSharesRequestorProxy is Proxy { constructor(bytes memory _constructData, address _authUserExecutedSharesRequestorLib) public Proxy(_constructData, _authUserExecutedSharesRequestorLib) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title Proxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract for all Proxy instances /// @dev The recommended implementation of a Proxy in EIP-1822, updated for solc 0.6.12, /// and using the EIP-1967 storage slot for the proxiable implementation. /// i.e., `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, which is /// "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc" /// See: https://eips.ethereum.org/EIPS/eip-1822 contract Proxy { constructor(bytes memory _constructData, address _contractLogic) public { assembly { sstore( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _contractLogic ) } (bool success, bytes memory returnData) = _contractLogic.delegatecall(_constructData); require(success, string(returnData)); } fallback() external payable { assembly { let contractLogic := sload( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc ) calldatacopy(0x0, 0x0, calldatasize()) let success := delegatecall( sub(gas(), 10000), contractLogic, 0x0, calldatasize(), 0, 0 ) let retSz := returndatasize() returndatacopy(0, 0, retSz) switch success case 0 { revert(0, retSz) } default { return(0, retSz) } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../utils/Proxy.sol"; /// @title ComptrollerProxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract for all ComptrollerProxy instances contract ComptrollerProxy is Proxy { constructor(bytes memory _constructData, address _comptrollerLib) public Proxy(_constructData, _comptrollerLib) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../../../persistent/dispatcher/IDispatcher.sol"; import "../../../persistent/utils/IMigrationHookHandler.sol"; import "../fund/comptroller/IComptroller.sol"; import "../fund/comptroller/ComptrollerProxy.sol"; import "../fund/vault/IVault.sol"; import "./IFundDeployer.sol"; /// @title FundDeployer Contract /// @author Enzyme Council <[email protected]> /// @notice The top-level contract of the release. /// It primarily coordinates fund deployment and fund migration, but /// it is also deferred to for contract access control and for allowed calls /// that can be made with a fund's VaultProxy as the msg.sender. contract FundDeployer is IFundDeployer, IMigrationHookHandler { event ComptrollerLibSet(address comptrollerLib); event ComptrollerProxyDeployed( address indexed creator, address comptrollerProxy, address indexed denominationAsset, uint256 sharesActionTimelock, bytes feeManagerConfigData, bytes policyManagerConfigData, bool indexed forMigration ); event NewFundCreated( address indexed creator, address comptrollerProxy, address vaultProxy, address indexed fundOwner, string fundName, address indexed denominationAsset, uint256 sharesActionTimelock, bytes feeManagerConfigData, bytes policyManagerConfigData ); event ReleaseStatusSet(ReleaseStatus indexed prevStatus, ReleaseStatus indexed nextStatus); event VaultCallDeregistered(address indexed contractAddress, bytes4 selector); event VaultCallRegistered(address indexed contractAddress, bytes4 selector); // Constants address private immutable CREATOR; address private immutable DISPATCHER; address private immutable VAULT_LIB; // Pseudo-constants (can only be set once) address private comptrollerLib; // Storage ReleaseStatus private releaseStatus; mapping(address => mapping(bytes4 => bool)) private contractToSelectorToIsRegisteredVaultCall; mapping(address => address) private pendingComptrollerProxyToCreator; modifier onlyLiveRelease() { require(releaseStatus == ReleaseStatus.Live, "Release is not Live"); _; } modifier onlyMigrator(address _vaultProxy) { require( IVault(_vaultProxy).canMigrate(msg.sender), "Only a permissioned migrator can call this function" ); _; } modifier onlyOwner() { require(msg.sender == getOwner(), "Only the contract owner can call this function"); _; } modifier onlyPendingComptrollerProxyCreator(address _comptrollerProxy) { require( msg.sender == pendingComptrollerProxyToCreator[_comptrollerProxy], "Only the ComptrollerProxy creator can call this function" ); _; } constructor( address _dispatcher, address _vaultLib, address[] memory _vaultCallContracts, bytes4[] memory _vaultCallSelectors ) public { if (_vaultCallContracts.length > 0) { __registerVaultCalls(_vaultCallContracts, _vaultCallSelectors); } CREATOR = msg.sender; DISPATCHER = _dispatcher; VAULT_LIB = _vaultLib; } ///////////// // GENERAL // ///////////// /// @notice Sets the comptrollerLib /// @param _comptrollerLib The ComptrollerLib contract address /// @dev Can only be set once function setComptrollerLib(address _comptrollerLib) external onlyOwner { require( comptrollerLib == address(0), "setComptrollerLib: This value can only be set once" ); comptrollerLib = _comptrollerLib; emit ComptrollerLibSet(_comptrollerLib); } /// @notice Sets the status of the protocol to a new state /// @param _nextStatus The next status state to set function setReleaseStatus(ReleaseStatus _nextStatus) external { require( msg.sender == IDispatcher(DISPATCHER).getOwner(), "setReleaseStatus: Only the Dispatcher owner can call this function" ); require( _nextStatus != ReleaseStatus.PreLaunch, "setReleaseStatus: Cannot return to PreLaunch status" ); require( comptrollerLib != address(0), "setReleaseStatus: Can only set the release status when comptrollerLib is set" ); ReleaseStatus prevStatus = releaseStatus; require(_nextStatus != prevStatus, "setReleaseStatus: _nextStatus is the current status"); releaseStatus = _nextStatus; emit ReleaseStatusSet(prevStatus, _nextStatus); } /// @notice Gets the current owner of the contract /// @return owner_ The contract owner address /// @dev Dynamically gets the owner based on the Protocol status. The owner is initially the /// contract's deployer, for convenience in setting up configuration. /// Ownership is claimed when the owner of the Dispatcher contract (the Enzyme Council) /// sets the releaseStatus to `Live`. function getOwner() public view override returns (address owner_) { if (releaseStatus == ReleaseStatus.PreLaunch) { return CREATOR; } return IDispatcher(DISPATCHER).getOwner(); } /////////////////// // FUND CREATION // /////////////////// /// @notice Creates a fully-configured ComptrollerProxy, to which a fund from a previous /// release can migrate in a subsequent step /// @param _denominationAsset The contract address of the denomination asset for the fund /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund /// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund /// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action function createMigratedFundConfig( address _denominationAsset, uint256 _sharesActionTimelock, bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external onlyLiveRelease returns (address comptrollerProxy_) { comptrollerProxy_ = __deployComptrollerProxy( _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData, true ); pendingComptrollerProxyToCreator[comptrollerProxy_] = msg.sender; return comptrollerProxy_; } /// @notice Creates a new fund /// @param _fundOwner The address of the owner for the fund /// @param _fundName The name of the fund /// @param _denominationAsset The contract address of the denomination asset for the fund /// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions" /// (buying or selling shares) by the same user /// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund /// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund /// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action function createNewFund( address _fundOwner, string calldata _fundName, address _denominationAsset, uint256 _sharesActionTimelock, bytes calldata _feeManagerConfigData, bytes calldata _policyManagerConfigData ) external onlyLiveRelease returns (address comptrollerProxy_, address vaultProxy_) { return __createNewFund( _fundOwner, _fundName, _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData ); } /// @dev Helper to avoid the stack-too-deep error during createNewFund function __createNewFund( address _fundOwner, string memory _fundName, address _denominationAsset, uint256 _sharesActionTimelock, bytes memory _feeManagerConfigData, bytes memory _policyManagerConfigData ) private returns (address comptrollerProxy_, address vaultProxy_) { require(_fundOwner != address(0), "__createNewFund: _owner cannot be empty"); comptrollerProxy_ = __deployComptrollerProxy( _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData, false ); vaultProxy_ = IDispatcher(DISPATCHER).deployVaultProxy( VAULT_LIB, _fundOwner, comptrollerProxy_, _fundName ); IComptroller(comptrollerProxy_).activate(vaultProxy_, false); emit NewFundCreated( msg.sender, comptrollerProxy_, vaultProxy_, _fundOwner, _fundName, _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData ); return (comptrollerProxy_, vaultProxy_); } /// @dev Helper function to deploy a configured ComptrollerProxy function __deployComptrollerProxy( address _denominationAsset, uint256 _sharesActionTimelock, bytes memory _feeManagerConfigData, bytes memory _policyManagerConfigData, bool _forMigration ) private returns (address comptrollerProxy_) { require( _denominationAsset != address(0), "__deployComptrollerProxy: _denominationAsset cannot be empty" ); bytes memory constructData = abi.encodeWithSelector( IComptroller.init.selector, _denominationAsset, _sharesActionTimelock ); comptrollerProxy_ = address(new ComptrollerProxy(constructData, comptrollerLib)); if (_feeManagerConfigData.length > 0 || _policyManagerConfigData.length > 0) { IComptroller(comptrollerProxy_).configureExtensions( _feeManagerConfigData, _policyManagerConfigData ); } emit ComptrollerProxyDeployed( msg.sender, comptrollerProxy_, _denominationAsset, _sharesActionTimelock, _feeManagerConfigData, _policyManagerConfigData, _forMigration ); return comptrollerProxy_; } ////////////////// // MIGRATION IN // ////////////////// /// @notice Cancels fund migration /// @param _vaultProxy The VaultProxy for which to cancel migration function cancelMigration(address _vaultProxy) external { __cancelMigration(_vaultProxy, false); } /// @notice Cancels fund migration, bypassing any failures. /// Should be used in an emergency only. /// @param _vaultProxy The VaultProxy for which to cancel migration function cancelMigrationEmergency(address _vaultProxy) external { __cancelMigration(_vaultProxy, true); } /// @notice Executes fund migration /// @param _vaultProxy The VaultProxy for which to execute the migration function executeMigration(address _vaultProxy) external { __executeMigration(_vaultProxy, false); } /// @notice Executes fund migration, bypassing any failures. /// Should be used in an emergency only. /// @param _vaultProxy The VaultProxy for which to execute the migration function executeMigrationEmergency(address _vaultProxy) external { __executeMigration(_vaultProxy, true); } /// @dev Unimplemented function invokeMigrationInCancelHook( address, address, address, address ) external virtual override { return; } /// @notice Signal a fund migration /// @param _vaultProxy The VaultProxy for which to signal the migration /// @param _comptrollerProxy The ComptrollerProxy for which to signal the migration function signalMigration(address _vaultProxy, address _comptrollerProxy) external { __signalMigration(_vaultProxy, _comptrollerProxy, false); } /// @notice Signal a fund migration, bypassing any failures. /// Should be used in an emergency only. /// @param _vaultProxy The VaultProxy for which to signal the migration /// @param _comptrollerProxy The ComptrollerProxy for which to signal the migration function signalMigrationEmergency(address _vaultProxy, address _comptrollerProxy) external { __signalMigration(_vaultProxy, _comptrollerProxy, true); } /// @dev Helper to cancel a migration function __cancelMigration(address _vaultProxy, bool _bypassFailure) private onlyLiveRelease onlyMigrator(_vaultProxy) { IDispatcher(DISPATCHER).cancelMigration(_vaultProxy, _bypassFailure); } /// @dev Helper to execute a migration function __executeMigration(address _vaultProxy, bool _bypassFailure) private onlyLiveRelease onlyMigrator(_vaultProxy) { IDispatcher dispatcherContract = IDispatcher(DISPATCHER); (, address comptrollerProxy, , ) = dispatcherContract .getMigrationRequestDetailsForVaultProxy(_vaultProxy); dispatcherContract.executeMigration(_vaultProxy, _bypassFailure); IComptroller(comptrollerProxy).activate(_vaultProxy, true); delete pendingComptrollerProxyToCreator[comptrollerProxy]; } /// @dev Helper to signal a migration function __signalMigration( address _vaultProxy, address _comptrollerProxy, bool _bypassFailure ) private onlyLiveRelease onlyPendingComptrollerProxyCreator(_comptrollerProxy) onlyMigrator(_vaultProxy) { IDispatcher(DISPATCHER).signalMigration( _vaultProxy, _comptrollerProxy, VAULT_LIB, _bypassFailure ); } /////////////////// // MIGRATION OUT // /////////////////// /// @notice Allows "hooking into" specific moments in the migration pipeline /// to execute arbitrary logic during a migration out of this release /// @param _vaultProxy The VaultProxy being migrated function invokeMigrationOutHook( MigrationOutHook _hook, address _vaultProxy, address, address, address ) external override { if (_hook != MigrationOutHook.PreMigrate) { return; } require( msg.sender == DISPATCHER, "postMigrateOriginHook: Only Dispatcher can call this function" ); // Must use PreMigrate hook to get the ComptrollerProxy from the VaultProxy address comptrollerProxy = IVault(_vaultProxy).getAccessor(); // Wind down fund and destroy its config IComptroller(comptrollerProxy).destruct(); } ////////////// // REGISTRY // ////////////// /// @notice De-registers allowed arbitrary contract calls that can be sent from the VaultProxy /// @param _contracts The contracts of the calls to de-register /// @param _selectors The selectors of the calls to de-register function deregisterVaultCalls(address[] calldata _contracts, bytes4[] calldata _selectors) external onlyOwner { require(_contracts.length > 0, "deregisterVaultCalls: Empty _contracts"); require( _contracts.length == _selectors.length, "deregisterVaultCalls: Uneven input arrays" ); for (uint256 i; i < _contracts.length; i++) { require( isRegisteredVaultCall(_contracts[i], _selectors[i]), "deregisterVaultCalls: Call not registered" ); contractToSelectorToIsRegisteredVaultCall[_contracts[i]][_selectors[i]] = false; emit VaultCallDeregistered(_contracts[i], _selectors[i]); } } /// @notice Registers allowed arbitrary contract calls that can be sent from the VaultProxy /// @param _contracts The contracts of the calls to register /// @param _selectors The selectors of the calls to register function registerVaultCalls(address[] calldata _contracts, bytes4[] calldata _selectors) external onlyOwner { require(_contracts.length > 0, "registerVaultCalls: Empty _contracts"); __registerVaultCalls(_contracts, _selectors); } /// @dev Helper to register allowed vault calls function __registerVaultCalls(address[] memory _contracts, bytes4[] memory _selectors) private { require( _contracts.length == _selectors.length, "__registerVaultCalls: Uneven input arrays" ); for (uint256 i; i < _contracts.length; i++) { require( !isRegisteredVaultCall(_contracts[i], _selectors[i]), "__registerVaultCalls: Call already registered" ); contractToSelectorToIsRegisteredVaultCall[_contracts[i]][_selectors[i]] = true; emit VaultCallRegistered(_contracts[i], _selectors[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `comptrollerLib` variable value /// @return comptrollerLib_ The `comptrollerLib` variable value function getComptrollerLib() external view returns (address comptrollerLib_) { return comptrollerLib; } /// @notice Gets the `CREATOR` variable value /// @return creator_ The `CREATOR` variable value function getCreator() external view returns (address creator_) { return CREATOR; } /// @notice Gets the `DISPATCHER` variable value /// @return dispatcher_ The `DISPATCHER` variable value function getDispatcher() external view returns (address dispatcher_) { return DISPATCHER; } /// @notice Gets the creator of a pending ComptrollerProxy /// @return pendingComptrollerProxyCreator_ The pending ComptrollerProxy creator function getPendingComptrollerProxyCreator(address _comptrollerProxy) external view returns (address pendingComptrollerProxyCreator_) { return pendingComptrollerProxyToCreator[_comptrollerProxy]; } /// @notice Gets the `releaseStatus` variable value /// @return status_ The `releaseStatus` variable value function getReleaseStatus() external view override returns (ReleaseStatus status_) { return releaseStatus; } /// @notice Gets the `VAULT_LIB` variable value /// @return vaultLib_ The `VAULT_LIB` variable value function getVaultLib() external view returns (address vaultLib_) { return VAULT_LIB; } /// @notice Checks if a contract call is registered /// @param _contract The contract of the call to check /// @param _selector The selector of the call to check /// @return isRegistered_ True if the call is registered function isRegisteredVaultCall(address _contract, bytes4 _selector) public view override returns (bool isRegistered_) { return contractToSelectorToIsRegisteredVaultCall[_contract][_selector]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IMigrationHookHandler Interface /// @author Enzyme Council <[email protected]> interface IMigrationHookHandler { enum MigrationOutHook {PreSignal, PostSignal, PreMigrate, PostMigrate, PostCancel} function invokeMigrationInCancelHook( address _vaultProxy, address _prevFundDeployer, address _nextVaultAccessor, address _nextVaultLib ) external; function invokeMigrationOutHook( MigrationOutHook _hook, address _vaultProxy, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib ) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../../core/fund/vault/IVault.sol"; import "../../infrastructure/price-feeds/derivatives/IDerivativePriceFeed.sol"; import "../../infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol"; import "../../utils/AddressArrayLib.sol"; import "../../utils/AssetFinalityResolver.sol"; import "../policy-manager/IPolicyManager.sol"; import "../utils/ExtensionBase.sol"; import "../utils/FundDeployerOwnerMixin.sol"; import "../utils/PermissionedVaultActionMixin.sol"; import "./integrations/IIntegrationAdapter.sol"; import "./IIntegrationManager.sol"; /// @title IntegrationManager /// @author Enzyme Council <[email protected]> /// @notice Extension to handle DeFi integration actions for funds contract IntegrationManager is IIntegrationManager, ExtensionBase, FundDeployerOwnerMixin, PermissionedVaultActionMixin, AssetFinalityResolver { using AddressArrayLib for address[]; using EnumerableSet for EnumerableSet.AddressSet; using SafeMath for uint256; event AdapterDeregistered(address indexed adapter, string indexed identifier); event AdapterRegistered(address indexed adapter, string indexed identifier); event AuthUserAddedForFund(address indexed comptrollerProxy, address indexed account); event AuthUserRemovedForFund(address indexed comptrollerProxy, address indexed account); event CallOnIntegrationExecutedForFund( address indexed comptrollerProxy, address vaultProxy, address caller, address indexed adapter, bytes4 indexed selector, bytes integrationData, address[] incomingAssets, uint256[] incomingAssetAmounts, address[] outgoingAssets, uint256[] outgoingAssetAmounts ); address private immutable DERIVATIVE_PRICE_FEED; address private immutable POLICY_MANAGER; address private immutable PRIMITIVE_PRICE_FEED; EnumerableSet.AddressSet private registeredAdapters; mapping(address => mapping(address => bool)) private comptrollerProxyToAcctToIsAuthUser; constructor( address _fundDeployer, address _policyManager, address _derivativePriceFeed, address _primitivePriceFeed, address _synthetixPriceFeed, address _synthetixAddressResolver ) public FundDeployerOwnerMixin(_fundDeployer) AssetFinalityResolver(_synthetixPriceFeed, _synthetixAddressResolver) { DERIVATIVE_PRICE_FEED = _derivativePriceFeed; POLICY_MANAGER = _policyManager; PRIMITIVE_PRICE_FEED = _primitivePriceFeed; } ///////////// // GENERAL // ///////////// /// @notice Activates the extension by storing the VaultProxy function activateForFund(bool) external override { __setValidatedVaultProxy(msg.sender); } /// @notice Authorizes a user to act on behalf of a fund via the IntegrationManager /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _who The user to authorize function addAuthUserForFund(address _comptrollerProxy, address _who) external { __validateSetAuthUser(_comptrollerProxy, _who, true); comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] = true; emit AuthUserAddedForFund(_comptrollerProxy, _who); } /// @notice Deactivate the extension by destroying storage function deactivateForFund() external override { delete comptrollerProxyToVaultProxy[msg.sender]; } /// @notice Removes an authorized user from the IntegrationManager for the given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _who The authorized user to remove function removeAuthUserForFund(address _comptrollerProxy, address _who) external { __validateSetAuthUser(_comptrollerProxy, _who, false); comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] = false; emit AuthUserRemovedForFund(_comptrollerProxy, _who); } /// @notice Checks whether an account is an authorized IntegrationManager user for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _who The account to check /// @return isAuthUser_ True if the account is an authorized user or the fund owner function isAuthUserForFund(address _comptrollerProxy, address _who) public view returns (bool isAuthUser_) { return comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] || _who == IVault(comptrollerProxyToVaultProxy[_comptrollerProxy]).getOwner(); } /// @dev Helper to validate calls to update comptrollerProxyToAcctToIsAuthUser function __validateSetAuthUser( address _comptrollerProxy, address _who, bool _nextIsAuthUser ) private view { require( comptrollerProxyToVaultProxy[_comptrollerProxy] != address(0), "__validateSetAuthUser: Fund has not been activated" ); address fundOwner = IVault(comptrollerProxyToVaultProxy[_comptrollerProxy]).getOwner(); require( msg.sender == fundOwner, "__validateSetAuthUser: Only the fund owner can call this function" ); require(_who != fundOwner, "__validateSetAuthUser: Cannot set for the fund owner"); if (_nextIsAuthUser) { require( !comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who], "__validateSetAuthUser: Account is already an authorized user" ); } else { require( comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who], "__validateSetAuthUser: Account is not an authorized user" ); } } /////////////////////////////// // CALL-ON-EXTENSION ACTIONS // /////////////////////////////// /// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy /// @param _caller The user who called for this action /// @param _actionId An ID representing the desired action /// @param _callArgs The encoded args for the action function receiveCallFromComptroller( address _caller, uint256 _actionId, bytes calldata _callArgs ) external override { // Since we validate and store the ComptrollerProxy-VaultProxy pairing during // activateForFund(), this function does not require further validation of the // sending ComptrollerProxy address vaultProxy = comptrollerProxyToVaultProxy[msg.sender]; require(vaultProxy != address(0), "receiveCallFromComptroller: Fund is not active"); require( isAuthUserForFund(msg.sender, _caller), "receiveCallFromComptroller: Not an authorized user" ); // Dispatch the action if (_actionId == 0) { __callOnIntegration(_caller, vaultProxy, _callArgs); } else if (_actionId == 1) { __addZeroBalanceTrackedAssets(vaultProxy, _callArgs); } else if (_actionId == 2) { __removeZeroBalanceTrackedAssets(vaultProxy, _callArgs); } else { revert("receiveCallFromComptroller: Invalid _actionId"); } } /// @dev Adds assets with a zero balance as tracked assets of the fund function __addZeroBalanceTrackedAssets(address _vaultProxy, bytes memory _callArgs) private { address[] memory assets = abi.decode(_callArgs, (address[])); for (uint256 i; i < assets.length; i++) { require( __finalizeIfSynthAndGetAssetBalance(_vaultProxy, assets[i], true) == 0, "__addZeroBalanceTrackedAssets: Balance is not zero" ); __addTrackedAsset(msg.sender, assets[i]); } } /// @dev Removes assets with a zero balance from tracked assets of the fund function __removeZeroBalanceTrackedAssets(address _vaultProxy, bytes memory _callArgs) private { address[] memory assets = abi.decode(_callArgs, (address[])); address denominationAsset = IComptroller(msg.sender).getDenominationAsset(); for (uint256 i; i < assets.length; i++) { require( assets[i] != denominationAsset, "__removeZeroBalanceTrackedAssets: Cannot remove denomination asset" ); require( __finalizeIfSynthAndGetAssetBalance(_vaultProxy, assets[i], true) == 0, "__removeZeroBalanceTrackedAssets: Balance is not zero" ); __removeTrackedAsset(msg.sender, assets[i]); } } ///////////////////////// // CALL ON INTEGRATION // ///////////////////////// /// @notice Universal method for calling third party contract functions through adapters /// @param _caller The caller of this function via the ComptrollerProxy /// @param _vaultProxy The VaultProxy of the fund /// @param _callArgs The encoded args for this function /// - _adapter Adapter of the integration on which to execute a call /// - _selector Method selector of the adapter method to execute /// - _integrationData Encoded arguments specific to the adapter /// @dev msg.sender is the ComptrollerProxy. /// Refer to specific adapter to see how to encode its arguments. function __callOnIntegration( address _caller, address _vaultProxy, bytes memory _callArgs ) private { ( address adapter, bytes4 selector, bytes memory integrationData ) = __decodeCallOnIntegrationArgs(_callArgs); __preCoIHook(adapter, selector); /// Passing decoded _callArgs leads to stack-too-deep error ( address[] memory incomingAssets, uint256[] memory incomingAssetAmounts, address[] memory outgoingAssets, uint256[] memory outgoingAssetAmounts ) = __callOnIntegrationInner(_vaultProxy, _callArgs); __postCoIHook( adapter, selector, incomingAssets, incomingAssetAmounts, outgoingAssets, outgoingAssetAmounts ); __emitCoIEvent( _vaultProxy, _caller, adapter, selector, integrationData, incomingAssets, incomingAssetAmounts, outgoingAssets, outgoingAssetAmounts ); } /// @dev Helper to execute the bulk of logic of callOnIntegration. /// Avoids the stack-too-deep-error. function __callOnIntegrationInner(address vaultProxy, bytes memory _callArgs) private returns ( address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_ ) { ( address[] memory expectedIncomingAssets, uint256[] memory preCallIncomingAssetBalances, uint256[] memory minIncomingAssetAmounts, SpendAssetsHandleType spendAssetsHandleType, address[] memory spendAssets, uint256[] memory maxSpendAssetAmounts, uint256[] memory preCallSpendAssetBalances ) = __preProcessCoI(vaultProxy, _callArgs); __executeCoI( vaultProxy, _callArgs, abi.encode( spendAssetsHandleType, spendAssets, maxSpendAssetAmounts, expectedIncomingAssets ) ); ( incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_ ) = __postProcessCoI( vaultProxy, expectedIncomingAssets, preCallIncomingAssetBalances, minIncomingAssetAmounts, spendAssetsHandleType, spendAssets, maxSpendAssetAmounts, preCallSpendAssetBalances ); return (incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_); } /// @dev Helper to decode CoI args function __decodeCallOnIntegrationArgs(bytes memory _callArgs) private pure returns ( address adapter_, bytes4 selector_, bytes memory integrationData_ ) { return abi.decode(_callArgs, (address, bytes4, bytes)); } /// @dev Helper to emit the CallOnIntegrationExecuted event. /// Avoids stack-too-deep error. function __emitCoIEvent( address _vaultProxy, address _caller, address _adapter, bytes4 _selector, bytes memory _integrationData, address[] memory _incomingAssets, uint256[] memory _incomingAssetAmounts, address[] memory _outgoingAssets, uint256[] memory _outgoingAssetAmounts ) private { emit CallOnIntegrationExecutedForFund( msg.sender, _vaultProxy, _caller, _adapter, _selector, _integrationData, _incomingAssets, _incomingAssetAmounts, _outgoingAssets, _outgoingAssetAmounts ); } /// @dev Helper to execute a call to an integration /// @dev Avoids stack-too-deep error function __executeCoI( address _vaultProxy, bytes memory _callArgs, bytes memory _encodedAssetTransferArgs ) private { ( address adapter, bytes4 selector, bytes memory integrationData ) = __decodeCallOnIntegrationArgs(_callArgs); (bool success, bytes memory returnData) = adapter.call( abi.encodeWithSelector( selector, _vaultProxy, integrationData, _encodedAssetTransferArgs ) ); require(success, string(returnData)); } /// @dev Helper to get the vault's balance of a particular asset function __getVaultAssetBalance(address _vaultProxy, address _asset) private view returns (uint256) { return ERC20(_asset).balanceOf(_vaultProxy); } /// @dev Helper to check if an asset is supported function __isSupportedAsset(address _asset) private view returns (bool isSupported_) { return IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_asset) || IDerivativePriceFeed(DERIVATIVE_PRICE_FEED).isSupportedAsset(_asset); } /// @dev Helper for the actions to take on external contracts prior to executing CoI function __preCoIHook(address _adapter, bytes4 _selector) private { IPolicyManager(POLICY_MANAGER).validatePolicies( msg.sender, IPolicyManager.PolicyHook.PreCallOnIntegration, abi.encode(_adapter, _selector) ); } /// @dev Helper for the internal actions to take prior to executing CoI function __preProcessCoI(address _vaultProxy, bytes memory _callArgs) private returns ( address[] memory expectedIncomingAssets_, uint256[] memory preCallIncomingAssetBalances_, uint256[] memory minIncomingAssetAmounts_, SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory maxSpendAssetAmounts_, uint256[] memory preCallSpendAssetBalances_ ) { ( address adapter, bytes4 selector, bytes memory integrationData ) = __decodeCallOnIntegrationArgs(_callArgs); require(adapterIsRegistered(adapter), "callOnIntegration: Adapter is not registered"); // Note that expected incoming and spend assets are allowed to overlap // (e.g., a fee for the incomingAsset charged in a spend asset) ( spendAssetsHandleType_, spendAssets_, maxSpendAssetAmounts_, expectedIncomingAssets_, minIncomingAssetAmounts_ ) = IIntegrationAdapter(adapter).parseAssetsForMethod(selector, integrationData); require( spendAssets_.length == maxSpendAssetAmounts_.length, "__preProcessCoI: Spend assets arrays unequal" ); require( expectedIncomingAssets_.length == minIncomingAssetAmounts_.length, "__preProcessCoI: Incoming assets arrays unequal" ); require(spendAssets_.isUniqueSet(), "__preProcessCoI: Duplicate spend asset"); require( expectedIncomingAssets_.isUniqueSet(), "__preProcessCoI: Duplicate incoming asset" ); IVault vaultProxyContract = IVault(_vaultProxy); preCallIncomingAssetBalances_ = new uint256[](expectedIncomingAssets_.length); for (uint256 i = 0; i < expectedIncomingAssets_.length; i++) { require( expectedIncomingAssets_[i] != address(0), "__preProcessCoI: Empty incoming asset address" ); require( minIncomingAssetAmounts_[i] > 0, "__preProcessCoI: minIncomingAssetAmount must be >0" ); require( __isSupportedAsset(expectedIncomingAssets_[i]), "__preProcessCoI: Non-receivable incoming asset" ); // Get pre-call balance of each incoming asset. // If the asset is not tracked by the fund, allow the balance to default to 0. if (vaultProxyContract.isTrackedAsset(expectedIncomingAssets_[i])) { // We do not require incoming asset finality, but we attempt to finalize so that // the final incoming asset amount is more accurate. There is no need to finalize // post-tx. preCallIncomingAssetBalances_[i] = __finalizeIfSynthAndGetAssetBalance( _vaultProxy, expectedIncomingAssets_[i], false ); } } // Get pre-call balances of spend assets and grant approvals to adapter preCallSpendAssetBalances_ = new uint256[](spendAssets_.length); for (uint256 i = 0; i < spendAssets_.length; i++) { require(spendAssets_[i] != address(0), "__preProcessCoI: Empty spend asset"); require(maxSpendAssetAmounts_[i] > 0, "__preProcessCoI: Empty max spend asset amount"); // A spend asset must either be a tracked asset of the fund or a supported asset, // in order to prevent seeding the fund with a malicious token and performing arbitrary // actions within an adapter. require( vaultProxyContract.isTrackedAsset(spendAssets_[i]) || __isSupportedAsset(spendAssets_[i]), "__preProcessCoI: Non-spendable spend asset" ); // If spend asset is also an incoming asset, no need to record its balance if (!expectedIncomingAssets_.contains(spendAssets_[i])) { // By requiring spend asset finality before CoI, we will know whether or // not the asset balance was entirely spent during the call. There is no need // to finalize post-tx. preCallSpendAssetBalances_[i] = __finalizeIfSynthAndGetAssetBalance( _vaultProxy, spendAssets_[i], true ); } // Grant spend assets access to the adapter. // Note that spendAssets_ is already asserted to a unique set. if (spendAssetsHandleType_ == SpendAssetsHandleType.Approve) { // Use exact approve amount rather than increasing allowances, // because all adapters finish their actions atomically. __approveAssetSpender( msg.sender, spendAssets_[i], adapter, maxSpendAssetAmounts_[i] ); } else if (spendAssetsHandleType_ == SpendAssetsHandleType.Transfer) { __withdrawAssetTo(msg.sender, spendAssets_[i], adapter, maxSpendAssetAmounts_[i]); } else if (spendAssetsHandleType_ == SpendAssetsHandleType.Remove) { __removeTrackedAsset(msg.sender, spendAssets_[i]); } } } /// @dev Helper for the actions to take on external contracts after executing CoI function __postCoIHook( address _adapter, bytes4 _selector, address[] memory _incomingAssets, uint256[] memory _incomingAssetAmounts, address[] memory _outgoingAssets, uint256[] memory _outgoingAssetAmounts ) private { IPolicyManager(POLICY_MANAGER).validatePolicies( msg.sender, IPolicyManager.PolicyHook.PostCallOnIntegration, abi.encode( _adapter, _selector, _incomingAssets, _incomingAssetAmounts, _outgoingAssets, _outgoingAssetAmounts ) ); } /// @dev Helper to reconcile and format incoming and outgoing assets after executing CoI function __postProcessCoI( address _vaultProxy, address[] memory _expectedIncomingAssets, uint256[] memory _preCallIncomingAssetBalances, uint256[] memory _minIncomingAssetAmounts, SpendAssetsHandleType _spendAssetsHandleType, address[] memory _spendAssets, uint256[] memory _maxSpendAssetAmounts, uint256[] memory _preCallSpendAssetBalances ) private returns ( address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_, address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_ ) { address[] memory increasedSpendAssets; uint256[] memory increasedSpendAssetAmounts; ( outgoingAssets_, outgoingAssetAmounts_, increasedSpendAssets, increasedSpendAssetAmounts ) = __reconcileCoISpendAssets( _vaultProxy, _spendAssetsHandleType, _spendAssets, _maxSpendAssetAmounts, _preCallSpendAssetBalances ); (incomingAssets_, incomingAssetAmounts_) = __reconcileCoIIncomingAssets( _vaultProxy, _expectedIncomingAssets, _preCallIncomingAssetBalances, _minIncomingAssetAmounts, increasedSpendAssets, increasedSpendAssetAmounts ); return (incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_); } /// @dev Helper to process incoming asset balance changes. /// See __reconcileCoISpendAssets() for explanation on "increasedSpendAssets". function __reconcileCoIIncomingAssets( address _vaultProxy, address[] memory _expectedIncomingAssets, uint256[] memory _preCallIncomingAssetBalances, uint256[] memory _minIncomingAssetAmounts, address[] memory _increasedSpendAssets, uint256[] memory _increasedSpendAssetAmounts ) private returns (address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_) { // Incoming assets = expected incoming assets + spend assets with increased balances uint256 incomingAssetsCount = _expectedIncomingAssets.length.add( _increasedSpendAssets.length ); // Calculate and validate incoming asset amounts incomingAssets_ = new address[](incomingAssetsCount); incomingAssetAmounts_ = new uint256[](incomingAssetsCount); for (uint256 i = 0; i < _expectedIncomingAssets.length; i++) { uint256 balanceDiff = __getVaultAssetBalance(_vaultProxy, _expectedIncomingAssets[i]) .sub(_preCallIncomingAssetBalances[i]); require( balanceDiff >= _minIncomingAssetAmounts[i], "__reconcileCoIAssets: Received incoming asset less than expected" ); // Even if the asset's previous balance was >0, it might not have been tracked __addTrackedAsset(msg.sender, _expectedIncomingAssets[i]); incomingAssets_[i] = _expectedIncomingAssets[i]; incomingAssetAmounts_[i] = balanceDiff; } // Append increaseSpendAssets to incomingAsset vars if (_increasedSpendAssets.length > 0) { uint256 incomingAssetIndex = _expectedIncomingAssets.length; for (uint256 i = 0; i < _increasedSpendAssets.length; i++) { incomingAssets_[incomingAssetIndex] = _increasedSpendAssets[i]; incomingAssetAmounts_[incomingAssetIndex] = _increasedSpendAssetAmounts[i]; incomingAssetIndex++; } } return (incomingAssets_, incomingAssetAmounts_); } /// @dev Helper to process spend asset balance changes. /// "outgoingAssets" are the spend assets with a decrease in balance. /// "increasedSpendAssets" are the spend assets with an unexpected increase in balance. /// For example, "increasedSpendAssets" can occur if an adapter has a pre-balance of /// the spendAsset, which would be transferred to the fund at the end of the tx. function __reconcileCoISpendAssets( address _vaultProxy, SpendAssetsHandleType _spendAssetsHandleType, address[] memory _spendAssets, uint256[] memory _maxSpendAssetAmounts, uint256[] memory _preCallSpendAssetBalances ) private returns ( address[] memory outgoingAssets_, uint256[] memory outgoingAssetAmounts_, address[] memory increasedSpendAssets_, uint256[] memory increasedSpendAssetAmounts_ ) { // Determine spend asset balance changes uint256[] memory postCallSpendAssetBalances = new uint256[](_spendAssets.length); uint256 outgoingAssetsCount; uint256 increasedSpendAssetsCount; for (uint256 i = 0; i < _spendAssets.length; i++) { // If spend asset's initial balance is 0, then it is an incoming asset if (_preCallSpendAssetBalances[i] == 0) { continue; } // Handle SpendAssetsHandleType.Remove separately if (_spendAssetsHandleType == SpendAssetsHandleType.Remove) { outgoingAssetsCount++; continue; } // Determine if the asset is outgoing or incoming, and store the post-balance for later use postCallSpendAssetBalances[i] = __getVaultAssetBalance(_vaultProxy, _spendAssets[i]); // If the pre- and post- balances are equal, then the asset is neither incoming nor outgoing if (postCallSpendAssetBalances[i] < _preCallSpendAssetBalances[i]) { outgoingAssetsCount++; } else if (postCallSpendAssetBalances[i] > _preCallSpendAssetBalances[i]) { increasedSpendAssetsCount++; } } // Format outgoingAssets and increasedSpendAssets (spend assets with unexpected increase in balance) outgoingAssets_ = new address[](outgoingAssetsCount); outgoingAssetAmounts_ = new uint256[](outgoingAssetsCount); increasedSpendAssets_ = new address[](increasedSpendAssetsCount); increasedSpendAssetAmounts_ = new uint256[](increasedSpendAssetsCount); uint256 outgoingAssetsIndex; uint256 increasedSpendAssetsIndex; for (uint256 i = 0; i < _spendAssets.length; i++) { // If spend asset's initial balance is 0, then it is an incoming asset. if (_preCallSpendAssetBalances[i] == 0) { continue; } // Handle SpendAssetsHandleType.Remove separately. // No need to validate the max spend asset amount. if (_spendAssetsHandleType == SpendAssetsHandleType.Remove) { outgoingAssets_[outgoingAssetsIndex] = _spendAssets[i]; outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i]; outgoingAssetsIndex++; continue; } // If the pre- and post- balances are equal, then the asset is neither incoming nor outgoing if (postCallSpendAssetBalances[i] < _preCallSpendAssetBalances[i]) { if (postCallSpendAssetBalances[i] == 0) { __removeTrackedAsset(msg.sender, _spendAssets[i]); outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i]; } else { outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i].sub( postCallSpendAssetBalances[i] ); } require( outgoingAssetAmounts_[outgoingAssetsIndex] <= _maxSpendAssetAmounts[i], "__reconcileCoISpendAssets: Spent amount greater than expected" ); outgoingAssets_[outgoingAssetsIndex] = _spendAssets[i]; outgoingAssetsIndex++; } else if (postCallSpendAssetBalances[i] > _preCallSpendAssetBalances[i]) { increasedSpendAssetAmounts_[increasedSpendAssetsIndex] = postCallSpendAssetBalances[i] .sub(_preCallSpendAssetBalances[i]); increasedSpendAssets_[increasedSpendAssetsIndex] = _spendAssets[i]; increasedSpendAssetsIndex++; } } return ( outgoingAssets_, outgoingAssetAmounts_, increasedSpendAssets_, increasedSpendAssetAmounts_ ); } /////////////////////////// // INTEGRATIONS REGISTRY // /////////////////////////// /// @notice Remove integration adapters from the list of registered adapters /// @param _adapters Addresses of adapters to be deregistered function deregisterAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require(_adapters.length > 0, "deregisterAdapters: _adapters cannot be empty"); for (uint256 i; i < _adapters.length; i++) { require( adapterIsRegistered(_adapters[i]), "deregisterAdapters: Adapter is not registered" ); registeredAdapters.remove(_adapters[i]); emit AdapterDeregistered(_adapters[i], IIntegrationAdapter(_adapters[i]).identifier()); } } /// @notice Add integration adapters to the list of registered adapters /// @param _adapters Addresses of adapters to be registered function registerAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require(_adapters.length > 0, "registerAdapters: _adapters cannot be empty"); for (uint256 i; i < _adapters.length; i++) { require(_adapters[i] != address(0), "registerAdapters: Adapter cannot be empty"); require( !adapterIsRegistered(_adapters[i]), "registerAdapters: Adapter already registered" ); registeredAdapters.add(_adapters[i]); emit AdapterRegistered(_adapters[i], IIntegrationAdapter(_adapters[i]).identifier()); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Checks if an integration adapter is registered /// @param _adapter The adapter to check /// @return isRegistered_ True if the adapter is registered function adapterIsRegistered(address _adapter) public view returns (bool isRegistered_) { return registeredAdapters.contains(_adapter); } /// @notice Gets the `DERIVATIVE_PRICE_FEED` variable /// @return derivativePriceFeed_ The `DERIVATIVE_PRICE_FEED` variable value function getDerivativePriceFeed() external view returns (address derivativePriceFeed_) { return DERIVATIVE_PRICE_FEED; } /// @notice Gets the `POLICY_MANAGER` variable /// @return policyManager_ The `POLICY_MANAGER` variable value function getPolicyManager() external view returns (address policyManager_) { return POLICY_MANAGER; } /// @notice Gets the `PRIMITIVE_PRICE_FEED` variable /// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) { return PRIMITIVE_PRICE_FEED; } /// @notice Gets all registered integration adapters /// @return registeredAdaptersArray_ A list of all registered integration adapters function getRegisteredAdapters() external view returns (address[] memory registeredAdaptersArray_) { registeredAdaptersArray_ = new address[](registeredAdapters.length()); for (uint256 i = 0; i < registeredAdaptersArray_.length; i++) { registeredAdaptersArray_[i] = registeredAdapters.at(i); } return registeredAdaptersArray_; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../infrastructure/price-feeds/derivatives/feeds/SynthetixPriceFeed.sol"; import "../../../../interfaces/ISynthetix.sol"; import "../utils/AdapterBase.sol"; /// @title SynthetixAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with Synthetix contract SynthetixAdapter is AdapterBase { address private immutable ORIGINATOR; address private immutable SYNTHETIX; address private immutable SYNTHETIX_PRICE_FEED; bytes32 private immutable TRACKING_CODE; constructor( address _integrationManager, address _synthetixPriceFeed, address _originator, address _synthetix, bytes32 _trackingCode ) public AdapterBase(_integrationManager) { ORIGINATOR = _originator; SYNTHETIX = _synthetix; SYNTHETIX_PRICE_FEED = _synthetixPriceFeed; TRACKING_CODE = _trackingCode; } // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "SYNTHETIX"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address incomingAsset, uint256 minIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.None, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on Synthetix /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata ) external onlyIntegrationManager { ( address incomingAsset, , address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); address[] memory synths = new address[](2); synths[0] = outgoingAsset; synths[1] = incomingAsset; bytes32[] memory currencyKeys = SynthetixPriceFeed(SYNTHETIX_PRICE_FEED) .getCurrencyKeysForSynths(synths); ISynthetix(SYNTHETIX).exchangeOnBehalfWithTracking( _vaultProxy, currencyKeys[0], outgoingAssetAmount, currencyKeys[1], ORIGINATOR, TRACKING_CODE ); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address incomingAsset_, uint256 minIncomingAssetAmount_, address outgoingAsset_, uint256 outgoingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, uint256, address, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ORIGINATOR` variable /// @return originator_ The `ORIGINATOR` variable value function getOriginator() external view returns (address originator_) { return ORIGINATOR; } /// @notice Gets the `SYNTHETIX` variable /// @return synthetix_ The `SYNTHETIX` variable value function getSynthetix() external view returns (address synthetix_) { return SYNTHETIX; } /// @notice Gets the `SYNTHETIX_PRICE_FEED` variable /// @return synthetixPriceFeed_ The `SYNTHETIX_PRICE_FEED` variable value function getSynthetixPriceFeed() external view returns (address synthetixPriceFeed_) { return SYNTHETIX_PRICE_FEED; } /// @notice Gets the `TRACKING_CODE` variable /// @return trackingCode_ The `TRACKING_CODE` variable value function getTrackingCode() external view returns (bytes32 trackingCode_) { return TRACKING_CODE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../interfaces/IChainlinkAggregator.sol"; import "../../utils/DispatcherOwnerMixin.sol"; import "./IPrimitivePriceFeed.sol"; /// @title ChainlinkPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice A price feed that uses Chainlink oracles as price sources contract ChainlinkPriceFeed is IPrimitivePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event EthUsdAggregatorSet(address prevEthUsdAggregator, address nextEthUsdAggregator); event PrimitiveAdded( address indexed primitive, address aggregator, RateAsset rateAsset, uint256 unit ); event PrimitiveRemoved(address indexed primitive); event PrimitiveUpdated( address indexed primitive, address prevAggregator, address nextAggregator ); event StalePrimitiveRemoved(address indexed primitive); event StaleRateThresholdSet(uint256 prevStaleRateThreshold, uint256 nextStaleRateThreshold); enum RateAsset {ETH, USD} struct AggregatorInfo { address aggregator; RateAsset rateAsset; } uint256 private constant ETH_UNIT = 10**18; address private immutable WETH_TOKEN; address private ethUsdAggregator; uint256 private staleRateThreshold; mapping(address => AggregatorInfo) private primitiveToAggregatorInfo; mapping(address => uint256) private primitiveToUnit; constructor( address _dispatcher, address _wethToken, address _ethUsdAggregator, address[] memory _primitives, address[] memory _aggregators, RateAsset[] memory _rateAssets ) public DispatcherOwnerMixin(_dispatcher) { WETH_TOKEN = _wethToken; staleRateThreshold = 25 hours; // 24 hour heartbeat + 1hr buffer __setEthUsdAggregator(_ethUsdAggregator); if (_primitives.length > 0) { __addPrimitives(_primitives, _aggregators, _rateAssets); } } // EXTERNAL FUNCTIONS /// @notice Calculates the value of a base asset in terms of a quote asset (using a canonical rate) /// @param _baseAsset The base asset /// @param _baseAssetAmount The base asset amount to convert /// @param _quoteAsset The quote asset /// @return quoteAssetAmount_ The equivalent quote asset amount /// @return isValid_ True if the rates used in calculations are deemed valid function calcCanonicalValue( address _baseAsset, uint256 _baseAssetAmount, address _quoteAsset ) public view override returns (uint256 quoteAssetAmount_, bool isValid_) { // Case where _baseAsset == _quoteAsset is handled by ValueInterpreter int256 baseAssetRate = __getLatestRateData(_baseAsset); if (baseAssetRate <= 0) { return (0, false); } int256 quoteAssetRate = __getLatestRateData(_quoteAsset); if (quoteAssetRate <= 0) { return (0, false); } (quoteAssetAmount_, isValid_) = __calcConversionAmount( _baseAsset, _baseAssetAmount, uint256(baseAssetRate), _quoteAsset, uint256(quoteAssetRate) ); return (quoteAssetAmount_, isValid_); } /// @notice Calculates the value of a base asset in terms of a quote asset (using a live rate) /// @param _baseAsset The base asset /// @param _baseAssetAmount The base asset amount to convert /// @param _quoteAsset The quote asset /// @return quoteAssetAmount_ The equivalent quote asset amount /// @return isValid_ True if the rates used in calculations are deemed valid /// @dev Live and canonical values are the same for Chainlink function calcLiveValue( address _baseAsset, uint256 _baseAssetAmount, address _quoteAsset ) external view override returns (uint256 quoteAssetAmount_, bool isValid_) { return calcCanonicalValue(_baseAsset, _baseAssetAmount, _quoteAsset); } /// @notice Checks whether an asset is a supported primitive of the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported primitive function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return _asset == WETH_TOKEN || primitiveToAggregatorInfo[_asset].aggregator != address(0); } /// @notice Sets the `ehUsdAggregator` variable value /// @param _nextEthUsdAggregator The `ehUsdAggregator` value to set function setEthUsdAggregator(address _nextEthUsdAggregator) external onlyDispatcherOwner { __setEthUsdAggregator(_nextEthUsdAggregator); } // PRIVATE FUNCTIONS /// @dev Helper to convert an amount from a _baseAsset to a _quoteAsset function __calcConversionAmount( address _baseAsset, uint256 _baseAssetAmount, uint256 _baseAssetRate, address _quoteAsset, uint256 _quoteAssetRate ) private view returns (uint256 quoteAssetAmount_, bool isValid_) { RateAsset baseAssetRateAsset = getRateAssetForPrimitive(_baseAsset); RateAsset quoteAssetRateAsset = getRateAssetForPrimitive(_quoteAsset); uint256 baseAssetUnit = getUnitForPrimitive(_baseAsset); uint256 quoteAssetUnit = getUnitForPrimitive(_quoteAsset); // If rates are both in ETH or both in USD if (baseAssetRateAsset == quoteAssetRateAsset) { return ( __calcConversionAmountSameRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate ), true ); } int256 ethPerUsdRate = IChainlinkAggregator(ethUsdAggregator).latestAnswer(); if (ethPerUsdRate <= 0) { return (0, false); } // If _baseAsset's rate is in ETH and _quoteAsset's rate is in USD if (baseAssetRateAsset == RateAsset.ETH) { return ( __calcConversionAmountEthRateAssetToUsdRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate, uint256(ethPerUsdRate) ), true ); } // If _baseAsset's rate is in USD and _quoteAsset's rate is in ETH return ( __calcConversionAmountUsdRateAssetToEthRateAsset( _baseAssetAmount, baseAssetUnit, _baseAssetRate, quoteAssetUnit, _quoteAssetRate, uint256(ethPerUsdRate) ), true ); } /// @dev Helper to convert amounts where the base asset has an ETH rate and the quote asset has a USD rate function __calcConversionAmountEthRateAssetToUsdRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate, uint256 _ethPerUsdRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow. // Intermediate step needed to resolve stack-too-deep error. uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_ethPerUsdRate).div( ETH_UNIT ); return intermediateStep.mul(_quoteAssetUnit).div(_baseAssetUnit).div(_quoteAssetRate); } /// @dev Helper to convert amounts where base and quote assets both have ETH rates or both have USD rates function __calcConversionAmountSameRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow return _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div( _baseAssetUnit.mul(_quoteAssetRate) ); } /// @dev Helper to convert amounts where the base asset has a USD rate and the quote asset has an ETH rate function __calcConversionAmountUsdRateAssetToEthRateAsset( uint256 _baseAssetAmount, uint256 _baseAssetUnit, uint256 _baseAssetRate, uint256 _quoteAssetUnit, uint256 _quoteAssetRate, uint256 _ethPerUsdRate ) private pure returns (uint256 quoteAssetAmount_) { // Only allows two consecutive multiplication operations to avoid potential overflow // Intermediate step needed to resolve stack-too-deep error. uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div( _ethPerUsdRate ); return intermediateStep.mul(ETH_UNIT).div(_baseAssetUnit).div(_quoteAssetRate); } /// @dev Helper to get the latest rate for a given primitive function __getLatestRateData(address _primitive) private view returns (int256 rate_) { if (_primitive == WETH_TOKEN) { return int256(ETH_UNIT); } address aggregator = primitiveToAggregatorInfo[_primitive].aggregator; require(aggregator != address(0), "__getLatestRateData: Primitive does not exist"); return IChainlinkAggregator(aggregator).latestAnswer(); } /// @dev Helper to set the `ethUsdAggregator` value function __setEthUsdAggregator(address _nextEthUsdAggregator) private { address prevEthUsdAggregator = ethUsdAggregator; require( _nextEthUsdAggregator != prevEthUsdAggregator, "__setEthUsdAggregator: Value already set" ); __validateAggregator(_nextEthUsdAggregator); ethUsdAggregator = _nextEthUsdAggregator; emit EthUsdAggregatorSet(prevEthUsdAggregator, _nextEthUsdAggregator); } ///////////////////////// // PRIMITIVES REGISTRY // ///////////////////////// /// @notice Adds a list of primitives with the given aggregator and rateAsset values /// @param _primitives The primitives to add /// @param _aggregators The ordered aggregators corresponding to the list of _primitives /// @param _rateAssets The ordered rate assets corresponding to the list of _primitives function addPrimitives( address[] calldata _primitives, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) external onlyDispatcherOwner { require(_primitives.length > 0, "addPrimitives: _primitives cannot be empty"); __addPrimitives(_primitives, _aggregators, _rateAssets); } /// @notice Removes a list of primitives from the feed /// @param _primitives The primitives to remove function removePrimitives(address[] calldata _primitives) external onlyDispatcherOwner { require(_primitives.length > 0, "removePrimitives: _primitives cannot be empty"); for (uint256 i; i < _primitives.length; i++) { require( primitiveToAggregatorInfo[_primitives[i]].aggregator != address(0), "removePrimitives: Primitive not yet added" ); delete primitiveToAggregatorInfo[_primitives[i]]; delete primitiveToUnit[_primitives[i]]; emit PrimitiveRemoved(_primitives[i]); } } /// @notice Removes stale primitives from the feed /// @param _primitives The stale primitives to remove /// @dev Callable by anybody function removeStalePrimitives(address[] calldata _primitives) external { require(_primitives.length > 0, "removeStalePrimitives: _primitives cannot be empty"); for (uint256 i; i < _primitives.length; i++) { address aggregatorAddress = primitiveToAggregatorInfo[_primitives[i]].aggregator; require(aggregatorAddress != address(0), "removeStalePrimitives: Invalid primitive"); require(rateIsStale(aggregatorAddress), "removeStalePrimitives: Rate is not stale"); delete primitiveToAggregatorInfo[_primitives[i]]; delete primitiveToUnit[_primitives[i]]; emit StalePrimitiveRemoved(_primitives[i]); } } /// @notice Sets the `staleRateThreshold` variable /// @param _nextStaleRateThreshold The next `staleRateThreshold` value function setStaleRateThreshold(uint256 _nextStaleRateThreshold) external onlyDispatcherOwner { uint256 prevStaleRateThreshold = staleRateThreshold; require( _nextStaleRateThreshold != prevStaleRateThreshold, "__setStaleRateThreshold: Value already set" ); staleRateThreshold = _nextStaleRateThreshold; emit StaleRateThresholdSet(prevStaleRateThreshold, _nextStaleRateThreshold); } /// @notice Updates the aggregators for given primitives /// @param _primitives The primitives to update /// @param _aggregators The ordered aggregators corresponding to the list of _primitives function updatePrimitives(address[] calldata _primitives, address[] calldata _aggregators) external onlyDispatcherOwner { require(_primitives.length > 0, "updatePrimitives: _primitives cannot be empty"); require( _primitives.length == _aggregators.length, "updatePrimitives: Unequal _primitives and _aggregators array lengths" ); for (uint256 i; i < _primitives.length; i++) { address prevAggregator = primitiveToAggregatorInfo[_primitives[i]].aggregator; require(prevAggregator != address(0), "updatePrimitives: Primitive not yet added"); require(_aggregators[i] != prevAggregator, "updatePrimitives: Value already set"); __validateAggregator(_aggregators[i]); primitiveToAggregatorInfo[_primitives[i]].aggregator = _aggregators[i]; emit PrimitiveUpdated(_primitives[i], prevAggregator, _aggregators[i]); } } /// @notice Checks whether the current rate is considered stale for the specified aggregator /// @param _aggregator The Chainlink aggregator of which to check staleness /// @return rateIsStale_ True if the rate is considered stale function rateIsStale(address _aggregator) public view returns (bool rateIsStale_) { return IChainlinkAggregator(_aggregator).latestTimestamp() < block.timestamp.sub(staleRateThreshold); } /// @dev Helper to add primitives to the feed function __addPrimitives( address[] memory _primitives, address[] memory _aggregators, RateAsset[] memory _rateAssets ) private { require( _primitives.length == _aggregators.length, "__addPrimitives: Unequal _primitives and _aggregators array lengths" ); require( _primitives.length == _rateAssets.length, "__addPrimitives: Unequal _primitives and _rateAssets array lengths" ); for (uint256 i = 0; i < _primitives.length; i++) { require( primitiveToAggregatorInfo[_primitives[i]].aggregator == address(0), "__addPrimitives: Value already set" ); __validateAggregator(_aggregators[i]); primitiveToAggregatorInfo[_primitives[i]] = AggregatorInfo({ aggregator: _aggregators[i], rateAsset: _rateAssets[i] }); // Store the amount that makes up 1 unit given the asset's decimals uint256 unit = 10**uint256(ERC20(_primitives[i]).decimals()); primitiveToUnit[_primitives[i]] = unit; emit PrimitiveAdded(_primitives[i], _aggregators[i], _rateAssets[i], unit); } } /// @dev Helper to validate an aggregator by checking its return values for the expected interface function __validateAggregator(address _aggregator) private view { require(_aggregator != address(0), "__validateAggregator: Empty _aggregator"); require( IChainlinkAggregator(_aggregator).latestAnswer() > 0, "__validateAggregator: No rate detected" ); require(!rateIsStale(_aggregator), "__validateAggregator: Stale rate detected"); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the aggregatorInfo variable value for a primitive /// @param _primitive The primitive asset for which to get the aggregatorInfo value /// @return aggregatorInfo_ The aggregatorInfo value function getAggregatorInfoForPrimitive(address _primitive) external view returns (AggregatorInfo memory aggregatorInfo_) { return primitiveToAggregatorInfo[_primitive]; } /// @notice Gets the `ethUsdAggregator` variable value /// @return ethUsdAggregator_ The `ethUsdAggregator` variable value function getEthUsdAggregator() external view returns (address ethUsdAggregator_) { return ethUsdAggregator; } /// @notice Gets the `staleRateThreshold` variable value /// @return staleRateThreshold_ The `staleRateThreshold` variable value function getStaleRateThreshold() external view returns (uint256 staleRateThreshold_) { return staleRateThreshold; } /// @notice Gets the `WETH_TOKEN` variable value /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } /// @notice Gets the rateAsset variable value for a primitive /// @return rateAsset_ The rateAsset variable value /// @dev This isn't strictly necessary as WETH_TOKEN will be undefined and thus /// the RateAsset will be the 0-position of the enum (i.e. ETH), but it makes the /// behavior more explicit function getRateAssetForPrimitive(address _primitive) public view returns (RateAsset rateAsset_) { if (_primitive == WETH_TOKEN) { return RateAsset.ETH; } return primitiveToAggregatorInfo[_primitive].rateAsset; } /// @notice Gets the unit variable value for a primitive /// @return unit_ The unit variable value function getUnitForPrimitive(address _primitive) public view returns (uint256 unit_) { if (_primitive == WETH_TOKEN) { return ETH_UNIT; } return primitiveToUnit[_primitive]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../release/infrastructure/value-interpreter/IValueInterpreter.sol"; import "../../release/infrastructure/price-feeds/derivatives/IAggregatedDerivativePriceFeed.sol"; import "../../release/infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol"; /// @dev This contract acts as a centralized rate provider for mocks. /// Suited for a dev environment, it doesn't take into account gas costs. contract CentralizedRateProvider is Ownable { using SafeMath for uint256; address private immutable WETH; uint256 private maxDeviationPerSender; // Addresses are not immutable to facilitate lazy load (they're are not accessible at the mock env). address private valueInterpreter; address private aggregateDerivativePriceFeed; address private primitivePriceFeed; constructor(address _weth, uint256 _maxDeviationPerSender) public { maxDeviationPerSender = _maxDeviationPerSender; WETH = _weth; } /// @dev Calculates the value of a _baseAsset relative to a _quoteAsset. /// Label to ValueInterprete's calcLiveAssetValue function calcLiveAssetValue( address _baseAsset, uint256 _amount, address _quoteAsset ) public returns (uint256 value_) { uint256 baseDecimalsRate = 10**uint256(ERC20(_baseAsset).decimals()); uint256 quoteDecimalsRate = 10**uint256(ERC20(_quoteAsset).decimals()); // 1. Check if quote asset is a primitive. If it is, use ValueInterpreter normally. if (IPrimitivePriceFeed(primitivePriceFeed).isSupportedAsset(_quoteAsset)) { (value_, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _baseAsset, _amount, _quoteAsset ); return value_; } // 2. Otherwise, check if base asset is a primitive, and use inverse rate from Value Interpreter. if (IPrimitivePriceFeed(primitivePriceFeed).isSupportedAsset(_baseAsset)) { (uint256 inverseRate, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _quoteAsset, 10**uint256(ERC20(_quoteAsset).decimals()), _baseAsset ); uint256 rate = uint256(baseDecimalsRate).mul(quoteDecimalsRate).div(inverseRate); value_ = _amount.mul(rate).div(baseDecimalsRate); return value_; } // 3. If both assets are derivatives, calculate the rate against ETH. (uint256 baseToWeth, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _baseAsset, baseDecimalsRate, WETH ); (uint256 quoteToWeth, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue( _quoteAsset, quoteDecimalsRate, WETH ); value_ = _amount.mul(baseToWeth).mul(quoteDecimalsRate).div(quoteToWeth).div( baseDecimalsRate ); return value_; } /// @dev Calculates a randomized live value of an asset /// Aggregation of two randomization seeds: msg.sender, and by block.number. function calcLiveAssetValueRandomized( address _baseAsset, uint256 _amount, address _quoteAsset, uint256 _maxDeviationPerBlock ) external returns (uint256 value_) { uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset); // Range [liveAssetValue * (1 - _blockNumberDeviation), liveAssetValue * (1 + _blockNumberDeviation)] uint256 senderRandomizedValue_ = __calcValueRandomizedByAddress( liveAssetValue, msg.sender, maxDeviationPerSender ); // Range [liveAssetValue * (1 - _maxDeviationPerBlock - maxDeviationPerSender), liveAssetValue * (1 + _maxDeviationPerBlock + maxDeviationPerSender)] value_ = __calcValueRandomizedByUint( senderRandomizedValue_, block.number, _maxDeviationPerBlock ); return value_; } /// @dev Calculates the live value of an asset including a grade of pseudo randomization, using msg.sender as the source of randomness function calcLiveAssetValueRandomizedByBlockNumber( address _baseAsset, uint256 _amount, address _quoteAsset, uint256 _maxDeviationPerBlock ) external returns (uint256 value_) { uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset); value_ = __calcValueRandomizedByUint(liveAssetValue, block.number, _maxDeviationPerBlock); return value_; } /// @dev Calculates the live value of an asset including a grade of pseudo-randomization, using `block.number` as the source of randomness function calcLiveAssetValueRandomizedBySender( address _baseAsset, uint256 _amount, address _quoteAsset ) external returns (uint256 value_) { uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset); value_ = __calcValueRandomizedByAddress(liveAssetValue, msg.sender, maxDeviationPerSender); return value_; } function setMaxDeviationPerSender(uint256 _maxDeviationPerSender) external onlyOwner { maxDeviationPerSender = _maxDeviationPerSender; } /// @dev Connector from release environment, inject price variables into the provider. function setReleasePriceAddresses( address _valueInterpreter, address _aggregateDerivativePriceFeed, address _primitivePriceFeed ) external onlyOwner { valueInterpreter = _valueInterpreter; aggregateDerivativePriceFeed = _aggregateDerivativePriceFeed; primitivePriceFeed = _primitivePriceFeed; } // PRIVATE FUNCTIONS /// @dev Calculates a a pseudo-randomized value as a seed an address function __calcValueRandomizedByAddress( uint256 _meanValue, address _seed, uint256 _maxDeviation ) private pure returns (uint256 value_) { // Value between [0, 100] uint256 senderRandomFactor = uint256(uint8(_seed)) .mul(100) .div(256) .mul(_maxDeviation) .div(100); value_ = __calcDeviatedValue(_meanValue, senderRandomFactor, _maxDeviation); return value_; } /// @dev Calculates a a pseudo-randomized value as a seed an uint256 function __calcValueRandomizedByUint( uint256 _meanValue, uint256 _seed, uint256 _maxDeviation ) private pure returns (uint256 value_) { // Depending on the _seed number, it will be one of {20, 40, 60, 80, 100} uint256 randomFactor = (_seed.mod(2).mul(20)) .add((_seed.mod(3).mul(40))) .mul(_maxDeviation) .div(100); value_ = __calcDeviatedValue(_meanValue, randomFactor, _maxDeviation); return value_; } /// @dev Given a mean value and a max deviation, returns a value in the spectrum between 0 (_meanValue - maxDeviation) and 100 (_mean + maxDeviation) /// TODO: Refactor to use 18 decimal precision function __calcDeviatedValue( uint256 _meanValue, uint256 _offset, uint256 _maxDeviation ) private pure returns (uint256 value_) { return _meanValue.add((_meanValue.mul((uint256(2)).mul(_offset)).div(uint256(100)))).sub( _meanValue.mul(_maxDeviation).div(uint256(100)) ); } /////////////////// // STATE GETTERS // /////////////////// function getMaxDeviationPerSender() public view returns (uint256 maxDeviationPerSender_) { return maxDeviationPerSender; } function getValueInterpreter() public view returns (address valueInterpreter_) { return valueInterpreter; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../release/interfaces/IUniswapV2Pair.sol"; import "../prices/CentralizedRateProvider.sol"; import "../tokens/MockToken.sol"; /// @dev This price source mocks the integration with Uniswap Pair /// Docs of Uniswap Pair implementation: <https://uniswap.org/docs/v2/smart-contracts/pair/> contract MockUniswapV2PriceSource is MockToken("Uniswap V2", "UNI-V2", 18) { using SafeMath for uint256; address private immutable TOKEN_0; address private immutable TOKEN_1; address private immutable CENTRALIZED_RATE_PROVIDER; constructor( address _centralizedRateProvider, address _token0, address _token1 ) public { CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; TOKEN_0 = _token0; TOKEN_1 = _token1; } /// @dev returns reserves for each token on the Uniswap Pair /// Reserves will be used to calculate the pair price /// Inherited from IUniswapV2Pair function getReserves() external returns ( uint112 reserve0_, uint112 reserve1_, uint32 blockTimestampLast_ ) { uint256 baseAmount = ERC20(TOKEN_0).balanceOf(address(this)); reserve0_ = uint112(baseAmount); reserve1_ = uint112( CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( TOKEN_0, baseAmount, TOKEN_1 ) ); return (reserve0_, reserve1_, blockTimestampLast_); } /////////////////// // STATE GETTERS // /////////////////// /// @dev Inherited from IUniswapV2Pair function token0() public view returns (address) { return TOKEN_0; } /// @dev Inherited from IUniswapV2Pair function token1() public view returns (address) { return TOKEN_1; } /// @dev Inherited from IUniswapV2Pair function kLast() public pure returns (uint256) { return 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract MockToken is ERC20Burnable, Ownable { using SafeMath for uint256; mapping(address => bool) private addressToIsMinter; modifier onlyMinter() { require( addressToIsMinter[msg.sender] || owner() == msg.sender, "msg.sender is not owner or minter" ); _; } constructor( string memory _name, string memory _symbol, uint8 _decimals ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); _mint(msg.sender, uint256(100000000).mul(10**uint256(_decimals))); } function mintFor(address _who, uint256 _amount) external onlyMinter { _mint(_who, _amount); } function mint(uint256 _amount) external onlyMinter { _mint(msg.sender, _amount); } function addMinters(address[] memory _minters) public onlyOwner { for (uint256 i = 0; i < _minters.length; i++) { addressToIsMinter[_minters[i]] = true; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../release/core/fund/comptroller/ComptrollerLib.sol"; import "./MockToken.sol"; /// @title MockReentrancyToken Contract /// @author Enzyme Council <[email protected]> /// @notice A mock ERC20 token implementation that is able to re-entrance redeemShares and buyShares functions contract MockReentrancyToken is MockToken("Mock Reentrancy Token", "MRT", 18) { bool public bad; address public comptrollerProxy; function makeItReentracyToken(address _comptrollerProxy) external { bad = true; comptrollerProxy = _comptrollerProxy; } function transfer(address recipient, uint256 amount) public override returns (bool) { if (bad) { ComptrollerLib(comptrollerProxy).redeemShares(); } else { _transfer(_msgSender(), recipient, amount); } return true; } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { if (bad) { ComptrollerLib(comptrollerProxy).buyShares( new address[](0), new uint256[](0), new uint256[](0) ); } else { _transfer(sender, recipient, amount); } return true; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./../../release/interfaces/ISynthetixProxyERC20.sol"; import "./../../release/interfaces/ISynthetixSynth.sol"; import "./MockToken.sol"; contract MockSynthetixToken is ISynthetixProxyERC20, ISynthetixSynth, MockToken { using SafeMath for uint256; bytes32 public override currencyKey; uint256 public constant WAITING_PERIOD_SECS = 3 * 60; mapping(address => uint256) public timelockByAccount; constructor( string memory _name, string memory _symbol, uint8 _decimals, bytes32 _currencyKey ) public MockToken(_name, _symbol, _decimals) { currencyKey = _currencyKey; } function setCurrencyKey(bytes32 _currencyKey) external onlyOwner { currencyKey = _currencyKey; } function _isLocked(address account) internal view returns (bool) { return timelockByAccount[account] >= now; } function _beforeTokenTransfer( address from, address, uint256 ) internal override { require(!_isLocked(from), "Cannot settle during waiting period"); } function target() external view override returns (address) { return address(this); } function isLocked(address account) external view returns (bool) { return _isLocked(account); } function burnFrom(address account, uint256 amount) public override { _burn(account, amount); } function lock(address account) public { timelockByAccount[account] = now.add(WAITING_PERIOD_SECS); } function unlock(address account) public { timelockByAccount[account] = 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IUniswapV2Factory.sol"; import "../../../../interfaces/IUniswapV2Router2.sol"; import "../utils/AdapterBase.sol"; /// @title UniswapV2Adapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with Uniswap v2 contract UniswapV2Adapter is AdapterBase { using SafeMath for uint256; address private immutable FACTORY; address private immutable ROUTER; constructor( address _integrationManager, address _router, address _factory ) public AdapterBase(_integrationManager) { FACTORY = _factory; ROUTER = _router; } // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "UNISWAP_V2"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { ( address[2] memory outgoingAssets, uint256[2] memory maxOutgoingAssetAmounts, , uint256 minIncomingAssetAmount ) = __decodeLendCallArgs(_encodedCallArgs); spendAssets_ = new address[](2); spendAssets_[0] = outgoingAssets[0]; spendAssets_[1] = outgoingAssets[1]; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = maxOutgoingAssetAmounts[0]; spendAssetAmounts_[1] = maxOutgoingAssetAmounts[1]; incomingAssets_ = new address[](1); // No need to validate not address(0), this will be caught in IntegrationManager incomingAssets_[0] = IUniswapV2Factory(FACTORY).getPair( outgoingAssets[0], outgoingAssets[1] ); minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else if (_selector == REDEEM_SELECTOR) { ( uint256 outgoingAssetAmount, address[2] memory incomingAssets, uint256[2] memory minIncomingAssetAmounts ) = __decodeRedeemCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); // No need to validate not address(0), this will be caught in IntegrationManager spendAssets_[0] = IUniswapV2Factory(FACTORY).getPair( incomingAssets[0], incomingAssets[1] ); spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](2); incomingAssets_[0] = incomingAssets[0]; incomingAssets_[1] = incomingAssets[1]; minIncomingAssetAmounts_ = new uint256[](2); minIncomingAssetAmounts_[0] = minIncomingAssetAmounts[0]; minIncomingAssetAmounts_[1] = minIncomingAssetAmounts[1]; } else if (_selector == TAKE_ORDER_SELECTOR) { ( address[] memory path, uint256 outgoingAssetAmount, uint256 minIncomingAssetAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); require(path.length >= 2, "parseAssetsForMethod: _path must be >= 2"); spendAssets_ = new address[](1); spendAssets_[0] = path[0]; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = path[path.length - 1]; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends assets for pool tokens on Uniswap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( address[2] memory outgoingAssets, uint256[2] memory maxOutgoingAssetAmounts, uint256[2] memory minOutgoingAssetAmounts, ) = __decodeLendCallArgs(_encodedCallArgs); __lend( _vaultProxy, outgoingAssets[0], outgoingAssets[1], maxOutgoingAssetAmounts[0], maxOutgoingAssetAmounts[1], minOutgoingAssetAmounts[0], minOutgoingAssetAmounts[1] ); } /// @notice Redeems pool tokens on Uniswap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingAssetAmount, address[2] memory incomingAssets, uint256[2] memory minIncomingAssetAmounts ) = __decodeRedeemCallArgs(_encodedCallArgs); // More efficient to parse pool token from _encodedAssetTransferArgs than external call (, address[] memory spendAssets, , ) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __redeem( _vaultProxy, spendAssets[0], outgoingAssetAmount, incomingAssets[0], incomingAssets[1], minIncomingAssetAmounts[0], minIncomingAssetAmounts[1] ); } /// @notice Trades assets on Uniswap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( address[] memory path, uint256 outgoingAssetAmount, uint256 minIncomingAssetAmount ) = __decodeTakeOrderCallArgs(_encodedCallArgs); __takeOrder(_vaultProxy, outgoingAssetAmount, minIncomingAssetAmount, path); } // PRIVATE FUNCTIONS /// @dev Helper to decode the lend encoded call arguments function __decodeLendCallArgs(bytes memory _encodedCallArgs) private pure returns ( address[2] memory outgoingAssets_, uint256[2] memory maxOutgoingAssetAmounts_, uint256[2] memory minOutgoingAssetAmounts_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address[2], uint256[2], uint256[2], uint256)); } /// @dev Helper to decode the redeem encoded call arguments function __decodeRedeemCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingAssetAmount_, address[2] memory incomingAssets_, uint256[2] memory minIncomingAssetAmounts_ ) { return abi.decode(_encodedCallArgs, (uint256, address[2], uint256[2])); } /// @dev Helper to decode the take order encoded call arguments function __decodeTakeOrderCallArgs(bytes memory _encodedCallArgs) private pure returns ( address[] memory path_, uint256 outgoingAssetAmount_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address[], uint256, uint256)); } /// @dev Helper to execute lend. Avoids stack-too-deep error. function __lend( address _vaultProxy, address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired, uint256 _amountAMin, uint256 _amountBMin ) private { __approveMaxAsNeeded(_tokenA, ROUTER, _amountADesired); __approveMaxAsNeeded(_tokenB, ROUTER, _amountBDesired); // Execute lend on Uniswap IUniswapV2Router2(ROUTER).addLiquidity( _tokenA, _tokenB, _amountADesired, _amountBDesired, _amountAMin, _amountBMin, _vaultProxy, block.timestamp.add(1) ); } /// @dev Helper to execute redeem. Avoids stack-too-deep error. function __redeem( address _vaultProxy, address _poolToken, uint256 _poolTokenAmount, address _tokenA, address _tokenB, uint256 _amountAMin, uint256 _amountBMin ) private { __approveMaxAsNeeded(_poolToken, ROUTER, _poolTokenAmount); // Execute redeem on Uniswap IUniswapV2Router2(ROUTER).removeLiquidity( _tokenA, _tokenB, _poolTokenAmount, _amountAMin, _amountBMin, _vaultProxy, block.timestamp.add(1) ); } /// @dev Helper to execute takeOrder. Avoids stack-too-deep error. function __takeOrder( address _vaultProxy, uint256 _outgoingAssetAmount, uint256 _minIncomingAssetAmount, address[] memory _path ) private { __approveMaxAsNeeded(_path[0], ROUTER, _outgoingAssetAmount); // Execute fill IUniswapV2Router2(ROUTER).swapExactTokensForTokens( _outgoingAssetAmount, _minIncomingAssetAmount, _path, _vaultProxy, block.timestamp.add(1) ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `FACTORY` variable /// @return factory_ The `FACTORY` variable value function getFactory() external view returns (address factory_) { return FACTORY; } /// @notice Gets the `ROUTER` variable /// @return router_ The `ROUTER` variable value function getRouter() external view returns (address router_) { return ROUTER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title UniswapV2Router2 Interface /// @author Enzyme Council <[email protected]> /// @dev Minimal interface for our interactions with Uniswap V2's Router2 interface IUniswapV2Router2 { function addLiquidity( address, address, uint256, uint256, uint256, uint256, address, uint256 ) external returns ( uint256, uint256, uint256 ); function removeLiquidity( address, address, uint256, uint256, uint256, address, uint256 ) external returns (uint256, uint256); function swapExactTokensForTokens( uint256, uint256, address[] calldata, address, uint256 ) external returns (uint256[] memory); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveLiquidityGaugeToken.sol"; import "../../../../interfaces/ICurveLiquidityPool.sol"; import "../../../../interfaces/ICurveRegistry.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../IDerivativePriceFeed.sol"; /// @title CurvePriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed for Curve pool tokens contract CurvePriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event DerivativeAdded( address indexed derivative, address indexed pool, address indexed invariantProxyAsset, uint256 invariantProxyAssetDecimals ); event DerivativeRemoved(address indexed derivative); // Both pool tokens and liquidity gauge tokens are treated the same for pricing purposes. // We take one asset as representative of the pool's invariant, e.g., WETH for ETH-based pools. struct DerivativeInfo { address pool; address invariantProxyAsset; uint256 invariantProxyAssetDecimals; } uint256 private constant VIRTUAL_PRICE_UNIT = 10**18; address private immutable ADDRESS_PROVIDER; mapping(address => DerivativeInfo) private derivativeToInfo; constructor(address _dispatcher, address _addressProvider) public DispatcherOwnerMixin(_dispatcher) { ADDRESS_PROVIDER = _addressProvider; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) public override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { DerivativeInfo memory derivativeInfo = derivativeToInfo[_derivative]; require( derivativeInfo.pool != address(0), "calcUnderlyingValues: _derivative is not supported" ); underlyings_ = new address[](1); underlyings_[0] = derivativeInfo.invariantProxyAsset; underlyingAmounts_ = new uint256[](1); if (derivativeInfo.invariantProxyAssetDecimals == 18) { underlyingAmounts_[0] = _derivativeAmount .mul(ICurveLiquidityPool(derivativeInfo.pool).get_virtual_price()) .div(VIRTUAL_PRICE_UNIT); } else { underlyingAmounts_[0] = _derivativeAmount .mul(ICurveLiquidityPool(derivativeInfo.pool).get_virtual_price()) .mul(10**derivativeInfo.invariantProxyAssetDecimals) .div(VIRTUAL_PRICE_UNIT.mul(2)); } return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return derivativeToInfo[_asset].pool != address(0); } ////////////////////////// // DERIVATIVES REGISTRY // ////////////////////////// /// @notice Adds Curve LP and/or liquidity gauge tokens to the price feed /// @param _derivatives Curve LP and/or liquidity gauge tokens to add /// @param _invariantProxyAssets The ordered assets that act as proxies to the pool invariants, /// corresponding to each item in _derivatives, e.g., WETH for ETH-based pools function addDerivatives( address[] calldata _derivatives, address[] calldata _invariantProxyAssets ) external onlyDispatcherOwner { require(_derivatives.length > 0, "addDerivatives: Empty _derivatives"); require( _derivatives.length == _invariantProxyAssets.length, "addDerivatives: Unequal arrays" ); for (uint256 i; i < _derivatives.length; i++) { require(_derivatives[i] != address(0), "addDerivatives: Empty derivative"); require( _invariantProxyAssets[i] != address(0), "addDerivatives: Empty invariantProxyAsset" ); require(!isSupportedAsset(_derivatives[i]), "addDerivatives: Value already set"); // First, try assuming that the derivative is an LP token ICurveRegistry curveRegistryContract = ICurveRegistry( ICurveAddressProvider(ADDRESS_PROVIDER).get_registry() ); address pool = curveRegistryContract.get_pool_from_lp_token(_derivatives[i]); // If the derivative is not a valid LP token, try to treat it as a liquidity gauge token if (pool == address(0)) { // We cannot confirm whether a liquidity gauge token is a valid token // for a particular liquidity gauge, due to some pools using // old liquidity gauge contracts that did not incorporate a token pool = curveRegistryContract.get_pool_from_lp_token( ICurveLiquidityGaugeToken(_derivatives[i]).lp_token() ); // Likely unreachable as above calls will revert on Curve, but doesn't hurt require( pool != address(0), "addDerivatives: Not a valid LP token or liquidity gauge token" ); } uint256 invariantProxyAssetDecimals = ERC20(_invariantProxyAssets[i]).decimals(); derivativeToInfo[_derivatives[i]] = DerivativeInfo({ pool: pool, invariantProxyAsset: _invariantProxyAssets[i], invariantProxyAssetDecimals: invariantProxyAssetDecimals }); // Confirm that a non-zero price can be returned for the registered derivative (, uint256[] memory underlyingAmounts) = calcUnderlyingValues( _derivatives[i], 1 ether ); require(underlyingAmounts[0] > 0, "addDerivatives: could not calculate valid price"); emit DerivativeAdded( _derivatives[i], pool, _invariantProxyAssets[i], invariantProxyAssetDecimals ); } } /// @notice Removes Curve LP and/or liquidity gauge tokens from the price feed /// @param _derivatives Curve LP and/or liquidity gauge tokens to add function removeDerivatives(address[] calldata _derivatives) external onlyDispatcherOwner { require(_derivatives.length > 0, "removeDerivatives: Empty _derivatives"); for (uint256 i; i < _derivatives.length; i++) { require(_derivatives[i] != address(0), "removeDerivatives: Empty derivative"); require(isSupportedAsset(_derivatives[i]), "removeDerivatives: Value is not set"); delete derivativeToInfo[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_PROVIDER` variable /// @return addressProvider_ The `ADDRESS_PROVIDER` variable value function getAddressProvider() external view returns (address addressProvider_) { return ADDRESS_PROVIDER; } /// @notice Gets the `DerivativeInfo` for a given derivative /// @param _derivative The derivative for which to get the `DerivativeInfo` /// @return derivativeInfo_ The `DerivativeInfo` value function getDerivativeInfo(address _derivative) external view returns (DerivativeInfo memory derivativeInfo_) { return derivativeToInfo[_derivative]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveAddressProvider interface /// @author Enzyme Council <[email protected]> interface ICurveAddressProvider { function get_address(uint256) external view returns (address); function get_registry() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityGaugeToken interface /// @author Enzyme Council <[email protected]> /// @notice Common interface functions for all Curve liquidity gauge token contracts interface ICurveLiquidityGaugeToken { function lp_token() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityPool interface /// @author Enzyme Council <[email protected]> interface ICurveLiquidityPool { function coins(uint256) external view returns (address); function get_virtual_price() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveRegistry interface /// @author Enzyme Council <[email protected]> interface ICurveRegistry { function get_gauges(address) external view returns (address[10] memory, int128[10] memory); function get_lp_token(address) external view returns (address); function get_pool_from_lp_token(address) external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveLiquidityGaugeV2.sol"; import "../../../../interfaces/ICurveLiquidityPool.sol"; import "../../../../interfaces/ICurveRegistry.sol"; import "../../../../interfaces/ICurveStableSwapSteth.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase2.sol"; /// @title CurveLiquidityStethAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for liquidity provision in Curve's steth pool (https://www.curve.fi/steth) contract CurveLiquidityStethAdapter is AdapterBase2 { int128 private constant POOL_INDEX_ETH = 0; int128 private constant POOL_INDEX_STETH = 1; address private immutable LIQUIDITY_GAUGE_TOKEN; address private immutable LP_TOKEN; address private immutable POOL; address private immutable STETH_TOKEN; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _liquidityGaugeToken, address _lpToken, address _pool, address _stethToken, address _wethToken ) public AdapterBase2(_integrationManager) { LIQUIDITY_GAUGE_TOKEN = _liquidityGaugeToken; LP_TOKEN = _lpToken; POOL = _pool; STETH_TOKEN = _stethToken; WETH_TOKEN = _wethToken; // Max approve contracts to spend relevant tokens ERC20(_lpToken).safeApprove(_liquidityGaugeToken, type(uint256).max); ERC20(_stethToken).safeApprove(_pool, type(uint256).max); } /// @dev Needed to receive ETH from redemption and to unwrap WETH receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "CURVE_LIQUIDITY_STETH"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR || _selector == LEND_AND_STAKE_SELECTOR) { ( uint256 outgoingWethAmount, uint256 outgoingStethAmount, uint256 minIncomingAssetAmount ) = __decodeLendCallArgs(_encodedCallArgs); if (outgoingWethAmount > 0 && outgoingStethAmount > 0) { spendAssets_ = new address[](2); spendAssets_[0] = WETH_TOKEN; spendAssets_[1] = STETH_TOKEN; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = outgoingWethAmount; spendAssetAmounts_[1] = outgoingStethAmount; } else if (outgoingWethAmount > 0) { spendAssets_ = new address[](1); spendAssets_[0] = WETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingWethAmount; } else { spendAssets_ = new address[](1); spendAssets_[0] = STETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingStethAmount; } incomingAssets_ = new address[](1); if (_selector == LEND_SELECTOR) { incomingAssets_[0] = LP_TOKEN; } else { incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN; } minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; } else if (_selector == REDEEM_SELECTOR || _selector == UNSTAKE_AND_REDEEM_SELECTOR) { ( uint256 outgoingAssetAmount, uint256 minIncomingWethAmount, uint256 minIncomingStethAmount, bool receiveSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); if (_selector == REDEEM_SELECTOR) { spendAssets_[0] = LP_TOKEN; } else { spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN; } spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; if (receiveSingleAsset) { incomingAssets_ = new address[](1); minIncomingAssetAmounts_ = new uint256[](1); if (minIncomingWethAmount == 0) { require( minIncomingStethAmount > 0, "parseAssetsForMethod: No min asset amount specified for receiveSingleAsset" ); incomingAssets_[0] = STETH_TOKEN; minIncomingAssetAmounts_[0] = minIncomingStethAmount; } else { require( minIncomingStethAmount == 0, "parseAssetsForMethod: Too many min asset amounts specified for receiveSingleAsset" ); incomingAssets_[0] = WETH_TOKEN; minIncomingAssetAmounts_[0] = minIncomingWethAmount; } } else { incomingAssets_ = new address[](2); incomingAssets_[0] = WETH_TOKEN; incomingAssets_[1] = STETH_TOKEN; minIncomingAssetAmounts_ = new uint256[](2); minIncomingAssetAmounts_[0] = minIncomingWethAmount; minIncomingAssetAmounts_[1] = minIncomingStethAmount; } } else if (_selector == STAKE_SELECTOR) { uint256 outgoingLPTokenAmount = __decodeStakeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = LP_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingLPTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = outgoingLPTokenAmount; } else if (_selector == UNSTAKE_SELECTOR) { uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = LP_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends assets for steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingWethAmount, uint256 outgoingStethAmount, uint256 minIncomingLiquidityGaugeTokenAmount ) = __decodeLendCallArgs(_encodedCallArgs); __lend(outgoingWethAmount, outgoingStethAmount, minIncomingLiquidityGaugeTokenAmount); } /// @notice Lends assets for steth LP tokens, then stakes the received LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lendAndStake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingWethAmount, uint256 outgoingStethAmount, uint256 minIncomingLiquidityGaugeTokenAmount ) = __decodeLendCallArgs(_encodedCallArgs); __lend(outgoingWethAmount, outgoingStethAmount, minIncomingLiquidityGaugeTokenAmount); __stake(ERC20(LP_TOKEN).balanceOf(address(this))); } /// @notice Redeems steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingLPTokenAmount, uint256 minIncomingWethAmount, uint256 minIncomingStethAmount, bool redeemSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); __redeem( outgoingLPTokenAmount, minIncomingWethAmount, minIncomingStethAmount, redeemSingleAsset ); } /// @notice Stakes steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function stake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { uint256 outgoingLPTokenAmount = __decodeStakeCallArgs(_encodedCallArgs); __stake(outgoingLPTokenAmount); } /// @notice Unstakes steth LP tokens /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function unstake( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_encodedCallArgs); __unstake(outgoingLiquidityGaugeTokenAmount); } /// @notice Unstakes steth LP tokens, then redeems them /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function unstakeAndRedeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( uint256 outgoingLiquidityGaugeTokenAmount, uint256 minIncomingWethAmount, uint256 minIncomingStethAmount, bool redeemSingleAsset ) = __decodeRedeemCallArgs(_encodedCallArgs); __unstake(outgoingLiquidityGaugeTokenAmount); __redeem( outgoingLiquidityGaugeTokenAmount, minIncomingWethAmount, minIncomingStethAmount, redeemSingleAsset ); } // PRIVATE FUNCTIONS /// @dev Helper to execute lend function __lend( uint256 _outgoingWethAmount, uint256 _outgoingStethAmount, uint256 _minIncomingLPTokenAmount ) private { if (_outgoingWethAmount > 0) { IWETH((WETH_TOKEN)).withdraw(_outgoingWethAmount); } ICurveStableSwapSteth(POOL).add_liquidity{value: _outgoingWethAmount}( [_outgoingWethAmount, _outgoingStethAmount], _minIncomingLPTokenAmount ); } /// @dev Helper to execute redeem function __redeem( uint256 _outgoingLPTokenAmount, uint256 _minIncomingWethAmount, uint256 _minIncomingStethAmount, bool _redeemSingleAsset ) private { if (_redeemSingleAsset) { // "_minIncomingWethAmount > 0 XOR _minIncomingStethAmount > 0" has already been // validated in parseAssetsForMethod() if (_minIncomingWethAmount > 0) { ICurveStableSwapSteth(POOL).remove_liquidity_one_coin( _outgoingLPTokenAmount, POOL_INDEX_ETH, _minIncomingWethAmount ); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } else { ICurveStableSwapSteth(POOL).remove_liquidity_one_coin( _outgoingLPTokenAmount, POOL_INDEX_STETH, _minIncomingStethAmount ); } } else { ICurveStableSwapSteth(POOL).remove_liquidity( _outgoingLPTokenAmount, [_minIncomingWethAmount, _minIncomingStethAmount] ); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } } /// @dev Helper to execute stake function __stake(uint256 _lpTokenAmount) private { ICurveLiquidityGaugeV2(LIQUIDITY_GAUGE_TOKEN).deposit(_lpTokenAmount, address(this)); } /// @dev Helper to execute unstake function __unstake(uint256 _liquidityGaugeTokenAmount) private { ICurveLiquidityGaugeV2(LIQUIDITY_GAUGE_TOKEN).withdraw(_liquidityGaugeTokenAmount); } /////////////////////// // ENCODED CALL ARGS // /////////////////////// /// @dev Helper to decode the encoded call arguments for lending function __decodeLendCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingWethAmount_, uint256 outgoingStethAmount_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (uint256, uint256, uint256)); } /// @dev Helper to decode the encoded call arguments for redeeming. /// If `receiveSingleAsset_` is `true`, then one (and only one) of /// `minIncomingWethAmount_` and `minIncomingStethAmount_` must be >0 /// to indicate which asset is to be received. function __decodeRedeemCallArgs(bytes memory _encodedCallArgs) private pure returns ( uint256 outgoingAssetAmount_, uint256 minIncomingWethAmount_, uint256 minIncomingStethAmount_, bool receiveSingleAsset_ ) { return abi.decode(_encodedCallArgs, (uint256, uint256, uint256, bool)); } /// @dev Helper to decode the encoded call arguments for staking function __decodeStakeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingLPTokenAmount_) { return abi.decode(_encodedCallArgs, (uint256)); } /// @dev Helper to decode the encoded call arguments for unstaking function __decodeUnstakeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingLiquidityGaugeTokenAmount_) { return abi.decode(_encodedCallArgs, (uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `LIQUIDITY_GAUGE_TOKEN` variable /// @return liquidityGaugeToken_ The `LIQUIDITY_GAUGE_TOKEN` variable value function getLiquidityGaugeToken() external view returns (address liquidityGaugeToken_) { return LIQUIDITY_GAUGE_TOKEN; } /// @notice Gets the `LP_TOKEN` variable /// @return lpToken_ The `LP_TOKEN` variable value function getLPToken() external view returns (address lpToken_) { return LP_TOKEN; } /// @notice Gets the `POOL` variable /// @return pool_ The `POOL` variable value function getPool() external view returns (address pool_) { return POOL; } /// @notice Gets the `STETH_TOKEN` variable /// @return stethToken_ The `STETH_TOKEN` variable value function getStethToken() external view returns (address stethToken_) { return STETH_TOKEN; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveLiquidityGaugeV2 interface /// @author Enzyme Council <[email protected]> interface ICurveLiquidityGaugeV2 { function deposit(uint256, address) external; function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveStableSwapSteth interface /// @author Enzyme Council <[email protected]> interface ICurveStableSwapSteth { function add_liquidity(uint256[2] calldata, uint256) external payable returns (uint256); function remove_liquidity(uint256, uint256[2] calldata) external returns (uint256[2] memory); function remove_liquidity_one_coin( uint256, int128, uint256 ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./AdapterBase.sol"; /// @title AdapterBase2 Contract /// @author Enzyme Council <[email protected]> /// @notice A base contract for integration adapters that extends AdapterBase /// @dev This is a temporary contract that will be merged into AdapterBase with the next release abstract contract AdapterBase2 is AdapterBase { /// @dev Provides a standard implementation for transferring incoming assets and /// unspent spend assets from an adapter to a VaultProxy at the end of an adapter action modifier postActionAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; ( , address[] memory spendAssets, , address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); __transferFullAssetBalances(_vaultProxy, incomingAssets); __transferFullAssetBalances(_vaultProxy, spendAssets); } /// @dev Provides a standard implementation for transferring incoming assets /// from an adapter to a VaultProxy at the end of an adapter action modifier postActionIncomingAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; (, , , address[] memory incomingAssets) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __transferFullAssetBalances(_vaultProxy, incomingAssets); } /// @dev Provides a standard implementation for transferring unspent spend assets /// from an adapter to a VaultProxy at the end of an adapter action modifier postActionSpendAssetsTransferHandler( address _vaultProxy, bytes memory _encodedAssetTransferArgs ) { _; (, address[] memory spendAssets, , ) = __decodeEncodedAssetTransferArgs( _encodedAssetTransferArgs ); __transferFullAssetBalances(_vaultProxy, spendAssets); } constructor(address _integrationManager) public AdapterBase(_integrationManager) {} /// @dev Helper to transfer full asset balances of current contract to the specified target function __transferFullAssetBalances(address _target, address[] memory _assets) internal { for (uint256 i = 0; i < _assets.length; i++) { uint256 balance = ERC20(_assets[i]).balanceOf(address(this)); if (balance > 0) { ERC20(_assets[i]).safeTransfer(_target, balance); } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IParaSwapAugustusSwapper.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title ParaSwapAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with ParaSwap contract ParaSwapAdapter is AdapterBase { using SafeMath for uint256; string private constant REFERRER = "enzyme"; address private immutable EXCHANGE; address private immutable TOKEN_TRANSFER_PROXY; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _exchange, address _tokenTransferProxy, address _wethToken ) public AdapterBase(_integrationManager) { EXCHANGE = _exchange; TOKEN_TRANSFER_PROXY = _tokenTransferProxy; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH refund from sent network fees receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "PARASWAP"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address incomingAsset, uint256 minIncomingAssetAmount, , address outgoingAsset, uint256 outgoingAssetAmount, IParaSwapAugustusSwapper.Path[] memory paths ) = __decodeCallArgs(_encodedCallArgs); // Format incoming assets incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; // Format outgoing assets depending on if there are network fees uint256 totalNetworkFees = __calcTotalNetworkFees(paths); if (totalNetworkFees > 0) { // We are not performing special logic if the incomingAsset is the fee asset if (outgoingAsset == WETH_TOKEN) { spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount.add(totalNetworkFees); } else { spendAssets_ = new address[](2); spendAssets_[0] = outgoingAsset; spendAssets_[1] = WETH_TOKEN; spendAssetAmounts_ = new uint256[](2); spendAssetAmounts_[0] = outgoingAssetAmount; spendAssetAmounts_[1] = totalNetworkFees; } } else { spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on ParaSwap /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { __takeOrder(_vaultProxy, _encodedCallArgs); } // PRIVATE FUNCTIONS /// @dev Helper to parse the total amount of network fees (in ETH) for the multiSwap() call function __calcTotalNetworkFees(IParaSwapAugustusSwapper.Path[] memory _paths) private pure returns (uint256 totalNetworkFees_) { for (uint256 i; i < _paths.length; i++) { totalNetworkFees_ = totalNetworkFees_.add(_paths[i].totalNetworkFee); } return totalNetworkFees_; } /// @dev Helper to decode the encoded callOnIntegration call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address incomingAsset_, uint256 minIncomingAssetAmount_, uint256 expectedIncomingAssetAmount_, // Passed as a courtesy to ParaSwap for analytics address outgoingAsset_, uint256 outgoingAssetAmount_, IParaSwapAugustusSwapper.Path[] memory paths_ ) { return abi.decode( _encodedCallArgs, (address, uint256, uint256, address, uint256, IParaSwapAugustusSwapper.Path[]) ); } /// @dev Helper to encode the call to ParaSwap multiSwap() as low-level calldata. /// Avoids the stack-too-deep error. function __encodeMultiSwapCallData( address _vaultProxy, address _incomingAsset, uint256 _minIncomingAssetAmount, uint256 _expectedIncomingAssetAmount, // Passed as a courtesy to ParaSwap for analytics address _outgoingAsset, uint256 _outgoingAssetAmount, IParaSwapAugustusSwapper.Path[] memory _paths ) private pure returns (bytes memory multiSwapCallData) { return abi.encodeWithSelector( IParaSwapAugustusSwapper.multiSwap.selector, _outgoingAsset, // fromToken _incomingAsset, // toToken _outgoingAssetAmount, // fromAmount _minIncomingAssetAmount, // toAmount _expectedIncomingAssetAmount, // expectedAmount _paths, // path 0, // mintPrice payable(_vaultProxy), // beneficiary 0, // donationPercentage REFERRER // referrer ); } /// @dev Helper to execute ParaSwapAugustusSwapper.multiSwap() via a low-level call. /// Avoids the stack-too-deep error. function __executeMultiSwap(bytes memory _multiSwapCallData, uint256 _totalNetworkFees) private { (bool success, bytes memory returnData) = EXCHANGE.call{value: _totalNetworkFees}( _multiSwapCallData ); require(success, string(returnData)); } /// @dev Helper for the inner takeOrder() logic. /// Avoids the stack-too-deep error. function __takeOrder(address _vaultProxy, bytes memory _encodedCallArgs) private { ( address incomingAsset, uint256 minIncomingAssetAmount, uint256 expectedIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount, IParaSwapAugustusSwapper.Path[] memory paths ) = __decodeCallArgs(_encodedCallArgs); __approveMaxAsNeeded(outgoingAsset, TOKEN_TRANSFER_PROXY, outgoingAssetAmount); // If there are network fees, unwrap enough WETH to cover the fees uint256 totalNetworkFees = __calcTotalNetworkFees(paths); if (totalNetworkFees > 0) { __unwrapWeth(totalNetworkFees); } // Get the callData for the low-level multiSwap() call bytes memory multiSwapCallData = __encodeMultiSwapCallData( _vaultProxy, incomingAsset, minIncomingAssetAmount, expectedIncomingAssetAmount, outgoingAsset, outgoingAssetAmount, paths ); // Execute the trade on ParaSwap __executeMultiSwap(multiSwapCallData, totalNetworkFees); // If fees were paid and ETH remains in the contract, wrap it as WETH so it can be returned if (totalNetworkFees > 0) { __wrapEth(); } } /// @dev Helper to unwrap specified amount of WETH into ETH. /// Avoids the stack-too-deep error. function __unwrapWeth(uint256 _amount) private { IWETH(payable(WETH_TOKEN)).withdraw(_amount); } /// @dev Helper to wrap all ETH in contract as WETH. /// Avoids the stack-too-deep error. function __wrapEth() private { uint256 ethBalance = payable(address(this)).balance; if (ethBalance > 0) { IWETH(payable(WETH_TOKEN)).deposit{value: ethBalance}(); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `EXCHANGE` variable /// @return exchange_ The `EXCHANGE` variable value function getExchange() external view returns (address exchange_) { return EXCHANGE; } /// @notice Gets the `TOKEN_TRANSFER_PROXY` variable /// @return tokenTransferProxy_ The `TOKEN_TRANSFER_PROXY` variable value function getTokenTransferProxy() external view returns (address tokenTransferProxy_) { return TOKEN_TRANSFER_PROXY; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @title ParaSwap IAugustusSwapper interface interface IParaSwapAugustusSwapper { struct Route { address payable exchange; address targetExchange; uint256 percent; bytes payload; uint256 networkFee; } struct Path { address to; uint256 totalNetworkFee; Route[] routes; } function multiSwap( address, address, uint256, uint256, uint256, Path[] calldata, uint256, address payable, uint256, string calldata ) external payable returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../release/interfaces/IParaSwapAugustusSwapper.sol"; import "../prices/CentralizedRateProvider.sol"; import "../utils/SwapperBase.sol"; contract MockParaSwapIntegratee is SwapperBase { using SafeMath for uint256; address private immutable MOCK_CENTRALIZED_RATE_PROVIDER; // Deviation set in % defines the MAX deviation per block from the mean rate uint256 private blockNumberDeviation; constructor(address _mockCentralizedRateProvider, uint256 _blockNumberDeviation) public { MOCK_CENTRALIZED_RATE_PROVIDER = _mockCentralizedRateProvider; blockNumberDeviation = _blockNumberDeviation; } /// @dev Must be `public` to avoid error function multiSwap( address _fromToken, address _toToken, uint256 _fromAmount, uint256, // toAmount (min received amount) uint256, // expectedAmount IParaSwapAugustusSwapper.Path[] memory _paths, uint256, // mintPrice address, // beneficiary uint256, // donationPercentage string memory // referrer ) public payable returns (uint256) { return __multiSwap(_fromToken, _toToken, _fromAmount, _paths); } /// @dev Helper to parse the total amount of network fees (in ETH) for the multiSwap() call function __calcTotalNetworkFees(IParaSwapAugustusSwapper.Path[] memory _paths) private pure returns (uint256 totalNetworkFees_) { for (uint256 i; i < _paths.length; i++) { totalNetworkFees_ = totalNetworkFees_.add(_paths[i].totalNetworkFee); } return totalNetworkFees_; } /// @dev Helper to avoid the stack-too-deep error function __multiSwap( address _fromToken, address _toToken, uint256 _fromAmount, IParaSwapAugustusSwapper.Path[] memory _paths ) private returns (uint256) { address[] memory assetsFromIntegratee = new address[](1); assetsFromIntegratee[0] = _toToken; uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1); assetsFromIntegrateeAmounts[0] = CentralizedRateProvider(MOCK_CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(_fromToken, _fromAmount, _toToken, blockNumberDeviation); uint256 totalNetworkFees = __calcTotalNetworkFees(_paths); address[] memory assetsToIntegratee; uint256[] memory assetsToIntegrateeAmounts; if (totalNetworkFees > 0) { assetsToIntegratee = new address[](2); assetsToIntegratee[1] = ETH_ADDRESS; assetsToIntegrateeAmounts = new uint256[](2); assetsToIntegrateeAmounts[1] = totalNetworkFees; } else { assetsToIntegratee = new address[](1); assetsToIntegrateeAmounts = new uint256[](1); } assetsToIntegratee[0] = _fromToken; assetsToIntegrateeAmounts[0] = _fromAmount; __swap( msg.sender, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); return assetsFromIntegrateeAmounts[0]; } /////////////////// // STATE GETTERS // /////////////////// function getBlockNumberDeviation() external view returns (uint256 blockNumberDeviation_) { return blockNumberDeviation; } function getCentralizedRateProvider() external view returns (address centralizedRateProvider_) { return MOCK_CENTRALIZED_RATE_PROVIDER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./EthConstantMixin.sol"; abstract contract SwapperBase is EthConstantMixin { receive() external payable {} function __swapAssets( address payable _trader, address _srcToken, uint256 _srcAmount, address _destToken, uint256 _actualRate ) internal returns (uint256 destAmount_) { address[] memory assetsToIntegratee = new address[](1); assetsToIntegratee[0] = _srcToken; uint256[] memory assetsToIntegrateeAmounts = new uint256[](1); assetsToIntegrateeAmounts[0] = _srcAmount; address[] memory assetsFromIntegratee = new address[](1); assetsFromIntegratee[0] = _destToken; uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1); assetsFromIntegrateeAmounts[0] = _actualRate; __swap( _trader, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); return assetsFromIntegrateeAmounts[0]; } function __swap( address payable _trader, address[] memory _assetsToIntegratee, uint256[] memory _assetsToIntegrateeAmounts, address[] memory _assetsFromIntegratee, uint256[] memory _assetsFromIntegrateeAmounts ) internal { // Take custody of incoming assets for (uint256 i = 0; i < _assetsToIntegratee.length; i++) { address asset = _assetsToIntegratee[i]; uint256 amount = _assetsToIntegrateeAmounts[i]; require(asset != address(0), "__swap: empty value in _assetsToIntegratee"); require(amount > 0, "__swap: empty value in _assetsToIntegrateeAmounts"); // Incoming ETH amounts can be ignored if (asset == ETH_ADDRESS) { continue; } ERC20(asset).transferFrom(_trader, address(this), amount); } // Distribute outgoing assets for (uint256 i = 0; i < _assetsFromIntegratee.length; i++) { address asset = _assetsFromIntegratee[i]; uint256 amount = _assetsFromIntegrateeAmounts[i]; require(asset != address(0), "__swap: empty value in _assetsFromIntegratee"); require(amount > 0, "__swap: empty value in _assetsFromIntegrateeAmounts"); if (asset == ETH_ADDRESS) { _trader.transfer(amount); } else { ERC20(asset).transfer(_trader, amount); } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; abstract contract EthConstantMixin { address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/NormalizedRateProviderBase.sol"; import "../../utils/SwapperBase.sol"; abstract contract MockIntegrateeBase is NormalizedRateProviderBase, SwapperBase { constructor( address[] memory _defaultRateAssets, address[] memory _specialAssets, uint8[] memory _specialAssetDecimals, uint256 _ratePrecision ) public NormalizedRateProviderBase( _defaultRateAssets, _specialAssets, _specialAssetDecimals, _ratePrecision ) {} function __getRate(address _baseAsset, address _quoteAsset) internal view override returns (uint256) { // 1. Return constant if base asset is quote asset if (_baseAsset == _quoteAsset) { return 10**RATE_PRECISION; } // 2. Check for a direct rate uint256 directRate = assetToAssetRate[_baseAsset][_quoteAsset]; if (directRate > 0) { return directRate; } // 3. Check for inverse direct rate uint256 iDirectRate = assetToAssetRate[_quoteAsset][_baseAsset]; if (iDirectRate > 0) { return 10**(RATE_PRECISION.mul(2)).div(iDirectRate); } // 4. Else return 1 return 10**RATE_PRECISION; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./RateProviderBase.sol"; abstract contract NormalizedRateProviderBase is RateProviderBase { using SafeMath for uint256; uint256 public immutable RATE_PRECISION; constructor( address[] memory _defaultRateAssets, address[] memory _specialAssets, uint8[] memory _specialAssetDecimals, uint256 _ratePrecision ) public RateProviderBase(_specialAssets, _specialAssetDecimals) { RATE_PRECISION = _ratePrecision; for (uint256 i = 0; i < _defaultRateAssets.length; i++) { for (uint256 j = i + 1; j < _defaultRateAssets.length; j++) { assetToAssetRate[_defaultRateAssets[i]][_defaultRateAssets[j]] = 10**_ratePrecision; assetToAssetRate[_defaultRateAssets[j]][_defaultRateAssets[i]] = 10**_ratePrecision; } } } // TODO: move to main contracts' utils for use with prices function __calcDenormalizedQuoteAssetAmount( uint256 _baseAssetDecimals, uint256 _baseAssetAmount, uint256 _quoteAssetDecimals, uint256 _rate ) internal view returns (uint256) { return _rate.mul(_baseAssetAmount).mul(10**_quoteAssetDecimals).div( 10**(RATE_PRECISION.add(_baseAssetDecimals)) ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./EthConstantMixin.sol"; abstract contract RateProviderBase is EthConstantMixin { mapping(address => mapping(address => uint256)) public assetToAssetRate; // Handles non-ERC20 compliant assets like ETH and USD mapping(address => uint8) public specialAssetToDecimals; constructor(address[] memory _specialAssets, uint8[] memory _specialAssetDecimals) public { require( _specialAssets.length == _specialAssetDecimals.length, "constructor: _specialAssets and _specialAssetDecimals are uneven lengths" ); for (uint256 i = 0; i < _specialAssets.length; i++) { specialAssetToDecimals[_specialAssets[i]] = _specialAssetDecimals[i]; } specialAssetToDecimals[ETH_ADDRESS] = 18; } function __getDecimalsForAsset(address _asset) internal view returns (uint256) { uint256 decimals = specialAssetToDecimals[_asset]; if (decimals == 0) { decimals = uint256(ERC20(_asset).decimals()); } return decimals; } function __getRate(address _baseAsset, address _quoteAsset) internal view virtual returns (uint256) { return assetToAssetRate[_baseAsset][_quoteAsset]; } function setRates( address[] calldata _baseAssets, address[] calldata _quoteAssets, uint256[] calldata _rates ) external { require( _baseAssets.length == _quoteAssets.length, "setRates: _baseAssets and _quoteAssets are uneven lengths" ); require( _baseAssets.length == _rates.length, "setRates: _baseAssets and _rates are uneven lengths" ); for (uint256 i = 0; i < _baseAssets.length; i++) { assetToAssetRate[_baseAssets[i]][_quoteAssets[i]] = _rates[i]; } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /// @title AssetUnitCacheMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Mixin to store a cache of asset units abstract contract AssetUnitCacheMixin { event AssetUnitCached(address indexed asset, uint256 prevUnit, uint256 nextUnit); mapping(address => uint256) private assetToUnit; /// @notice Caches the decimal-relative unit for a given asset /// @param _asset The asset for which to cache the decimal-relative unit /// @dev Callable by any account function cacheAssetUnit(address _asset) public { uint256 prevUnit = getCachedUnitForAsset(_asset); uint256 nextUnit = 10**uint256(ERC20(_asset).decimals()); if (nextUnit != prevUnit) { assetToUnit[_asset] = nextUnit; emit AssetUnitCached(_asset, prevUnit, nextUnit); } } /// @notice Caches the decimal-relative units for multiple given assets /// @param _assets The assets for which to cache the decimal-relative units /// @dev Callable by any account function cacheAssetUnits(address[] memory _assets) public { for (uint256 i; i < _assets.length; i++) { cacheAssetUnit(_assets[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the cached decimal-relative unit for a given asset /// @param _asset The asset for which to get the cached decimal-relative unit /// @return unit_ The cached decimal-relative unit function getCachedUnitForAsset(address _asset) public view returns (uint256 unit_) { return assetToUnit[_asset]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../IDerivativePriceFeed.sol"; /// @title SinglePeggedDerivativePriceFeedBase Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed base for any single derivative that is pegged 1:1 to its underlying abstract contract SinglePeggedDerivativePriceFeedBase is IDerivativePriceFeed { address private immutable DERIVATIVE; address private immutable UNDERLYING; constructor(address _derivative, address _underlying) public { require( ERC20(_derivative).decimals() == ERC20(_underlying).decimals(), "constructor: Unequal decimals" ); DERIVATIVE = _derivative; UNDERLYING = _underlying; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Not a supported derivative"); underlyings_ = new address[](1); underlyings_[0] = UNDERLYING; underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount; return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == DERIVATIVE; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `DERIVATIVE` variable value /// @return derivative_ The `DERIVATIVE` variable value function getDerivative() external view returns (address derivative_) { return DERIVATIVE; } /// @notice Gets the `UNDERLYING` variable value /// @return underlying_ The `UNDERLYING` variable value function getUnderlying() external view returns (address underlying_) { return UNDERLYING; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../release/infrastructure/price-feeds/derivatives/feeds/utils/SinglePeggedDerivativePriceFeedBase.sol"; /// @title TestSingleUnderlyingDerivativeRegistry Contract /// @author Enzyme Council <[email protected]> /// @notice A test implementation of SinglePeggedDerivativePriceFeedBase contract TestSinglePeggedDerivativePriceFeed is SinglePeggedDerivativePriceFeedBase { constructor(address _derivative, address _underlying) public SinglePeggedDerivativePriceFeedBase(_derivative, _underlying) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/SinglePeggedDerivativePriceFeedBase.sol"; /// @title StakehoundEthPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Stakehound stETH, which maps 1:1 with ETH contract StakehoundEthPriceFeed is SinglePeggedDerivativePriceFeedBase { constructor(address _steth, address _weth) public SinglePeggedDerivativePriceFeedBase(_steth, _weth) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]yme.finance> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/SinglePeggedDerivativePriceFeedBase.sol"; /// @title LidoStethPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Lido stETH, which maps 1:1 with ETH (https://lido.fi/) contract LidoStethPriceFeed is SinglePeggedDerivativePriceFeedBase { constructor(address _steth, address _weth) public SinglePeggedDerivativePriceFeedBase(_steth, _weth) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/IKyberNetworkProxy.sol"; import "../../../../interfaces/IWETH.sol"; import "../../../../utils/MathHelpers.sol"; import "../utils/AdapterBase.sol"; /// @title KyberAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for interacting with Kyber Network contract KyberAdapter is AdapterBase, MathHelpers { address private immutable EXCHANGE; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _exchange, address _wethToken ) public AdapterBase(_integrationManager) { EXCHANGE = _exchange; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH from swap receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "KYBER_NETWORK"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address incomingAsset, uint256 minIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); require( incomingAsset != outgoingAsset, "parseAssetsForMethod: incomingAsset and outgoingAsset asset cannot be the same" ); require(outgoingAssetAmount > 0, "parseAssetsForMethod: outgoingAssetAmount must be >0"); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on Kyber /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { ( address incomingAsset, uint256 minIncomingAssetAmount, address outgoingAsset, uint256 outgoingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); uint256 minExpectedRate = __calcNormalizedRate( ERC20(outgoingAsset).decimals(), outgoingAssetAmount, ERC20(incomingAsset).decimals(), minIncomingAssetAmount ); if (outgoingAsset == WETH_TOKEN) { __swapNativeAssetToToken(incomingAsset, outgoingAssetAmount, minExpectedRate); } else if (incomingAsset == WETH_TOKEN) { __swapTokenToNativeAsset(outgoingAsset, outgoingAssetAmount, minExpectedRate); } else { __swapTokenToToken(incomingAsset, outgoingAsset, outgoingAssetAmount, minExpectedRate); } } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address incomingAsset_, uint256 minIncomingAssetAmount_, address outgoingAsset_, uint256 outgoingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, uint256, address, uint256)); } /// @dev Executes a swap of ETH to ERC20 function __swapNativeAssetToToken( address _incomingAsset, uint256 _outgoingAssetAmount, uint256 _minExpectedRate ) private { IWETH(payable(WETH_TOKEN)).withdraw(_outgoingAssetAmount); IKyberNetworkProxy(EXCHANGE).swapEtherToToken{value: _outgoingAssetAmount}( _incomingAsset, _minExpectedRate ); } /// @dev Executes a swap of ERC20 to ETH function __swapTokenToNativeAsset( address _outgoingAsset, uint256 _outgoingAssetAmount, uint256 _minExpectedRate ) private { __approveMaxAsNeeded(_outgoingAsset, EXCHANGE, _outgoingAssetAmount); IKyberNetworkProxy(EXCHANGE).swapTokenToEther( _outgoingAsset, _outgoingAssetAmount, _minExpectedRate ); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } /// @dev Executes a swap of ERC20 to ERC20 function __swapTokenToToken( address _incomingAsset, address _outgoingAsset, uint256 _outgoingAssetAmount, uint256 _minExpectedRate ) private { __approveMaxAsNeeded(_outgoingAsset, EXCHANGE, _outgoingAssetAmount); IKyberNetworkProxy(EXCHANGE).swapTokenToToken( _outgoingAsset, _outgoingAssetAmount, _incomingAsset, _minExpectedRate ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `EXCHANGE` variable /// @return exchange_ The `EXCHANGE` variable value function getExchange() external view returns (address exchange_) { return EXCHANGE; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title Kyber Network interface interface IKyberNetworkProxy { function swapEtherToToken(address, uint256) external payable returns (uint256); function swapTokenToEther( address, uint256, uint256 ) external returns (uint256); function swapTokenToToken( address, uint256, address, uint256 ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../release/utils/MathHelpers.sol"; import "../prices/CentralizedRateProvider.sol"; import "../utils/SwapperBase.sol"; contract MockKyberIntegratee is SwapperBase, Ownable, MathHelpers { using SafeMath for uint256; address private immutable CENTRALIZED_RATE_PROVIDER; address private immutable WETH; uint256 private constant PRECISION = 18; // Deviation set in % defines the MAX deviation per block from the mean rate uint256 private blockNumberDeviation; constructor( address _centralizedRateProvider, address _weth, uint256 _blockNumberDeviation ) public { CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; WETH = _weth; blockNumberDeviation = _blockNumberDeviation; } function swapEtherToToken(address _destToken, uint256) external payable returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(WETH, msg.value, _destToken, blockNumberDeviation); __swapAssets(msg.sender, ETH_ADDRESS, msg.value, _destToken, destAmount); return msg.value; } function swapTokenToEther( address _srcToken, uint256 _srcAmount, uint256 ) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(_srcToken, _srcAmount, WETH, blockNumberDeviation); __swapAssets(msg.sender, _srcToken, _srcAmount, ETH_ADDRESS, destAmount); return _srcAmount; } function swapTokenToToken( address _srcToken, uint256 _srcAmount, address _destToken, uint256 ) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(_srcToken, _srcAmount, _destToken, blockNumberDeviation); __swapAssets(msg.sender, _srcToken, _srcAmount, _destToken, destAmount); return _srcAmount; } function setBlockNumberDeviation(uint256 _deviationPct) external onlyOwner { blockNumberDeviation = _deviationPct; } function getExpectedRate( address _srcToken, address _destToken, uint256 _amount ) external returns (uint256 rate_, uint256 worstRate_) { if (_srcToken == ETH_ADDRESS) { _srcToken = WETH; } if (_destToken == ETH_ADDRESS) { _destToken = WETH; } uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomizedBySender(_srcToken, _amount, _destToken); rate_ = __calcNormalizedRate( ERC20(_srcToken).decimals(), _amount, ERC20(_destToken).decimals(), destAmount ); worstRate_ = rate_.mul(uint256(100).sub(blockNumberDeviation)).div(100); } /////////////////// // STATE GETTERS // /////////////////// function getCentralizedRateProvider() public view returns (address) { return CENTRALIZED_RATE_PROVIDER; } function getWeth() public view returns (address) { return WETH; } function getBlockNumberDeviation() public view returns (uint256) { return blockNumberDeviation; } function getPrecision() public pure returns (uint256) { return PRECISION; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./../../release/interfaces/ISynthetixExchangeRates.sol"; import "../prices/MockChainlinkPriceSource.sol"; /// @dev This price source offers two different options getting prices /// The first one is getting a fixed rate, which can be useful for tests /// The second approach calculates dinamically the rate making use of a chainlink price source /// Mocks the functionality of the folllowing Synthetix contracts: { Exchanger, ExchangeRates } contract MockSynthetixPriceSource is Ownable, ISynthetixExchangeRates { using SafeMath for uint256; mapping(bytes32 => uint256) private fixedRate; mapping(bytes32 => AggregatorInfo) private currencyKeyToAggregator; enum RateAsset {ETH, USD} struct AggregatorInfo { address aggregator; RateAsset rateAsset; } constructor(address _ethUsdAggregator) public { currencyKeyToAggregator[bytes32("ETH")] = AggregatorInfo({ aggregator: _ethUsdAggregator, rateAsset: RateAsset.USD }); } function setPriceSourcesForCurrencyKeys( bytes32[] calldata _currencyKeys, address[] calldata _aggregators, RateAsset[] calldata _rateAssets ) external onlyOwner { require( _currencyKeys.length == _aggregators.length && _rateAssets.length == _aggregators.length ); for (uint256 i = 0; i < _currencyKeys.length; i++) { currencyKeyToAggregator[_currencyKeys[i]] = AggregatorInfo({ aggregator: _aggregators[i], rateAsset: _rateAssets[i] }); } } function setRate(bytes32 _currencyKey, uint256 _rate) external onlyOwner { fixedRate[_currencyKey] = _rate; } /// @dev Calculates the rate from a currency key against USD function rateAndInvalid(bytes32 _currencyKey) external view override returns (uint256 rate_, bool isInvalid_) { uint256 storedRate = getFixedRate(_currencyKey); if (storedRate != 0) { rate_ = storedRate; } else { AggregatorInfo memory aggregatorInfo = getAggregatorFromCurrencyKey(_currencyKey); address aggregator = aggregatorInfo.aggregator; if (aggregator == address(0)) { rate_ = 0; isInvalid_ = true; return (rate_, isInvalid_); } uint256 decimals = MockChainlinkPriceSource(aggregator).decimals(); rate_ = uint256(MockChainlinkPriceSource(aggregator).latestAnswer()).mul( 10**(uint256(18).sub(decimals)) ); if (aggregatorInfo.rateAsset == RateAsset.ETH) { uint256 ethToUsd = uint256( MockChainlinkPriceSource( getAggregatorFromCurrencyKey(bytes32("ETH")) .aggregator ) .latestAnswer() ); rate_ = rate_.mul(ethToUsd).div(10**8); } } isInvalid_ = (rate_ == 0); return (rate_, isInvalid_); } /////////////////// // STATE GETTERS // /////////////////// function getAggregatorFromCurrencyKey(bytes32 _currencyKey) public view returns (AggregatorInfo memory _aggregator) { return currencyKeyToAggregator[_currencyKey]; } function getFixedRate(bytes32 _currencyKey) public view returns (uint256) { return fixedRate[_currencyKey]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; contract MockChainlinkPriceSource { event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp); uint256 public DECIMALS; int256 public latestAnswer; uint256 public latestTimestamp; uint256 public roundId; address public aggregator; constructor(uint256 _decimals) public { DECIMALS = _decimals; latestAnswer = int256(10**_decimals); latestTimestamp = now; roundId = 1; aggregator = address(this); } function setLatestAnswer(int256 _nextAnswer, uint256 _nextTimestamp) external { latestAnswer = _nextAnswer; latestTimestamp = _nextTimestamp; roundId = roundId + 1; emit AnswerUpdated(latestAnswer, roundId, latestTimestamp); } function setAggregator(address _nextAggregator) external { aggregator = _nextAggregator; } function decimals() public view returns (uint256) { return DECIMALS; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "./../../release/interfaces/ISynthetixExchangeRates.sol"; import "../prices/CentralizedRateProvider.sol"; import "../tokens/MockSynthetixToken.sol"; /// @dev Synthetix Integratee. Mocks functionalities from the folllowing synthetix contracts /// Synthetix, SynthetixAddressResolver, SynthetixDelegateApprovals /// Link to contracts: <https://github.com/Synthetixio/synthetix/tree/develop/contracts> contract MockSynthetixIntegratee is Ownable, MockToken { using SafeMath for uint256; mapping(address => mapping(address => bool)) private authorizerToDelegateToApproval; mapping(bytes32 => address) private currencyKeyToSynth; address private immutable CENTRALIZED_RATE_PROVIDER; address private immutable EXCHANGE_RATES; uint256 private immutable FEE; uint256 private constant UNIT_FEE = 1000; constructor( string memory _name, string memory _symbol, uint8 _decimals, address _centralizedRateProvider, address _exchangeRates, uint256 _fee ) public MockToken(_name, _symbol, _decimals) { CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; EXCHANGE_RATES = address(_exchangeRates); FEE = _fee; } receive() external payable {} function exchangeOnBehalfWithTracking( address _exchangeForAddress, bytes32 _srcCurrencyKey, uint256 _srcAmount, bytes32 _destinationCurrencyKey, address, bytes32 ) external returns (uint256 amountReceived_) { require( canExchangeFor(_exchangeForAddress, msg.sender), "exchangeOnBehalfWithTracking: Not approved to act on behalf" ); amountReceived_ = __calculateAndSwap( _exchangeForAddress, _srcAmount, _srcCurrencyKey, _destinationCurrencyKey ); return amountReceived_; } function getAmountsForExchange( uint256 _srcAmount, bytes32 _srcCurrencyKey, bytes32 _destCurrencyKey ) public returns ( uint256 amountReceived_, uint256 fee_, uint256 exchangeFeeRate_ ) { address srcToken = currencyKeyToSynth[_srcCurrencyKey]; address destToken = currencyKeyToSynth[_destCurrencyKey]; require( currencyKeyToSynth[_srcCurrencyKey] != address(0) && currencyKeyToSynth[_destCurrencyKey] != address(0), "getAmountsForExchange: Currency key doesn't have an associated synth" ); uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomizedBySender(srcToken, _srcAmount, destToken); exchangeFeeRate_ = FEE; amountReceived_ = destAmount.mul(UNIT_FEE.sub(exchangeFeeRate_)).div(UNIT_FEE); fee_ = destAmount.sub(amountReceived_); return (amountReceived_, fee_, exchangeFeeRate_); } function setSynthFromCurrencyKeys(bytes32[] calldata _currencyKeys, address[] calldata _synths) external { require( _currencyKeys.length == _synths.length, "setSynthFromCurrencyKey: Unequal _currencyKeys and _synths lengths" ); for (uint256 i = 0; i < _currencyKeys.length; i++) { currencyKeyToSynth[_currencyKeys[i]] = _synths[i]; } } function approveExchangeOnBehalf(address _delegate) external { authorizerToDelegateToApproval[msg.sender][_delegate] = true; } function __calculateAndSwap( address _exchangeForAddress, uint256 _srcAmount, bytes32 _srcCurrencyKey, bytes32 _destCurrencyKey ) private returns (uint256 amountReceived_) { MockSynthetixToken srcSynth = MockSynthetixToken(currencyKeyToSynth[_srcCurrencyKey]); MockSynthetixToken destSynth = MockSynthetixToken(currencyKeyToSynth[_destCurrencyKey]); require(address(srcSynth) != address(0), "__calculateAndSwap: Source synth is not listed"); require( address(destSynth) != address(0), "__calculateAndSwap: Destination synth is not listed" ); require( !srcSynth.isLocked(_exchangeForAddress), "__calculateAndSwap: Cannot settle during waiting period" ); (amountReceived_, , ) = getAmountsForExchange( _srcAmount, _srcCurrencyKey, _destCurrencyKey ); srcSynth.burnFrom(_exchangeForAddress, _srcAmount); destSynth.mintFor(_exchangeForAddress, amountReceived_); destSynth.lock(_exchangeForAddress); return amountReceived_; } function requireAndGetAddress(bytes32 _name, string calldata) external view returns (address resolvedAddress_) { if (_name == "ExchangeRates") { return EXCHANGE_RATES; } return address(this); } function settle(address, bytes32) external returns ( uint256, uint256, uint256 ) {} /////////////////// // STATE GETTERS // /////////////////// function canExchangeFor(address _authorizer, address _delegate) public view returns (bool canExchange_) { return authorizerToDelegateToApproval[_authorizer][_delegate]; } function getExchangeRates() public view returns (address exchangeRates_) { return EXCHANGE_RATES; } function getFee() public view returns (uint256 fee_) { return FEE; } function getSynthFromCurrencyKey(bytes32 _currencyKey) public view returns (address synth_) { return currencyKeyToSynth[_currencyKey]; } function getUnitFee() public pure returns (uint256 fee_) { return UNIT_FEE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../prices/CentralizedRateProvider.sol"; import "./utils/SimpleMockIntegrateeBase.sol"; /// @dev Mocks the integration with `UniswapV2Router02` <https://uniswap.org/docs/v2/smart-contracts/router02/> /// Additionally mocks the integration with `UniswapV2Factory` <https://uniswap.org/docs/v2/smart-contracts/factory/> contract MockUniswapV2Integratee is SwapperBase, Ownable { using SafeMath for uint256; mapping(address => mapping(address => address)) private assetToAssetToPair; address private immutable CENTRALIZED_RATE_PROVIDER; uint256 private constant PRECISION = 18; // Set in %, defines the MAX deviation per block from the mean rate uint256 private blockNumberDeviation; constructor( address[] memory _listOfToken0, address[] memory _listOfToken1, address[] memory _listOfPair, address _centralizedRateProvider, uint256 _blockNumberDeviation ) public { addPair(_listOfToken0, _listOfToken1, _listOfPair); CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; blockNumberDeviation = _blockNumberDeviation; } /// @dev Adds the maximum possible value from {_amountADesired _amountBDesired} /// Makes use of the value interpreter to perform those calculations function addLiquidity( address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired, uint256, uint256, address, uint256 ) external returns ( uint256, uint256, uint256 ) { __addLiquidity(_tokenA, _tokenB, _amountADesired, _amountBDesired); } /// @dev Removes the specified amount of liquidity /// Returns 50% of the incoming liquidity value on each token. function removeLiquidity( address _tokenA, address _tokenB, uint256 _liquidity, uint256, uint256, address, uint256 ) public returns (uint256, uint256) { __removeLiquidity(_tokenA, _tokenB, _liquidity); } function swapExactTokensForTokens( uint256 amountIn, uint256, address[] calldata path, address, uint256 ) external returns (uint256[] memory) { uint256 amountOut = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomized(path[0], amountIn, path[1], blockNumberDeviation); __swapAssets(msg.sender, path[0], amountIn, path[path.length - 1], amountOut); } /// @dev We don't calculate any intermediate values here because they aren't actually used /// Returns the randomized by sender value of the edge path assets function getAmountsOut(uint256 _amountIn, address[] calldata _path) external returns (uint256[] memory amounts_) { require(_path.length >= 2, "getAmountsOut: path must be >= 2"); address assetIn = _path[0]; address assetOut = _path[_path.length - 1]; uint256 amountOut = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValueRandomizedBySender(assetIn, _amountIn, assetOut); amounts_ = new uint256[](_path.length); amounts_[0] = _amountIn; amounts_[_path.length - 1] = amountOut; return amounts_; } function addPair( address[] memory _listOfToken0, address[] memory _listOfToken1, address[] memory _listOfPair ) public onlyOwner { require( _listOfPair.length == _listOfToken0.length, "constructor: _listOfPair and _listOfToken0 have an unequal length" ); require( _listOfPair.length == _listOfToken1.length, "constructor: _listOfPair and _listOfToken1 have an unequal length" ); for (uint256 i; i < _listOfPair.length; i++) { address token0 = _listOfToken0[i]; address token1 = _listOfToken1[i]; address pair = _listOfPair[i]; assetToAssetToPair[token0][token1] = pair; assetToAssetToPair[token1][token0] = pair; } } function setBlockNumberDeviation(uint256 _deviationPct) external onlyOwner { blockNumberDeviation = _deviationPct; } // PRIVATE FUNCTIONS /// Avoids stack-too-deep error. function __addLiquidity( address _tokenA, address _tokenB, uint256 _amountADesired, uint256 _amountBDesired ) private { address pair = getPair(_tokenA, _tokenB); uint256 amountA; uint256 amountB; uint256 amountBFromA = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(_tokenA, _amountADesired, _tokenB); uint256 amountAFromB = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(_tokenB, _amountBDesired, _tokenA); if (amountBFromA >= _amountBDesired) { amountA = amountAFromB; amountB = _amountBDesired; } else { amountA = _amountADesired; amountB = amountBFromA; } uint256 tokenPerLPToken = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(pair, 10**uint256(PRECISION), _tokenA); // Calculate the inverse rate to know the amount of LPToken to return from a unit of token uint256 inverseRate = uint256(10**PRECISION).mul(10**PRECISION).div(tokenPerLPToken); // Total liquidity can be calculated as 2x liquidity from amount A uint256 totalLiquidity = uint256(2).mul( amountA.mul(inverseRate).div(uint256(10**PRECISION)) ); require( ERC20(pair).balanceOf(address(this)) >= totalLiquidity, "__addLiquidity: Integratee doesn't have enough pair balance to cover the expected amount" ); address[] memory assetsToIntegratee = new address[](2); uint256[] memory assetsToIntegrateeAmounts = new uint256[](2); address[] memory assetsFromIntegratee = new address[](1); uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1); assetsToIntegratee[0] = _tokenA; assetsToIntegrateeAmounts[0] = amountA; assetsToIntegratee[1] = _tokenB; assetsToIntegrateeAmounts[1] = amountB; assetsFromIntegratee[0] = pair; assetsFromIntegrateeAmounts[0] = totalLiquidity; __swap( msg.sender, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); } /// Avoids stack-too-deep error. function __removeLiquidity( address _tokenA, address _tokenB, uint256 _liquidity ) private { address pair = assetToAssetToPair[_tokenA][_tokenB]; require(pair != address(0), "__removeLiquidity: this pair doesn't exist"); uint256 amountA = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(pair, _liquidity, _tokenA) .div(uint256(2)); uint256 amountB = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(pair, _liquidity, _tokenB) .div(uint256(2)); address[] memory assetsToIntegratee = new address[](1); uint256[] memory assetsToIntegrateeAmounts = new uint256[](1); address[] memory assetsFromIntegratee = new address[](2); uint256[] memory assetsFromIntegrateeAmounts = new uint256[](2); assetsToIntegratee[0] = pair; assetsToIntegrateeAmounts[0] = _liquidity; assetsFromIntegratee[0] = _tokenA; assetsFromIntegrateeAmounts[0] = amountA; assetsFromIntegratee[1] = _tokenB; assetsFromIntegrateeAmounts[1] = amountB; require( ERC20(_tokenA).balanceOf(address(this)) >= amountA, "__removeLiquidity: Integratee doesn't have enough tokenA balance to cover the expected amount" ); require( ERC20(_tokenB).balanceOf(address(this)) >= amountA, "__removeLiquidity: Integratee doesn't have enough tokenB balance to cover the expected amount" ); __swap( msg.sender, assetsToIntegratee, assetsToIntegrateeAmounts, assetsFromIntegratee, assetsFromIntegrateeAmounts ); } /////////////////// // STATE GETTERS // /////////////////// /// @dev By default set to address(0). It is read by UniswapV2PoolTokenValueCalculator: __calcPoolTokenValue function feeTo() external pure returns (address) { return address(0); } function getCentralizedRateProvider() public view returns (address) { return CENTRALIZED_RATE_PROVIDER; } function getBlockNumberDeviation() public view returns (uint256) { return blockNumberDeviation; } function getPrecision() public pure returns (uint256) { return PRECISION; } function getPair(address _token0, address _token1) public view returns (address) { return assetToAssetToPair[_token0][_token1]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./MockIntegrateeBase.sol"; abstract contract SimpleMockIntegrateeBase is MockIntegrateeBase { constructor( address[] memory _defaultRateAssets, address[] memory _specialAssets, uint8[] memory _specialAssetDecimals, uint256 _ratePrecision ) public MockIntegrateeBase( _defaultRateAssets, _specialAssets, _specialAssetDecimals, _ratePrecision ) {} function __getRateAndSwapAssets( address payable _trader, address _srcToken, uint256 _srcAmount, address _destToken ) internal returns (uint256 destAmount_) { uint256 actualRate = __getRate(_srcToken, _destToken); __swapAssets(_trader, _srcToken, _srcAmount, _destToken, actualRate); return actualRate; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "../../prices/CentralizedRateProvider.sol"; import "../../utils/SwapperBase.sol"; contract MockCTokenBase is ERC20, SwapperBase, Ownable { address internal immutable TOKEN; address internal immutable CENTRALIZED_RATE_PROVIDER; uint256 internal rate; mapping(address => mapping(address => uint256)) internal _allowances; constructor( string memory _name, string memory _symbol, uint8 _decimals, address _token, address _centralizedRateProvider, uint256 _initialRate ) public ERC20(_name, _symbol) { _setupDecimals(_decimals); TOKEN = _token; CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; rate = _initialRate; } function approve(address _spender, uint256 _amount) public virtual override returns (bool) { _allowances[msg.sender][_spender] = _amount; return true; } /// @dev Overriden `allowance` function, give the integratee infinite approval by default function allowance(address _owner, address _spender) public view override returns (uint256) { if (_spender == address(this) || _owner == _spender) { return 2**256 - 1; } else { return _allowances[_owner][_spender]; } } /// @dev Necessary as this contract doesn't directly inherit from MockToken function mintFor(address _who, uint256 _amount) external onlyOwner { _mint(_who, _amount); } /// @dev Necessary to allow updates on persistent deployments (e.g Kovan) function setRate(uint256 _rate) public onlyOwner { rate = _rate; } function transferFrom( address _sender, address _recipient, uint256 _amount ) public virtual override returns (bool) { _transfer(_sender, _recipient, _amount); return true; } // INTERNAL FUNCTIONS /// @dev Calculates the cTokenAmount given a tokenAmount /// Makes use of a inverse rate with the CentralizedRateProvider as a derivative can't be used as quoteAsset function __calcCTokenAmount(uint256 _tokenAmount) internal returns (uint256 cTokenAmount_) { uint256 tokenDecimals = ERC20(TOKEN).decimals(); uint256 cTokenDecimals = decimals(); // Result in Token Decimals uint256 tokenPerCTokenUnit = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(address(this), 10**uint256(cTokenDecimals), TOKEN); // Result in cToken decimals uint256 inverseRate = uint256(10**tokenDecimals).mul(10**uint256(cTokenDecimals)).div( tokenPerCTokenUnit ); // Amount in token decimals, result in cToken decimals cTokenAmount_ = _tokenAmount.mul(inverseRate).div(10**tokenDecimals); } /////////////////// // STATE GETTERS // /////////////////// /// @dev Part of ICERC20 token interface function underlying() public view returns (address) { return TOKEN; } /// @dev Part of ICERC20 token interface. /// Called from CompoundPriceFeed, returns the actual Rate cToken/Token function exchangeRateStored() public view returns (uint256) { return rate; } function getCentralizedRateProvider() public view returns (address) { return CENTRALIZED_RATE_PROVIDER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./MockCTokenBase.sol"; contract MockCTokenIntegratee is MockCTokenBase { constructor( string memory _name, string memory _symbol, uint8 _decimals, address _token, address _centralizedRateProvider, uint256 _initialRate ) public MockCTokenBase(_name, _symbol, _decimals, _token, _centralizedRateProvider, _initialRate) {} function mint(uint256 _amount) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( TOKEN, _amount, address(this) ); __swapAssets(msg.sender, TOKEN, _amount, address(this), destAmount); return _amount; } function redeem(uint256 _amount) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( address(this), _amount, TOKEN ); __swapAssets(msg.sender, address(this), _amount, TOKEN, destAmount); return _amount; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./MockCTokenBase.sol"; contract MockCEtherIntegratee is MockCTokenBase { constructor( string memory _name, string memory _symbol, uint8 _decimals, address _weth, address _centralizedRateProvider, uint256 _initialRate ) public MockCTokenBase(_name, _symbol, _decimals, _weth, _centralizedRateProvider, _initialRate) {} function mint() external payable { uint256 amount = msg.value; uint256 destAmount = __calcCTokenAmount(amount); __swapAssets(msg.sender, ETH_ADDRESS, amount, address(this), destAmount); } function redeem(uint256 _amount) external returns (uint256) { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( address(this), _amount, TOKEN ); __swapAssets(msg.sender, address(this), _amount, ETH_ADDRESS, destAmount); return _amount; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../../../interfaces/ICurveAddressProvider.sol"; import "../../../../interfaces/ICurveSwapsERC20.sol"; import "../../../../interfaces/ICurveSwapsEther.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title CurveExchangeAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for swapping assets on Curve <https://www.curve.fi/> contract CurveExchangeAdapter is AdapterBase { address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address private immutable ADDRESS_PROVIDER; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _addressProvider, address _wethToken ) public AdapterBase(_integrationManager) { ADDRESS_PROVIDER = _addressProvider; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH from swap and to unwrap WETH receive() external payable {} // EXTERNAL FUNCTIONS /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "CURVE_EXCHANGE"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid"); ( address pool, address outgoingAsset, uint256 outgoingAssetAmount, address incomingAsset, uint256 minIncomingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); require(pool != address(0), "parseAssetsForMethod: No pool address provided"); spendAssets_ = new address[](1); spendAssets_[0] = outgoingAsset; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = outgoingAssetAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = incomingAsset; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIncomingAssetAmount; return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Trades assets on Curve /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters function takeOrder( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata ) external onlyIntegrationManager { ( address pool, address outgoingAsset, uint256 outgoingAssetAmount, address incomingAsset, uint256 minIncomingAssetAmount ) = __decodeCallArgs(_encodedCallArgs); address swaps = ICurveAddressProvider(ADDRESS_PROVIDER).get_address(2); __takeOrder( _vaultProxy, swaps, pool, outgoingAsset, outgoingAssetAmount, incomingAsset, minIncomingAssetAmount ); } // PRIVATE FUNCTIONS /// @dev Helper to decode the take order encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address pool_, address outgoingAsset_, uint256 outgoingAssetAmount_, address incomingAsset_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, address, uint256, address, uint256)); } /// @dev Helper to execute takeOrder. Avoids stack-too-deep error. function __takeOrder( address _vaultProxy, address _swaps, address _pool, address _outgoingAsset, uint256 _outgoingAssetAmount, address _incomingAsset, uint256 _minIncomingAssetAmount ) private { if (_outgoingAsset == WETH_TOKEN) { IWETH(WETH_TOKEN).withdraw(_outgoingAssetAmount); ICurveSwapsEther(_swaps).exchange{value: _outgoingAssetAmount}( _pool, ETH_ADDRESS, _incomingAsset, _outgoingAssetAmount, _minIncomingAssetAmount, _vaultProxy ); } else if (_incomingAsset == WETH_TOKEN) { __approveMaxAsNeeded(_outgoingAsset, _swaps, _outgoingAssetAmount); ICurveSwapsERC20(_swaps).exchange( _pool, _outgoingAsset, ETH_ADDRESS, _outgoingAssetAmount, _minIncomingAssetAmount, address(this) ); // wrap received ETH and send back to the vault uint256 receivedAmount = payable(address(this)).balance; IWETH(payable(WETH_TOKEN)).deposit{value: receivedAmount}(); ERC20(WETH_TOKEN).safeTransfer(_vaultProxy, receivedAmount); } else { __approveMaxAsNeeded(_outgoingAsset, _swaps, _outgoingAssetAmount); ICurveSwapsERC20(_swaps).exchange( _pool, _outgoingAsset, _incomingAsset, _outgoingAssetAmount, _minIncomingAssetAmount, _vaultProxy ); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `ADDRESS_PROVIDER` variable /// @return addressProvider_ The `ADDRESS_PROVIDER` variable value function getAddressProvider() external view returns (address addressProvider_) { return ADDRESS_PROVIDER; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveSwapsERC20 Interface /// @author Enzyme Council <[email protected]> interface ICurveSwapsERC20 { function exchange( address, address, address, uint256, uint256, address ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title ICurveSwapsEther Interface /// @author Enzyme Council <[email protected]> interface ICurveSwapsEther { function exchange( address, address, address, uint256, uint256, address ) external payable returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../../IDerivativePriceFeed.sol"; import "./SingleUnderlyingDerivativeRegistryMixin.sol"; /// @title PeggedDerivativesPriceFeedBase Contract /// @author Enzyme Council <[email protected]> /// @notice Price feed base for multiple derivatives that are pegged 1:1 to their underlyings, /// and have the same decimals as their underlying abstract contract PeggedDerivativesPriceFeedBase is IDerivativePriceFeed, SingleUnderlyingDerivativeRegistryMixin { constructor(address _dispatcher) public SingleUnderlyingDerivativeRegistryMixin(_dispatcher) {} /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { address underlying = getUnderlyingForDerivative(_derivative); require(underlying != address(0), "calcUnderlyingValues: Not a supported derivative"); underlyings_ = new address[](1); underlyings_[0] = underlying; underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount; return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return getUnderlyingForDerivative(_asset) != address(0); } /// @dev Provides validation that the derivative and underlying have the same decimals. /// Can be overrode by the inheriting price feed using super() to implement further validation. function __validateDerivative(address _derivative, address _underlying) internal virtual override { require( ERC20(_derivative).decimals() == ERC20(_underlying).decimals(), "__validateDerivative: Unequal decimals" ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../utils/DispatcherOwnerMixin.sol"; /// @title SingleUnderlyingDerivativeRegistryMixin Contract /// @author Enzyme Council <[email protected]> /// @notice Mixin for derivative price feeds that handle multiple derivatives /// that each have a single underlying asset abstract contract SingleUnderlyingDerivativeRegistryMixin is DispatcherOwnerMixin { event DerivativeAdded(address indexed derivative, address indexed underlying); event DerivativeRemoved(address indexed derivative); mapping(address => address) private derivativeToUnderlying; constructor(address _dispatcher) public DispatcherOwnerMixin(_dispatcher) {} /// @notice Adds derivatives with corresponding underlyings to the price feed /// @param _derivatives The derivatives to add /// @param _underlyings The corresponding underlyings to add function addDerivatives(address[] memory _derivatives, address[] memory _underlyings) external virtual onlyDispatcherOwner { require(_derivatives.length > 0, "addDerivatives: Empty _derivatives"); require(_derivatives.length == _underlyings.length, "addDerivatives: Unequal arrays"); for (uint256 i; i < _derivatives.length; i++) { require(_derivatives[i] != address(0), "addDerivatives: Empty derivative"); require(_underlyings[i] != address(0), "addDerivatives: Empty underlying"); require( getUnderlyingForDerivative(_derivatives[i]) == address(0), "addDerivatives: Value already set" ); __validateDerivative(_derivatives[i], _underlyings[i]); derivativeToUnderlying[_derivatives[i]] = _underlyings[i]; emit DerivativeAdded(_derivatives[i], _underlyings[i]); } } /// @notice Removes derivatives from the price feed /// @param _derivatives The derivatives to remove function removeDerivatives(address[] memory _derivatives) external onlyDispatcherOwner { require(_derivatives.length > 0, "removeDerivatives: Empty _derivatives"); for (uint256 i; i < _derivatives.length; i++) { require( getUnderlyingForDerivative(_derivatives[i]) != address(0), "removeDerivatives: Value not set" ); delete derivativeToUnderlying[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } /// @dev Optionally allow the inheriting price feed to validate the derivative-underlying pair function __validateDerivative(address, address) internal virtual { // UNIMPLEMENTED } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the underlying asset for a given derivative /// @param _derivative The derivative for which to get the underlying asset /// @return underlying_ The underlying asset function getUnderlyingForDerivative(address _derivative) public view returns (address underlying_) { return derivativeToUnderlying[_derivative]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../release/infrastructure/price-feeds/derivatives/feeds/utils/PeggedDerivativesPriceFeedBase.sol"; /// @title TestSingleUnderlyingDerivativeRegistry Contract /// @author Enzyme Council <[email protected]> /// @notice A test implementation of PeggedDerivativesPriceFeedBase contract TestPeggedDerivativesPriceFeed is PeggedDerivativesPriceFeedBase { constructor(address _dispatcher) public PeggedDerivativesPriceFeedBase(_dispatcher) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../release/infrastructure/price-feeds/derivatives/feeds/utils/SingleUnderlyingDerivativeRegistryMixin.sol"; /// @title TestSingleUnderlyingDerivativeRegistry Contract /// @author Enzyme Council <[email protected]> /// @notice A test implementation of SingleUnderlyingDerivativeRegistryMixin contract TestSingleUnderlyingDerivativeRegistry is SingleUnderlyingDerivativeRegistryMixin { constructor(address _dispatcher) public SingleUnderlyingDerivativeRegistryMixin(_dispatcher) {} } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../interfaces/IAaveProtocolDataProvider.sol"; import "./utils/PeggedDerivativesPriceFeedBase.sol"; /// @title AavePriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Aave contract AavePriceFeed is PeggedDerivativesPriceFeedBase { address private immutable PROTOCOL_DATA_PROVIDER; constructor(address _dispatcher, address _protocolDataProvider) public PeggedDerivativesPriceFeedBase(_dispatcher) { PROTOCOL_DATA_PROVIDER = _protocolDataProvider; } function __validateDerivative(address _derivative, address _underlying) internal override { super.__validateDerivative(_derivative, _underlying); (address aTokenAddress, , ) = IAaveProtocolDataProvider(PROTOCOL_DATA_PROVIDER) .getReserveTokensAddresses(_underlying); require( aTokenAddress == _derivative, "__validateDerivative: Invalid aToken or token provided" ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `PROTOCOL_DATA_PROVIDER` variable value /// @return protocolDataProvider_ The `PROTOCOL_DATA_PROVIDER` variable value function getProtocolDataProvider() external view returns (address protocolDataProvider_) { return PROTOCOL_DATA_PROVIDER; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAaveProtocolDataProvider interface /// @author Enzyme Council <[email protected]> interface IAaveProtocolDataProvider { function getReserveTokensAddresses(address) external view returns ( address, address, address ); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../infrastructure/price-feeds/derivatives/feeds/AavePriceFeed.sol"; import "../../../../interfaces/IAaveLendingPool.sol"; import "../../../../interfaces/IAaveLendingPoolAddressProvider.sol"; import "../utils/AdapterBase.sol"; /// @title AaveAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Aave Lending <https://aave.com/> contract AaveAdapter is AdapterBase { address private immutable AAVE_PRICE_FEED; address private immutable LENDING_POOL_ADDRESS_PROVIDER; uint16 private constant REFERRAL_CODE = 158; constructor( address _integrationManager, address _lendingPoolAddressProvider, address _aavePriceFeed ) public AdapterBase(_integrationManager) { LENDING_POOL_ADDRESS_PROVIDER = _lendingPoolAddressProvider; AAVE_PRICE_FEED = _aavePriceFeed; } /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "AAVE"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (address aToken, uint256 amount) = __decodeCallArgs(_encodedCallArgs); // Prevent from invalid token/aToken combination address token = AavePriceFeed(AAVE_PRICE_FEED).getUnderlyingForDerivative(aToken); require(token != address(0), "parseAssetsForMethod: Unsupported aToken"); spendAssets_ = new address[](1); spendAssets_[0] = token; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = amount; incomingAssets_ = new address[](1); incomingAssets_[0] = aToken; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = amount; } else if (_selector == REDEEM_SELECTOR) { (address aToken, uint256 amount) = __decodeCallArgs(_encodedCallArgs); // Prevent from invalid token/aToken combination address token = AavePriceFeed(AAVE_PRICE_FEED).getUnderlyingForDerivative(aToken); require(token != address(0), "parseAssetsForMethod: Unsupported aToken"); spendAssets_ = new address[](1); spendAssets_[0] = aToken; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = amount; incomingAssets_ = new address[](1); incomingAssets_[0] = token; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = amount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends an amount of a token to AAVE /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager { ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); address lendingPoolAddress = IAaveLendingPoolAddressProvider(LENDING_POOL_ADDRESS_PROVIDER) .getLendingPool(); __approveMaxAsNeeded(spendAssets[0], lendingPoolAddress, spendAssetAmounts[0]); IAaveLendingPool(lendingPoolAddress).deposit( spendAssets[0], spendAssetAmounts[0], _vaultProxy, REFERRAL_CODE ); } /// @notice Redeems an amount of aTokens from AAVE /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager { ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); address lendingPoolAddress = IAaveLendingPoolAddressProvider(LENDING_POOL_ADDRESS_PROVIDER) .getLendingPool(); __approveMaxAsNeeded(spendAssets[0], lendingPoolAddress, spendAssetAmounts[0]); IAaveLendingPool(lendingPoolAddress).withdraw( incomingAssets[0], spendAssetAmounts[0], _vaultProxy ); } // PRIVATE FUNCTIONS /// @dev Helper to decode callArgs for lend and redeem function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (address aToken, uint256 amount) { return abi.decode(_encodedCallArgs, (address, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `AAVE_PRICE_FEED` variable /// @return aavePriceFeed_ The `AAVE_PRICE_FEED` variable value function getAavePriceFeed() external view returns (address aavePriceFeed_) { return AAVE_PRICE_FEED; } /// @notice Gets the `LENDING_POOL_ADDRESS_PROVIDER` variable /// @return lendingPoolAddressProvider_ The `LENDING_POOL_ADDRESS_PROVIDER` variable value function getLendingPoolAddressProvider() external view returns (address lendingPoolAddressProvider_) { return LENDING_POOL_ADDRESS_PROVIDER; } /// @notice Gets the `REFERRAL_CODE` variable /// @return referralCode_ The `REFERRAL_CODE` variable value function getReferralCode() external pure returns (uint16 referralCode_) { return REFERRAL_CODE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAaveLendingPool interface /// @author Enzyme Council <[email protected]> interface IAaveLendingPool { function deposit( address, uint256, address, uint16 ) external; function withdraw( address, uint256, address ) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAaveLendingPoolAddressProvider interface /// @author Enzyme Council <[email protected]> interface IAaveLendingPoolAddressProvider { function getLendingPool() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../utils/AddressArrayLib.sol"; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PostCallOnIntegrationValidatePolicyBase.sol"; /// @title AssetWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of assets in a fund's holdings contract AssetWhitelist is PostCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { using AddressArrayLib for address[]; constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Validates and initializes a policy as necessary prior to fund activation /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyPolicyManager { require( passesRule(_comptrollerProxy, VaultLib(_vaultProxy).getTrackedAssets()), "activateForFund: Non-whitelisted asset detected" ); } /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { address[] memory assets = abi.decode(_encodedSettings, (address[])); require( assets.contains(ComptrollerLib(_comptrollerProxy).getDenominationAsset()), "addFundSettings: Must whitelist denominationAsset" ); __addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[]))); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ASSET_WHITELIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _assets The assets with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address[] memory _assets) public view returns (bool isValid_) { for (uint256 i; i < _assets.length; i++) { if (!isInList(_comptrollerProxy, _assets[i])) { return false; } } return true; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, incomingAssets); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; /// @title AddressListPolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice An abstract mixin contract for policies that use an address list abstract contract AddressListPolicyMixin { using EnumerableSet for EnumerableSet.AddressSet; event AddressesAdded(address indexed comptrollerProxy, address[] items); event AddressesRemoved(address indexed comptrollerProxy, address[] items); mapping(address => EnumerableSet.AddressSet) private comptrollerProxyToList; // EXTERNAL FUNCTIONS /// @notice Get all addresses in a fund's list /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @return list_ The addresses in the fund's list function getList(address _comptrollerProxy) external view returns (address[] memory list_) { list_ = new address[](comptrollerProxyToList[_comptrollerProxy].length()); for (uint256 i = 0; i < list_.length; i++) { list_[i] = comptrollerProxyToList[_comptrollerProxy].at(i); } return list_; } // PUBLIC FUNCTIONS /// @notice Check if an address is in a fund's list /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _item The address to check against the list /// @return isInList_ True if the address is in the list function isInList(address _comptrollerProxy, address _item) public view returns (bool isInList_) { return comptrollerProxyToList[_comptrollerProxy].contains(_item); } // INTERNAL FUNCTIONS /// @dev Helper to add addresses to the calling fund's list function __addToList(address _comptrollerProxy, address[] memory _items) internal { require(_items.length > 0, "__addToList: No addresses provided"); for (uint256 i = 0; i < _items.length; i++) { require( comptrollerProxyToList[_comptrollerProxy].add(_items[i]), "__addToList: Address already exists in list" ); } emit AddressesAdded(_comptrollerProxy, _items); } /// @dev Helper to remove addresses from the calling fund's list function __removeFromList(address _comptrollerProxy, address[] memory _items) internal { require(_items.length > 0, "__removeFromList: No addresses provided"); for (uint256 i = 0; i < _items.length; i++) { require( comptrollerProxyToList[_comptrollerProxy].remove(_items[i]), "__removeFromList: Address does not exist in list" ); } emit AddressesRemoved(_comptrollerProxy, _items); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/comptroller/ComptrollerLib.sol"; import "../../../../core/fund/vault/VaultLib.sol"; import "../../../../utils/AddressArrayLib.sol"; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PostCallOnIntegrationValidatePolicyBase.sol"; /// @title AssetBlacklist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that disallows a configurable blacklist of assets in a fund's holdings contract AssetBlacklist is PostCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { using AddressArrayLib for address[]; constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Validates and initializes a policy as necessary prior to fund activation /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _vaultProxy The fund's VaultProxy address function activateForFund(address _comptrollerProxy, address _vaultProxy) external override onlyPolicyManager { require( passesRule(_comptrollerProxy, VaultLib(_vaultProxy).getTrackedAssets()), "activateForFund: Blacklisted asset detected" ); } /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { address[] memory assets = abi.decode(_encodedSettings, (address[])); require( !assets.contains(ComptrollerLib(_comptrollerProxy).getDenominationAsset()), "addFundSettings: Cannot blacklist denominationAsset" ); __addToList(_comptrollerProxy, assets); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ASSET_BLACKLIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _assets The assets with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address[] memory _assets) public view returns (bool isValid_) { for (uint256 i; i < _assets.length; i++) { if (isInList(_comptrollerProxy, _assets[i])) { return false; } } return true; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, incomingAssets); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PreCallOnIntegrationValidatePolicyBase.sol"; /// @title AdapterWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of adapters for use by a fund contract AdapterWhitelist is PreCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[]))); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ADAPTER_WHITELIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _adapter The adapter with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _adapter) public view returns (bool isValid_) { return isInList(_comptrollerProxy, _adapter); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address adapter, ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, adapter); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title CallOnIntegrationPreValidatePolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the PreCallOnIntegration policy hook abstract contract PreCallOnIntegrationValidatePolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.PreCallOnIntegration; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedRuleArgs) internal pure returns (address adapter_, bytes4 selector_) { return abi.decode(_encodedRuleArgs, (address, bytes4)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../utils/FundDeployerOwnerMixin.sol"; import "./utils/PreCallOnIntegrationValidatePolicyBase.sol"; /// @title GuaranteedRedemption Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that guarantees that shares will either be continuously redeemable or /// redeemable within a predictable daily window by preventing trading during a configurable daily period contract GuaranteedRedemption is PreCallOnIntegrationValidatePolicyBase, FundDeployerOwnerMixin { using SafeMath for uint256; event AdapterAdded(address adapter); event AdapterRemoved(address adapter); event FundSettingsSet( address indexed comptrollerProxy, uint256 startTimestamp, uint256 duration ); event RedemptionWindowBufferSet(uint256 prevBuffer, uint256 nextBuffer); struct RedemptionWindow { uint256 startTimestamp; uint256 duration; } uint256 private constant ONE_DAY = 24 * 60 * 60; mapping(address => bool) private adapterToCanBlockRedemption; mapping(address => RedemptionWindow) private comptrollerProxyToRedemptionWindow; uint256 private redemptionWindowBuffer; constructor( address _policyManager, address _fundDeployer, uint256 _redemptionWindowBuffer, address[] memory _redemptionBlockingAdapters ) public PolicyBase(_policyManager) FundDeployerOwnerMixin(_fundDeployer) { redemptionWindowBuffer = _redemptionWindowBuffer; __addRedemptionBlockingAdapters(_redemptionBlockingAdapters); } // EXTERNAL FUNCTIONS /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { (uint256 startTimestamp, uint256 duration) = abi.decode( _encodedSettings, (uint256, uint256) ); if (startTimestamp == 0) { require(duration == 0, "addFundSettings: duration must be 0 if startTimestamp is 0"); return; } // Use 23 hours instead of 1 day to allow up to 1 hr of redemptionWindowBuffer require( duration > 0 && duration <= 23 hours, "addFundSettings: duration must be between 1 second and 23 hours" ); comptrollerProxyToRedemptionWindow[_comptrollerProxy].startTimestamp = startTimestamp; comptrollerProxyToRedemptionWindow[_comptrollerProxy].duration = duration; emit FundSettingsSet(_comptrollerProxy, startTimestamp, duration); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "GUARANTEED_REDEMPTION"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _adapter The adapter for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _adapter) public view returns (bool isValid_) { if (!adapterCanBlockRedemption(_adapter)) { return true; } RedemptionWindow memory redemptionWindow = comptrollerProxyToRedemptionWindow[_comptrollerProxy]; // If no RedemptionWindow is set, the fund can never use redemption-blocking adapters if (redemptionWindow.startTimestamp == 0) { return false; } uint256 latestRedemptionWindowStart = calcLatestRedemptionWindowStart( redemptionWindow.startTimestamp ); // A fund can't trade during its redemption window, nor in the buffer beforehand. // The lower bound is only relevant when the startTimestamp is in the future, // so we check it last. if ( block.timestamp >= latestRedemptionWindowStart.add(redemptionWindow.duration) || block.timestamp <= latestRedemptionWindowStart.sub(redemptionWindowBuffer) ) { return true; } return false; } /// @notice Sets a new value for the redemptionWindowBuffer variable /// @param _nextRedemptionWindowBuffer The number of seconds for the redemptionWindowBuffer /// @dev The redemptionWindowBuffer is added to the beginning of the redemption window, /// and should always be >= the longest potential block on redemption amongst all adapters. /// (e.g., Synthetix blocks token transfers during a timelock after trading synths) function setRedemptionWindowBuffer(uint256 _nextRedemptionWindowBuffer) external onlyFundDeployerOwner { uint256 prevRedemptionWindowBuffer = redemptionWindowBuffer; require( _nextRedemptionWindowBuffer != prevRedemptionWindowBuffer, "setRedemptionWindowBuffer: Value already set" ); redemptionWindowBuffer = _nextRedemptionWindowBuffer; emit RedemptionWindowBufferSet(prevRedemptionWindowBuffer, _nextRedemptionWindowBuffer); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address adapter, ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, adapter); } // PUBLIC FUNCTIONS /// @notice Calculates the start of the most recent redemption window /// @param _startTimestamp The initial startTimestamp for the redemption window /// @return latestRedemptionWindowStart_ The starting timestamp of the most recent redemption window function calcLatestRedemptionWindowStart(uint256 _startTimestamp) public view returns (uint256 latestRedemptionWindowStart_) { if (block.timestamp <= _startTimestamp) { return _startTimestamp; } uint256 timeSinceStartTimestamp = block.timestamp.sub(_startTimestamp); uint256 timeSincePeriodStart = timeSinceStartTimestamp.mod(ONE_DAY); return block.timestamp.sub(timeSincePeriodStart); } /////////////////////////////////////////// // REDEMPTION-BLOCKING ADAPTERS REGISTRY // /////////////////////////////////////////// /// @notice Add adapters which can block shares redemption /// @param _adapters The addresses of adapters to be added function addRedemptionBlockingAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require( _adapters.length > 0, "__addRedemptionBlockingAdapters: _adapters cannot be empty" ); __addRedemptionBlockingAdapters(_adapters); } /// @notice Remove adapters which can block shares redemption /// @param _adapters The addresses of adapters to be removed function removeRedemptionBlockingAdapters(address[] calldata _adapters) external onlyFundDeployerOwner { require( _adapters.length > 0, "removeRedemptionBlockingAdapters: _adapters cannot be empty" ); for (uint256 i; i < _adapters.length; i++) { require( adapterCanBlockRedemption(_adapters[i]), "removeRedemptionBlockingAdapters: adapter is not added" ); adapterToCanBlockRedemption[_adapters[i]] = false; emit AdapterRemoved(_adapters[i]); } } /// @dev Helper to mark adapters that can block shares redemption function __addRedemptionBlockingAdapters(address[] memory _adapters) private { for (uint256 i; i < _adapters.length; i++) { require( _adapters[i] != address(0), "__addRedemptionBlockingAdapters: adapter cannot be empty" ); require( !adapterCanBlockRedemption(_adapters[i]), "__addRedemptionBlockingAdapters: adapter already added" ); adapterToCanBlockRedemption[_adapters[i]] = true; emit AdapterAdded(_adapters[i]); } } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `redemptionWindowBuffer` variable /// @return redemptionWindowBuffer_ The `redemptionWindowBuffer` variable value function getRedemptionWindowBuffer() external view returns (uint256 redemptionWindowBuffer_) { return redemptionWindowBuffer; } /// @notice Gets the RedemptionWindow settings for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return redemptionWindow_ The RedemptionWindow settings function getRedemptionWindowForFund(address _comptrollerProxy) external view returns (RedemptionWindow memory redemptionWindow_) { return comptrollerProxyToRedemptionWindow[_comptrollerProxy]; } /// @notice Checks whether an adapter can block shares redemption /// @param _adapter The address of the adapter to check /// @return canBlockRedemption_ True if the adapter can block shares redemption function adapterCanBlockRedemption(address _adapter) public view returns (bool canBlockRedemption_) { return adapterToCanBlockRedemption[_adapter]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PreCallOnIntegrationValidatePolicyBase.sol"; /// @title AdapterBlacklist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that disallows a configurable blacklist of adapters from use by a fund contract AdapterBlacklist is PreCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Add the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[]))); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "ADAPTER_BLACKLIST"; } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _adapter The adapter with which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _adapter) public view returns (bool isValid_) { return !isInList(_comptrollerProxy, _adapter); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address adapter, ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, adapter); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/PreBuySharesValidatePolicyBase.sol"; /// @title InvestorWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of investors to buy shares in a fund contract InvestorWhitelist is PreBuySharesValidatePolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Adds the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "INVESTOR_WHITELIST"; } /// @notice Updates the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function updateFundSettings( address _comptrollerProxy, address, bytes calldata _encodedSettings ) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _investor The investor for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _investor) public view returns (bool isValid_) { return isInList(_comptrollerProxy, _investor); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address buyer, , , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, buyer); } /// @dev Helper to update the investor whitelist by adding and/or removing addresses function __updateList(address _comptrollerProxy, bytes memory _settingsData) private { (address[] memory itemsToAdd, address[] memory itemsToRemove) = abi.decode( _settingsData, (address[], address[]) ); // If an address is in both add and remove arrays, they will not be in the final list. // We do not check for uniqueness between the two arrays for efficiency. if (itemsToAdd.length > 0) { __addToList(_comptrollerProxy, itemsToAdd); } if (itemsToRemove.length > 0) { __removeFromList(_comptrollerProxy, itemsToRemove); } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title BuySharesPolicyMixin Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the PreBuyShares policy hook abstract contract PreBuySharesValidatePolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.PreBuyShares; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedArgs) internal pure returns ( address buyer_, uint256 investmentAmount_, uint256 minSharesQuantity_, uint256 gav_ ) { return abi.decode(_encodedArgs, (address, uint256, uint256, uint256)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./utils/PreBuySharesValidatePolicyBase.sol"; /// @title MinMaxInvestment Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that restricts the amount of the fund's denomination asset that a user can /// send in a single call to buy shares in a fund contract MinMaxInvestment is PreBuySharesValidatePolicyBase { event FundSettingsSet( address indexed comptrollerProxy, uint256 minInvestmentAmount, uint256 maxInvestmentAmount ); struct FundSettings { uint256 minInvestmentAmount; uint256 maxInvestmentAmount; } mapping(address => FundSettings) private comptrollerProxyToFundSettings; constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Adds the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __setFundSettings(_comptrollerProxy, _encodedSettings); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "MIN_MAX_INVESTMENT"; } /// @notice Updates the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function updateFundSettings( address _comptrollerProxy, address, bytes calldata _encodedSettings ) external override onlyPolicyManager { __setFundSettings(_comptrollerProxy, _encodedSettings); } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _investmentAmount The investment amount for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, uint256 _investmentAmount) public view returns (bool isValid_) { uint256 minInvestmentAmount = comptrollerProxyToFundSettings[_comptrollerProxy] .minInvestmentAmount; uint256 maxInvestmentAmount = comptrollerProxyToFundSettings[_comptrollerProxy] .maxInvestmentAmount; // Both minInvestmentAmount and maxInvestmentAmount can be 0 in order to close the fund // temporarily if (minInvestmentAmount == 0) { return _investmentAmount <= maxInvestmentAmount; } else if (maxInvestmentAmount == 0) { return _investmentAmount >= minInvestmentAmount; } return _investmentAmount >= minInvestmentAmount && _investmentAmount <= maxInvestmentAmount; } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (, uint256 investmentAmount, , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, investmentAmount); } /// @dev Helper to set the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function __setFundSettings(address _comptrollerProxy, bytes memory _encodedSettings) private { (uint256 minInvestmentAmount, uint256 maxInvestmentAmount) = abi.decode( _encodedSettings, (uint256, uint256) ); require( maxInvestmentAmount == 0 || minInvestmentAmount < maxInvestmentAmount, "__setFundSettings: minInvestmentAmount must be less than maxInvestmentAmount" ); comptrollerProxyToFundSettings[_comptrollerProxy] .minInvestmentAmount = minInvestmentAmount; comptrollerProxyToFundSettings[_comptrollerProxy] .maxInvestmentAmount = maxInvestmentAmount; emit FundSettingsSet(_comptrollerProxy, minInvestmentAmount, maxInvestmentAmount); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the min and max investment amount for a given fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @return fundSettings_ The fund settings function getFundSettings(address _comptrollerProxy) external view returns (FundSettings memory fundSettings_) { return comptrollerProxyToFundSettings[_comptrollerProxy]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/AddressListPolicyMixin.sol"; import "./utils/BuySharesSetupPolicyBase.sol"; /// @title BuySharesCallerWhitelist Contract /// @author Enzyme Council <[email protected]> /// @notice A policy that only allows a configurable whitelist of buyShares callers for a fund contract BuySharesCallerWhitelist is BuySharesSetupPolicyBase, AddressListPolicyMixin { constructor(address _policyManager) public PolicyBase(_policyManager) {} /// @notice Adds the initial policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Provides a constant string identifier for a policy /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "BUY_SHARES_CALLER_WHITELIST"; } /// @notice Updates the policy settings for a fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedSettings Encoded settings to apply to a fund function updateFundSettings( address _comptrollerProxy, address, bytes calldata _encodedSettings ) external override onlyPolicyManager { __updateList(_comptrollerProxy, _encodedSettings); } /// @notice Checks whether a particular condition passes the rule for a particular fund /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _buySharesCaller The buyShares caller for which to check the rule /// @return isValid_ True if the rule passes function passesRule(address _comptrollerProxy, address _buySharesCaller) public view returns (bool isValid_) { return isInList(_comptrollerProxy, _buySharesCaller); } /// @notice Apply the rule with the specified parameters of a PolicyHook /// @param _comptrollerProxy The fund's ComptrollerProxy address /// @param _encodedArgs Encoded args with which to validate the rule /// @return isValid_ True if the rule passes function validateRule( address _comptrollerProxy, address, IPolicyManager.PolicyHook, bytes calldata _encodedArgs ) external override returns (bool isValid_) { (address caller, , ) = __decodeRuleArgs(_encodedArgs); return passesRule(_comptrollerProxy, caller); } /// @dev Helper to update the whitelist by adding and/or removing addresses function __updateList(address _comptrollerProxy, bytes memory _settingsData) private { (address[] memory itemsToAdd, address[] memory itemsToRemove) = abi.decode( _settingsData, (address[], address[]) ); // If an address is in both add and remove arrays, they will not be in the final list. // We do not check for uniqueness between the two arrays for efficiency. if (itemsToAdd.length > 0) { __addToList(_comptrollerProxy, itemsToAdd); } if (itemsToRemove.length > 0) { __removeFromList(_comptrollerProxy, itemsToRemove); } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/PolicyBase.sol"; /// @title BuySharesSetupPolicyBase Contract /// @author Enzyme Council <[email protected]> /// @notice A mixin contract for policies that only implement the BuySharesSetup policy hook abstract contract BuySharesSetupPolicyBase is PolicyBase { /// @notice Gets the implemented PolicyHooks for a policy /// @return implementedHooks_ The implemented PolicyHooks function implementedHooks() external view override returns (IPolicyManager.PolicyHook[] memory implementedHooks_) { implementedHooks_ = new IPolicyManager.PolicyHook[](1); implementedHooks_[0] = IPolicyManager.PolicyHook.BuySharesSetup; return implementedHooks_; } /// @notice Helper to decode rule arguments function __decodeRuleArgs(bytes memory _encodedArgs) internal pure returns ( address caller_, uint256[] memory investmentAmounts_, uint256 gav_ ) { return abi.decode(_encodedArgs, (address, uint256[], uint256)); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../core/fund/vault/VaultLib.sol"; import "../utils/AdapterBase.sol"; /// @title TrackedAssetsAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter to add tracked assets to a fund (useful e.g. to handle token airdrops) contract TrackedAssetsAdapter is AdapterBase { constructor(address _integrationManager) public AdapterBase(_integrationManager) {} /// @notice Add multiple assets to the Vault's list of tracked assets /// @dev No need to perform any validation or implement any logic function addTrackedAssets( address, bytes calldata, bytes calldata ) external view {} /// @notice Provides a constant string identifier for an adapter /// @return identifier_ The identifer string function identifier() external pure override returns (string memory identifier_) { return "TRACKED_ASSETS"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { require( _selector == ADD_TRACKED_ASSETS_SELECTOR, "parseAssetsForMethod: _selector invalid" ); incomingAssets_ = __decodeCallArgs(_encodedCallArgs); minIncomingAssetAmounts_ = new uint256[](incomingAssets_.length); for (uint256 i; i < minIncomingAssetAmounts_.length; i++) { minIncomingAssetAmounts_[i] = 1; } return ( spendAssetsHandleType_, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (address[] memory incomingAssets_) { return abi.decode(_encodedCallArgs, (address[])); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/ProxiableVaultLib.sol"; /// @title VaultProxy Contract /// @author Enzyme Council <[email protected]> /// @notice A proxy contract for all VaultProxy instances, slightly modified from EIP-1822 /// @dev Adapted from the recommended implementation of a Proxy in EIP-1822, updated for solc 0.6.12, /// and using the EIP-1967 storage slot for the proxiable implementation. /// i.e., `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, which is /// "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc" /// See: https://eips.ethereum.org/EIPS/eip-1822 contract VaultProxy { constructor(bytes memory _constructData, address _vaultLib) public { // "0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5" corresponds to // `bytes32(keccak256('mln.proxiable.vaultlib'))` require( bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) == ProxiableVaultLib(_vaultLib).proxiableUUID(), "constructor: _vaultLib not compatible" ); assembly { // solium-disable-line sstore(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _vaultLib) } (bool success, bytes memory returnData) = _vaultLib.delegatecall(_constructData); // solium-disable-line require(success, string(returnData)); } fallback() external payable { assembly { // solium-disable-line let contractLogic := sload( 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc ) calldatacopy(0x0, 0x0, calldatasize()) let success := delegatecall( sub(gas(), 10000), contractLogic, 0x0, calldatasize(), 0, 0 ) let retSz := returndatasize() returndatacopy(0, 0, retSz) switch success case 0 { revert(0, retSz) } default { return(0, retSz) } } } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/IMigrationHookHandler.sol"; import "../utils/IMigratableVault.sol"; import "../vault/VaultProxy.sol"; import "./IDispatcher.sol"; /// @title Dispatcher Contract /// @author Enzyme Council <[email protected]> /// @notice The top-level contract linking multiple releases. /// It handles the deployment of new VaultProxy instances, /// and the regulation of fund migration from a previous release to the current one. /// It can also be referred to for access-control based on this contract's owner. /// @dev DO NOT EDIT CONTRACT contract Dispatcher is IDispatcher { event CurrentFundDeployerSet(address prevFundDeployer, address nextFundDeployer); event MigrationCancelled( address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib, uint256 executableTimestamp ); event MigrationExecuted( address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib, uint256 executableTimestamp ); event MigrationSignaled( address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib, uint256 executableTimestamp ); event MigrationTimelockSet(uint256 prevTimelock, uint256 nextTimelock); event NominatedOwnerSet(address indexed nominatedOwner); event NominatedOwnerRemoved(address indexed nominatedOwner); event OwnershipTransferred(address indexed prevOwner, address indexed nextOwner); event MigrationInCancelHookFailed( bytes failureReturnData, address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib ); event MigrationOutHookFailed( bytes failureReturnData, IMigrationHookHandler.MigrationOutHook hook, address indexed vaultProxy, address indexed prevFundDeployer, address indexed nextFundDeployer, address nextVaultAccessor, address nextVaultLib ); event SharesTokenSymbolSet(string _nextSymbol); event VaultProxyDeployed( address indexed fundDeployer, address indexed owner, address vaultProxy, address indexed vaultLib, address vaultAccessor, string fundName ); struct MigrationRequest { address nextFundDeployer; address nextVaultAccessor; address nextVaultLib; uint256 executableTimestamp; } address private currentFundDeployer; address private nominatedOwner; address private owner; uint256 private migrationTimelock; string private sharesTokenSymbol; mapping(address => address) private vaultProxyToFundDeployer; mapping(address => MigrationRequest) private vaultProxyToMigrationRequest; modifier onlyCurrentFundDeployer() { require( msg.sender == currentFundDeployer, "Only the current FundDeployer can call this function" ); _; } modifier onlyOwner() { require(msg.sender == owner, "Only the contract owner can call this function"); _; } constructor() public { migrationTimelock = 2 days; owner = msg.sender; sharesTokenSymbol = "ENZF"; } ///////////// // GENERAL // ///////////// /// @notice Sets a new `symbol` value for VaultProxy instances /// @param _nextSymbol The symbol value to set function setSharesTokenSymbol(string calldata _nextSymbol) external override onlyOwner { sharesTokenSymbol = _nextSymbol; emit SharesTokenSymbolSet(_nextSymbol); } //////////////////// // ACCESS CONTROL // //////////////////// /// @notice Claim ownership of the contract function claimOwnership() external override { address nextOwner = nominatedOwner; require( msg.sender == nextOwner, "claimOwnership: Only the nominatedOwner can call this function" ); delete nominatedOwner; address prevOwner = owner; owner = nextOwner; emit OwnershipTransferred(prevOwner, nextOwner); } /// @notice Revoke the nomination of a new contract owner function removeNominatedOwner() external override onlyOwner { address removedNominatedOwner = nominatedOwner; require( removedNominatedOwner != address(0), "removeNominatedOwner: There is no nominated owner" ); delete nominatedOwner; emit NominatedOwnerRemoved(removedNominatedOwner); } /// @notice Set a new FundDeployer for use within the contract /// @param _nextFundDeployer The address of the FundDeployer contract function setCurrentFundDeployer(address _nextFundDeployer) external override onlyOwner { require( _nextFundDeployer != address(0), "setCurrentFundDeployer: _nextFundDeployer cannot be empty" ); require( __isContract(_nextFundDeployer), "setCurrentFundDeployer: Non-contract _nextFundDeployer" ); address prevFundDeployer = currentFundDeployer; require( _nextFundDeployer != prevFundDeployer, "setCurrentFundDeployer: _nextFundDeployer is already currentFundDeployer" ); currentFundDeployer = _nextFundDeployer; emit CurrentFundDeployerSet(prevFundDeployer, _nextFundDeployer); } /// @notice Nominate a new contract owner /// @param _nextNominatedOwner The account to nominate /// @dev Does not prohibit overwriting the current nominatedOwner function setNominatedOwner(address _nextNominatedOwner) external override onlyOwner { require( _nextNominatedOwner != address(0), "setNominatedOwner: _nextNominatedOwner cannot be empty" ); require( _nextNominatedOwner != owner, "setNominatedOwner: _nextNominatedOwner is already the owner" ); require( _nextNominatedOwner != nominatedOwner, "setNominatedOwner: _nextNominatedOwner is already nominated" ); nominatedOwner = _nextNominatedOwner; emit NominatedOwnerSet(_nextNominatedOwner); } /// @dev Helper to check whether an address is a deployed contract function __isContract(address _who) private view returns (bool isContract_) { uint256 size; assembly { size := extcodesize(_who) } return size > 0; } //////////////// // DEPLOYMENT // //////////////// /// @notice Deploys a VaultProxy /// @param _vaultLib The VaultLib library with which to instantiate the VaultProxy /// @param _owner The account to set as the VaultProxy's owner /// @param _vaultAccessor The account to set as the VaultProxy's permissioned accessor /// @param _fundName The name of the fund /// @dev Input validation should be handled by the VaultProxy during deployment function deployVaultProxy( address _vaultLib, address _owner, address _vaultAccessor, string calldata _fundName ) external override onlyCurrentFundDeployer returns (address vaultProxy_) { require(__isContract(_vaultAccessor), "deployVaultProxy: Non-contract _vaultAccessor"); bytes memory constructData = abi.encodeWithSelector( IMigratableVault.init.selector, _owner, _vaultAccessor, _fundName ); vaultProxy_ = address(new VaultProxy(constructData, _vaultLib)); address fundDeployer = msg.sender; vaultProxyToFundDeployer[vaultProxy_] = fundDeployer; emit VaultProxyDeployed( fundDeployer, _owner, vaultProxy_, _vaultLib, _vaultAccessor, _fundName ); return vaultProxy_; } //////////////// // MIGRATIONS // //////////////// /// @notice Cancels a pending migration request /// @param _vaultProxy The VaultProxy contract for which to cancel the migration request /// @param _bypassFailure True if a failure in either migration hook should be ignored /// @dev Because this function must also be callable by a permissioned migrator, it has an /// extra migration hook to the nextFundDeployer for the case where cancelMigration() /// is called directly (rather than via the nextFundDeployer). function cancelMigration(address _vaultProxy, bool _bypassFailure) external override { MigrationRequest memory request = vaultProxyToMigrationRequest[_vaultProxy]; address nextFundDeployer = request.nextFundDeployer; require(nextFundDeployer != address(0), "cancelMigration: No migration request exists"); // TODO: confirm that if canMigrate() does not exist but the caller is a valid FundDeployer, this still works. require( msg.sender == nextFundDeployer || IMigratableVault(_vaultProxy).canMigrate(msg.sender), "cancelMigration: Not an allowed caller" ); address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy]; address nextVaultAccessor = request.nextVaultAccessor; address nextVaultLib = request.nextVaultLib; uint256 executableTimestamp = request.executableTimestamp; delete vaultProxyToMigrationRequest[_vaultProxy]; __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PostCancel, _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); __invokeMigrationInCancelHook( _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); emit MigrationCancelled( _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, executableTimestamp ); } /// @notice Executes a pending migration request /// @param _vaultProxy The VaultProxy contract for which to execute the migration request /// @param _bypassFailure True if a failure in either migration hook should be ignored function executeMigration(address _vaultProxy, bool _bypassFailure) external override { MigrationRequest memory request = vaultProxyToMigrationRequest[_vaultProxy]; address nextFundDeployer = request.nextFundDeployer; require( nextFundDeployer != address(0), "executeMigration: No migration request exists for _vaultProxy" ); require( msg.sender == nextFundDeployer, "executeMigration: Only the target FundDeployer can call this function" ); require( nextFundDeployer == currentFundDeployer, "executeMigration: The target FundDeployer is no longer the current FundDeployer" ); uint256 executableTimestamp = request.executableTimestamp; require( block.timestamp >= executableTimestamp, "executeMigration: The migration timelock has not elapsed" ); address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy]; address nextVaultAccessor = request.nextVaultAccessor; address nextVaultLib = request.nextVaultLib; __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PreMigrate, _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); // Upgrade the VaultProxy to a new VaultLib and update the accessor via the new VaultLib IMigratableVault(_vaultProxy).setVaultLib(nextVaultLib); IMigratableVault(_vaultProxy).setAccessor(nextVaultAccessor); // Update the FundDeployer that migrated the VaultProxy vaultProxyToFundDeployer[_vaultProxy] = nextFundDeployer; // Remove the migration request delete vaultProxyToMigrationRequest[_vaultProxy]; __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PostMigrate, _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, _bypassFailure ); emit MigrationExecuted( _vaultProxy, prevFundDeployer, nextFundDeployer, nextVaultAccessor, nextVaultLib, executableTimestamp ); } /// @notice Sets a new migration timelock /// @param _nextTimelock The number of seconds for the new timelock function setMigrationTimelock(uint256 _nextTimelock) external override onlyOwner { uint256 prevTimelock = migrationTimelock; require( _nextTimelock != prevTimelock, "setMigrationTimelock: _nextTimelock is the current timelock" ); migrationTimelock = _nextTimelock; emit MigrationTimelockSet(prevTimelock, _nextTimelock); } /// @notice Signals a migration by creating a migration request /// @param _vaultProxy The VaultProxy contract for which to signal migration /// @param _nextVaultAccessor The account that will be the next `accessor` on the VaultProxy /// @param _nextVaultLib The next VaultLib library contract address to set on the VaultProxy /// @param _bypassFailure True if a failure in either migration hook should be ignored function signalMigration( address _vaultProxy, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) external override onlyCurrentFundDeployer { require( __isContract(_nextVaultAccessor), "signalMigration: Non-contract _nextVaultAccessor" ); address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy]; require(prevFundDeployer != address(0), "signalMigration: _vaultProxy does not exist"); address nextFundDeployer = msg.sender; require( nextFundDeployer != prevFundDeployer, "signalMigration: Can only migrate to a new FundDeployer" ); __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PreSignal, _vaultProxy, prevFundDeployer, nextFundDeployer, _nextVaultAccessor, _nextVaultLib, _bypassFailure ); uint256 executableTimestamp = block.timestamp + migrationTimelock; vaultProxyToMigrationRequest[_vaultProxy] = MigrationRequest({ nextFundDeployer: nextFundDeployer, nextVaultAccessor: _nextVaultAccessor, nextVaultLib: _nextVaultLib, executableTimestamp: executableTimestamp }); __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook.PostSignal, _vaultProxy, prevFundDeployer, nextFundDeployer, _nextVaultAccessor, _nextVaultLib, _bypassFailure ); emit MigrationSignaled( _vaultProxy, prevFundDeployer, nextFundDeployer, _nextVaultAccessor, _nextVaultLib, executableTimestamp ); } /// @dev Helper to invoke a MigrationInCancelHook on the next FundDeployer being "migrated in" to, /// which can optionally be implemented on the FundDeployer function __invokeMigrationInCancelHook( address _vaultProxy, address _prevFundDeployer, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) private { (bool success, bytes memory returnData) = _nextFundDeployer.call( abi.encodeWithSelector( IMigrationHookHandler.invokeMigrationInCancelHook.selector, _vaultProxy, _prevFundDeployer, _nextVaultAccessor, _nextVaultLib ) ); if (!success) { require( _bypassFailure, string(abi.encodePacked("MigrationOutCancelHook: ", returnData)) ); emit MigrationInCancelHookFailed( returnData, _vaultProxy, _prevFundDeployer, _nextFundDeployer, _nextVaultAccessor, _nextVaultLib ); } } /// @dev Helper to invoke a IMigrationHookHandler.MigrationOutHook on the previous FundDeployer being "migrated out" of, /// which can optionally be implemented on the FundDeployer function __invokeMigrationOutHook( IMigrationHookHandler.MigrationOutHook _hook, address _vaultProxy, address _prevFundDeployer, address _nextFundDeployer, address _nextVaultAccessor, address _nextVaultLib, bool _bypassFailure ) private { (bool success, bytes memory returnData) = _prevFundDeployer.call( abi.encodeWithSelector( IMigrationHookHandler.invokeMigrationOutHook.selector, _hook, _vaultProxy, _nextFundDeployer, _nextVaultAccessor, _nextVaultLib ) ); if (!success) { require( _bypassFailure, string(abi.encodePacked(__migrationOutHookFailureReasonPrefix(_hook), returnData)) ); emit MigrationOutHookFailed( returnData, _hook, _vaultProxy, _prevFundDeployer, _nextFundDeployer, _nextVaultAccessor, _nextVaultLib ); } } /// @dev Helper to return a revert reason string prefix for a given MigrationOutHook function __migrationOutHookFailureReasonPrefix(IMigrationHookHandler.MigrationOutHook _hook) private pure returns (string memory failureReasonPrefix_) { if (_hook == IMigrationHookHandler.MigrationOutHook.PreSignal) { return "MigrationOutHook.PreSignal: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PostSignal) { return "MigrationOutHook.PostSignal: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PreMigrate) { return "MigrationOutHook.PreMigrate: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PostMigrate) { return "MigrationOutHook.PostMigrate: "; } if (_hook == IMigrationHookHandler.MigrationOutHook.PostCancel) { return "MigrationOutHook.PostCancel: "; } return ""; } /////////////////// // STATE GETTERS // /////////////////// // Provides several potentially helpful getters that are not strictly necessary /// @notice Gets the current FundDeployer that is allowed to deploy and migrate funds /// @return currentFundDeployer_ The current FundDeployer contract address function getCurrentFundDeployer() external view override returns (address currentFundDeployer_) { return currentFundDeployer; } /// @notice Gets the FundDeployer with which a given VaultProxy is associated /// @param _vaultProxy The VaultProxy instance /// @return fundDeployer_ The FundDeployer contract address function getFundDeployerForVaultProxy(address _vaultProxy) external view override returns (address fundDeployer_) { return vaultProxyToFundDeployer[_vaultProxy]; } /// @notice Gets the details of a pending migration request for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return nextFundDeployer_ The FundDeployer contract address from which the migration /// request was made /// @return nextVaultAccessor_ The account that will be the next `accessor` on the VaultProxy /// @return nextVaultLib_ The next VaultLib library contract address to set on the VaultProxy /// @return executableTimestamp_ The timestamp at which the migration request can be executed function getMigrationRequestDetailsForVaultProxy(address _vaultProxy) external view override returns ( address nextFundDeployer_, address nextVaultAccessor_, address nextVaultLib_, uint256 executableTimestamp_ ) { MigrationRequest memory r = vaultProxyToMigrationRequest[_vaultProxy]; if (r.executableTimestamp > 0) { return ( r.nextFundDeployer, r.nextVaultAccessor, r.nextVaultLib, r.executableTimestamp ); } } /// @notice Gets the amount of time that must pass between signaling and executing a migration /// @return migrationTimelock_ The timelock value (in seconds) function getMigrationTimelock() external view override returns (uint256 migrationTimelock_) { return migrationTimelock; } /// @notice Gets the account that is nominated to be the next owner of this contract /// @return nominatedOwner_ The account that is nominated to be the owner function getNominatedOwner() external view override returns (address nominatedOwner_) { return nominatedOwner; } /// @notice Gets the owner of this contract /// @return owner_ The account that is the owner function getOwner() external view override returns (address owner_) { return owner; } /// @notice Gets the shares token `symbol` value for use in VaultProxy instances /// @return sharesTokenSymbol_ The `symbol` value function getSharesTokenSymbol() external view override returns (string memory sharesTokenSymbol_) { return sharesTokenSymbol; } /// @notice Gets the time remaining until the migration request of a given VaultProxy can be executed /// @param _vaultProxy The VaultProxy instance /// @return secondsRemaining_ The number of seconds remaining on the timelock function getTimelockRemainingForMigrationRequest(address _vaultProxy) external view override returns (uint256 secondsRemaining_) { uint256 executableTimestamp = vaultProxyToMigrationRequest[_vaultProxy] .executableTimestamp; if (executableTimestamp == 0) { return 0; } if (block.timestamp >= executableTimestamp) { return 0; } return executableTimestamp - block.timestamp; } /// @notice Checks whether a migration request that is executable exists for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return hasExecutableRequest_ True if a migration request exists and is executable function hasExecutableMigrationRequest(address _vaultProxy) external view override returns (bool hasExecutableRequest_) { uint256 executableTimestamp = vaultProxyToMigrationRequest[_vaultProxy] .executableTimestamp; return executableTimestamp > 0 && block.timestamp >= executableTimestamp; } /// @notice Checks whether a migration request exists for a given VaultProxy /// @param _vaultProxy The VaultProxy instance /// @return hasMigrationRequest_ True if a migration request exists function hasMigrationRequest(address _vaultProxy) external view override returns (bool hasMigrationRequest_) { return vaultProxyToMigrationRequest[_vaultProxy].executableTimestamp > 0; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../persistent/vault/VaultLibBaseCore.sol"; /// @title MockVaultLib Contract /// @author Enzyme Council <[email protected]> /// @notice A mock VaultLib implementation that only extends VaultLibBaseCore contract MockVaultLib is VaultLibBaseCore { function getAccessor() external view returns (address) { return accessor; } function getCreator() external view returns (address) { return creator; } function getMigrator() external view returns (address) { return migrator; } function getOwner() external view returns (address) { return owner; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity ^0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title ICERC20 Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for interactions with Compound tokens (cTokens) interface ICERC20 is IERC20 { function decimals() external view returns (uint8); function mint(uint256) external returns (uint256); function redeem(uint256) external returns (uint256); function exchangeRateStored() external view returns (uint256); function underlying() external returns (address); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/ICERC20.sol"; import "../../../utils/DispatcherOwnerMixin.sol"; import "../IDerivativePriceFeed.sol"; /// @title CompoundPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Compound Tokens (cTokens) contract CompoundPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin { using SafeMath for uint256; event CTokenAdded(address indexed cToken, address indexed token); uint256 private constant CTOKEN_RATE_DIVISOR = 10**18; mapping(address => address) private cTokenToToken; constructor( address _dispatcher, address _weth, address _ceth, address[] memory cERC20Tokens ) public DispatcherOwnerMixin(_dispatcher) { // Set cEth cTokenToToken[_ceth] = _weth; emit CTokenAdded(_ceth, _weth); // Set any other cTokens if (cERC20Tokens.length > 0) { __addCERC20Tokens(cERC20Tokens); } } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { underlyings_ = new address[](1); underlyings_[0] = cTokenToToken[_derivative]; require(underlyings_[0] != address(0), "calcUnderlyingValues: Unsupported derivative"); underlyingAmounts_ = new uint256[](1); // Returns a rate scaled to 10^18 underlyingAmounts_[0] = _derivativeAmount .mul(ICERC20(_derivative).exchangeRateStored()) .div(CTOKEN_RATE_DIVISOR); return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return cTokenToToken[_asset] != address(0); } ////////////////////// // CTOKENS REGISTRY // ////////////////////// /// @notice Adds cTokens to the price feed /// @param _cTokens cTokens to add /// @dev Only allows CERC20 tokens. CEther is set in the constructor. function addCTokens(address[] calldata _cTokens) external onlyDispatcherOwner { __addCERC20Tokens(_cTokens); } /// @dev Helper to add cTokens function __addCERC20Tokens(address[] memory _cTokens) private { require(_cTokens.length > 0, "__addCTokens: Empty _cTokens"); for (uint256 i; i < _cTokens.length; i++) { require(cTokenToToken[_cTokens[i]] == address(0), "__addCTokens: Value already set"); address token = ICERC20(_cTokens[i]).underlying(); cTokenToToken[_cTokens[i]] = token; emit CTokenAdded(_cTokens[i], token); } } //////////////////// // STATE GETTERS // /////////////////// /// @notice Returns the underlying asset of a given cToken /// @param _cToken The cToken for which to get the underlying asset /// @return token_ The underlying token function getTokenFromCToken(address _cToken) public view returns (address token_) { return cTokenToToken[_cToken]; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../infrastructure/price-feeds/derivatives/feeds/CompoundPriceFeed.sol"; import "../../../../interfaces/ICERC20.sol"; import "../../../../interfaces/ICEther.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title CompoundAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Compound <https://compound.finance/> contract CompoundAdapter is AdapterBase { address private immutable COMPOUND_PRICE_FEED; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _compoundPriceFeed, address _wethToken ) public AdapterBase(_integrationManager) { COMPOUND_PRICE_FEED = _compoundPriceFeed; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH during cEther lend/redeem receive() external payable {} /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "COMPOUND"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (address cToken, uint256 tokenAmount, uint256 minCTokenAmount) = __decodeCallArgs( _encodedCallArgs ); address token = CompoundPriceFeed(COMPOUND_PRICE_FEED).getTokenFromCToken(cToken); require(token != address(0), "parseAssetsForMethod: Unsupported cToken"); spendAssets_ = new address[](1); spendAssets_[0] = token; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = tokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = cToken; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minCTokenAmount; } else if (_selector == REDEEM_SELECTOR) { (address cToken, uint256 cTokenAmount, uint256 minTokenAmount) = __decodeCallArgs( _encodedCallArgs ); address token = CompoundPriceFeed(COMPOUND_PRICE_FEED).getTokenFromCToken(cToken); require(token != address(0), "parseAssetsForMethod: Unsupported cToken"); spendAssets_ = new address[](1); spendAssets_[0] = cToken; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = cTokenAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = token; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minTokenAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends an amount of a token to Compound /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { // More efficient to parse all from _encodedAssetTransferArgs ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); if (spendAssets[0] == WETH_TOKEN) { IWETH(WETH_TOKEN).withdraw(spendAssetAmounts[0]); ICEther(incomingAssets[0]).mint{value: spendAssetAmounts[0]}(); } else { __approveMaxAsNeeded(spendAssets[0], incomingAssets[0], spendAssetAmounts[0]); ICERC20(incomingAssets[0]).mint(spendAssetAmounts[0]); } } /// @notice Redeems an amount of cTokens from Compound /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { // More efficient to parse all from _encodedAssetTransferArgs ( , address[] memory spendAssets, uint256[] memory spendAssetAmounts, address[] memory incomingAssets ) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs); ICERC20(spendAssets[0]).redeem(spendAssetAmounts[0]); if (incomingAssets[0] == WETH_TOKEN) { IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } } // PRIVATE FUNCTIONS /// @dev Helper to decode callArgs for lend and redeem function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns ( address cToken_, uint256 outgoingAssetAmount_, uint256 minIncomingAssetAmount_ ) { return abi.decode(_encodedCallArgs, (address, uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `COMPOUND_PRICE_FEED` variable /// @return compoundPriceFeed_ The `COMPOUND_PRICE_FEED` variable value function getCompoundPriceFeed() external view returns (address compoundPriceFeed_) { return COMPOUND_PRICE_FEED; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity ^0.6.12; /// @title ICEther Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for interactions with Compound Ether interface ICEther { function mint() external payable; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title IChai Interface /// @author Enzyme Council <[email protected]> /// @notice Minimal interface for our interactions with the Chai contract interface IChai is IERC20 { function exit(address, uint256) external; function join(address, uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../interfaces/IChai.sol"; import "../utils/AdapterBase.sol"; /// @title ChaiAdapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Chai <https://github.com/dapphub/chai> contract ChaiAdapter is AdapterBase { address private immutable CHAI; address private immutable DAI; constructor( address _integrationManager, address _chai, address _dai ) public AdapterBase(_integrationManager) { CHAI = _chai; DAI = _dai; } /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "CHAI"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (uint256 daiAmount, uint256 minChaiAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = DAI; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = daiAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = CHAI; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minChaiAmount; } else if (_selector == REDEEM_SELECTOR) { (uint256 chaiAmount, uint256 minDaiAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = CHAI; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = chaiAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = DAI; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minDaiAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lend Dai for Chai /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 daiAmount, ) = __decodeCallArgs(_encodedCallArgs); __approveMaxAsNeeded(DAI, CHAI, daiAmount); // Execute Lend on Chai // Chai.join allows specifying the vaultProxy as the destination of Chai tokens IChai(CHAI).join(_vaultProxy, daiAmount); } /// @notice Redeem Chai for Dai /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 chaiAmount, ) = __decodeCallArgs(_encodedCallArgs); // Execute redeem on Chai // Chai.exit sends Dai back to the adapter IChai(CHAI).exit(address(this), chaiAmount); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingAmount_, uint256 minIncomingAmount_) { return abi.decode(_encodedCallArgs, (uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `CHAI` variable value /// @return chai_ The `CHAI` variable value function getChai() external view returns (address chai_) { return CHAI; } /// @notice Gets the `DAI` variable value /// @return dai_ The `DAI` variable value function getDai() external view returns (address dai_) { return DAI; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../utils/SwapperBase.sol"; contract MockGenericIntegratee is SwapperBase { function swap( address[] calldata _assetsToIntegratee, uint256[] calldata _assetsToIntegrateeAmounts, address[] calldata _assetsFromIntegratee, uint256[] calldata _assetsFromIntegrateeAmounts ) external payable { __swap( msg.sender, _assetsToIntegratee, _assetsToIntegrateeAmounts, _assetsFromIntegratee, _assetsFromIntegrateeAmounts ); } function swapOnBehalf( address payable _trader, address[] calldata _assetsToIntegratee, uint256[] calldata _assetsToIntegrateeAmounts, address[] calldata _assetsFromIntegratee, uint256[] calldata _assetsFromIntegrateeAmounts ) external payable { __swap( _trader, _assetsToIntegratee, _assetsToIntegrateeAmounts, _assetsFromIntegratee, _assetsFromIntegrateeAmounts ); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../prices/CentralizedRateProvider.sol"; import "../tokens/MockToken.sol"; import "../utils/SwapperBase.sol"; contract MockChaiIntegratee is MockToken, SwapperBase { address private immutable CENTRALIZED_RATE_PROVIDER; address public immutable DAI; constructor( address _dai, address _centralizedRateProvider, uint8 _decimals ) public MockToken("Chai", "CHAI", _decimals) { _setupDecimals(_decimals); CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider; DAI = _dai; } function join(address, uint256 _daiAmount) external { uint256 tokenDecimals = ERC20(DAI).decimals(); uint256 chaiDecimals = decimals(); // Calculate the amount of tokens per one unit of DAI uint256 daiPerChaiUnit = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER) .calcLiveAssetValue(address(this), 10**uint256(chaiDecimals), DAI); // Calculate the inverse rate to know the amount of CHAI to return from a unit of DAI uint256 inverseRate = uint256(10**tokenDecimals).mul(10**uint256(chaiDecimals)).div( daiPerChaiUnit ); // Mint and send those CHAI to sender uint256 destAmount = _daiAmount.mul(inverseRate).div(10**tokenDecimals); _mint(address(this), destAmount); __swapAssets(msg.sender, DAI, _daiAmount, address(this), destAmount); } function exit(address payable _trader, uint256 _chaiAmount) external { uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue( address(this), _chaiAmount, DAI ); // Burn CHAI of the trader. _burn(_trader, _chaiAmount); // Release DAI to the trader. ERC20(DAI).transfer(msg.sender, destAmount); } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../../../interfaces/IAlphaHomoraV1Bank.sol"; import "../../../../interfaces/IWETH.sol"; import "../utils/AdapterBase.sol"; /// @title AlphaHomoraV1Adapter Contract /// @author Enzyme Council <[email protected]> /// @notice Adapter for Alpha Homora v1 <https://alphafinance.io/> contract AlphaHomoraV1Adapter is AdapterBase { address private immutable IBETH_TOKEN; address private immutable WETH_TOKEN; constructor( address _integrationManager, address _ibethToken, address _wethToken ) public AdapterBase(_integrationManager) { IBETH_TOKEN = _ibethToken; WETH_TOKEN = _wethToken; } /// @dev Needed to receive ETH during redemption receive() external payable {} /// @notice Provides a constant string identifier for an adapter /// @return identifier_ An identifier string function identifier() external pure override returns (string memory identifier_) { return "ALPHA_HOMORA_V1"; } /// @notice Parses the expected assets to receive from a call on integration /// @param _selector The function selector for the callOnIntegration /// @param _encodedCallArgs The encoded parameters for the callOnIntegration /// @return spendAssetsHandleType_ A type that dictates how to handle granting /// the adapter access to spend assets (`None` by default) /// @return spendAssets_ The assets to spend in the call /// @return spendAssetAmounts_ The max asset amounts to spend in the call /// @return incomingAssets_ The assets to receive in the call /// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs) external view override returns ( IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_, address[] memory spendAssets_, uint256[] memory spendAssetAmounts_, address[] memory incomingAssets_, uint256[] memory minIncomingAssetAmounts_ ) { if (_selector == LEND_SELECTOR) { (uint256 wethAmount, uint256 minIbethAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = WETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = wethAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = IBETH_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minIbethAmount; } else if (_selector == REDEEM_SELECTOR) { (uint256 ibethAmount, uint256 minWethAmount) = __decodeCallArgs(_encodedCallArgs); spendAssets_ = new address[](1); spendAssets_[0] = IBETH_TOKEN; spendAssetAmounts_ = new uint256[](1); spendAssetAmounts_[0] = ibethAmount; incomingAssets_ = new address[](1); incomingAssets_[0] = WETH_TOKEN; minIncomingAssetAmounts_ = new uint256[](1); minIncomingAssetAmounts_[0] = minWethAmount; } else { revert("parseAssetsForMethod: _selector invalid"); } return ( IIntegrationManager.SpendAssetsHandleType.Transfer, spendAssets_, spendAssetAmounts_, incomingAssets_, minIncomingAssetAmounts_ ); } /// @notice Lends WETH for ibETH /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function lend( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 wethAmount, ) = __decodeCallArgs(_encodedCallArgs); IWETH(payable(WETH_TOKEN)).withdraw(wethAmount); IAlphaHomoraV1Bank(IBETH_TOKEN).deposit{value: payable(address(this)).balance}(); } /// @notice Redeems ibETH for WETH /// @param _vaultProxy The VaultProxy of the calling fund /// @param _encodedCallArgs Encoded order parameters /// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive function redeem( address _vaultProxy, bytes calldata _encodedCallArgs, bytes calldata _encodedAssetTransferArgs ) external onlyIntegrationManager fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs) { (uint256 ibethAmount, ) = __decodeCallArgs(_encodedCallArgs); IAlphaHomoraV1Bank(IBETH_TOKEN).withdraw(ibethAmount); IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}(); } // PRIVATE FUNCTIONS /// @dev Helper to decode the encoded call arguments function __decodeCallArgs(bytes memory _encodedCallArgs) private pure returns (uint256 outgoingAmount_, uint256 minIncomingAmount_) { return abi.decode(_encodedCallArgs, (uint256, uint256)); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `IBETH_TOKEN` variable /// @return ibethToken_ The `IBETH_TOKEN` variable value function getIbethToken() external view returns (address ibethToken_) { return IBETH_TOKEN; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @title IAlphaHomoraV1Bank interface /// @author Enzyme Council <[email protected]> interface IAlphaHomoraV1Bank { function deposit() external payable; function totalETH() external view returns (uint256); function totalSupply() external view returns (uint256); function withdraw(uint256) external; } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IAlphaHomoraV1Bank.sol"; import "../IDerivativePriceFeed.sol"; /// @title AlphaHomoraV1PriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Alpha Homora v1 ibETH contract AlphaHomoraV1PriceFeed is IDerivativePriceFeed { using SafeMath for uint256; address private immutable IBETH_TOKEN; address private immutable WETH_TOKEN; constructor(address _ibethToken, address _wethToken) public { IBETH_TOKEN = _ibethToken; WETH_TOKEN = _wethToken; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only ibETH is supported"); underlyings_ = new address[](1); underlyings_[0] = WETH_TOKEN; underlyingAmounts_ = new uint256[](1); IAlphaHomoraV1Bank alphaHomoraBankContract = IAlphaHomoraV1Bank(IBETH_TOKEN); underlyingAmounts_[0] = _derivativeAmount.mul(alphaHomoraBankContract.totalETH()).div( alphaHomoraBankContract.totalSupply() ); return (underlyings_, underlyingAmounts_); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == IBETH_TOKEN; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `IBETH_TOKEN` variable /// @return ibethToken_ The `IBETH_TOKEN` variable value function getIbethToken() external view returns (address ibethToken_) { return IBETH_TOKEN; } /// @notice Gets the `WETH_TOKEN` variable /// @return wethToken_ The `WETH_TOKEN` variable value function getWethToken() external view returns (address wethToken_) { return WETH_TOKEN; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../../../../interfaces/IMakerDaoPot.sol"; import "../IDerivativePriceFeed.sol"; /// @title ChaiPriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Price source oracle for Chai contract ChaiPriceFeed is IDerivativePriceFeed { using SafeMath for uint256; uint256 private constant CHI_DIVISOR = 10**27; address private immutable CHAI; address private immutable DAI; address private immutable DSR_POT; constructor( address _chai, address _dai, address _dsrPot ) public { CHAI = _chai; DAI = _dai; DSR_POT = _dsrPot; } /// @notice Converts a given amount of a derivative to its underlying asset values /// @param _derivative The derivative to convert /// @param _derivativeAmount The amount of the derivative to convert /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount /// @dev Calculation based on Chai source: https://github.com/dapphub/chai/blob/master/src/chai.sol function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only Chai is supported"); underlyings_ = new address[](1); underlyings_[0] = DAI; underlyingAmounts_ = new uint256[](1); underlyingAmounts_[0] = _derivativeAmount.mul(IMakerDaoPot(DSR_POT).chi()).div( CHI_DIVISOR ); } /// @notice Checks if an asset is supported by the price feed /// @param _asset The asset to check /// @return isSupported_ True if the asset is supported function isSupportedAsset(address _asset) public view override returns (bool isSupported_) { return _asset == CHAI; } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `CHAI` variable value /// @return chai_ The `CHAI` variable value function getChai() external view returns (address chai_) { return CHAI; } /// @notice Gets the `DAI` variable value /// @return dai_ The `DAI` variable value function getDai() external view returns (address dai_) { return DAI; } /// @notice Gets the `DSR_POT` variable value /// @return dsrPot_ The `DSR_POT` variable value function getDsrPot() external view returns (address dsrPot_) { return DSR_POT; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; /// @notice Limited interface for Maker DSR's Pot contract /// @dev See DSR integration guide: https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr-integration-guide-01.md interface IMakerDaoPot { function chi() external view returns (uint256); function rho() external view returns (uint256); function drip() external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./FeeBase.sol"; /// @title EntranceRateFeeBase Contract /// @author Enzyme Council <[email protected]> /// @notice Calculates a fee based on a rate to be charged to an investor upon entering a fund abstract contract EntranceRateFeeBase is FeeBase { using SafeMath for uint256; event FundSettingsAdded(address indexed comptrollerProxy, uint256 rate); event Settled(address indexed comptrollerProxy, address indexed payer, uint256 sharesQuantity); uint256 private constant RATE_DIVISOR = 10**18; IFeeManager.SettlementType private immutable SETTLEMENT_TYPE; mapping(address => uint256) private comptrollerProxyToRate; constructor(address _feeManager, IFeeManager.SettlementType _settlementType) public FeeBase(_feeManager) { require( _settlementType == IFeeManager.SettlementType.Burn || _settlementType == IFeeManager.SettlementType.Direct, "constructor: Invalid _settlementType" ); SETTLEMENT_TYPE = _settlementType; } // EXTERNAL FUNCTIONS /// @notice Add the fee settings for a fund /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settingsData Encoded settings to apply to the policy for a fund function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external override onlyFeeManager { uint256 rate = abi.decode(_settingsData, (uint256)); require(rate > 0, "addFundSettings: Fee rate must be >0"); comptrollerProxyToRate[_comptrollerProxy] = rate; emit FundSettingsAdded(_comptrollerProxy, rate); } /// @notice Gets the hooks that are implemented by the fee /// @return implementedHooksForSettle_ The hooks during which settle() is implemented /// @return implementedHooksForUpdate_ The hooks during which update() is implemented /// @return usesGavOnSettle_ True if GAV is used during the settle() implementation /// @return usesGavOnUpdate_ True if GAV is used during the update() implementation /// @dev Used only during fee registration function implementedHooks() external view override returns ( IFeeManager.FeeHook[] memory implementedHooksForSettle_, IFeeManager.FeeHook[] memory implementedHooksForUpdate_, bool usesGavOnSettle_, bool usesGavOnUpdate_ ) { implementedHooksForSettle_ = new IFeeManager.FeeHook[](1); implementedHooksForSettle_[0] = IFeeManager.FeeHook.PostBuyShares; return (implementedHooksForSettle_, new IFeeManager.FeeHook[](0), false, false); } /// @notice Settles the fee /// @param _comptrollerProxy The ComptrollerProxy of the fund /// @param _settlementData Encoded args to use in calculating the settlement /// @return settlementType_ The type of settlement /// @return payer_ The payer of shares due /// @return sharesDue_ The amount of shares due function settle( address _comptrollerProxy, address, IFeeManager.FeeHook, bytes calldata _settlementData, uint256 ) external override onlyFeeManager returns ( IFeeManager.SettlementType settlementType_, address payer_, uint256 sharesDue_ ) { uint256 sharesBought; (payer_, , sharesBought) = __decodePostBuySharesSettlementData(_settlementData); uint256 rate = comptrollerProxyToRate[_comptrollerProxy]; sharesDue_ = sharesBought.mul(rate).div(RATE_DIVISOR.add(rate)); if (sharesDue_ == 0) { return (IFeeManager.SettlementType.None, address(0), 0); } emit Settled(_comptrollerProxy, payer_, sharesDue_); return (SETTLEMENT_TYPE, payer_, sharesDue_); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the `rate` variable for a fund /// @param _comptrollerProxy The ComptrollerProxy contract for the fund /// @return rate_ The `rate` variable value function getRateForFund(address _comptrollerProxy) external view returns (uint256 rate_) { return comptrollerProxyToRate[_comptrollerProxy]; } /// @notice Gets the `SETTLEMENT_TYPE` variable /// @return settlementType_ The `SETTLEMENT_TYPE` variable value function getSettlementType() external view returns (IFeeManager.SettlementType settlementType_) { return SETTLEMENT_TYPE; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/EntranceRateFeeBase.sol"; /// @title EntranceRateDirectFee Contract /// @author Enzyme Council <[email protected]> /// @notice An EntranceRateFee that transfers the fee shares to the fund manager contract EntranceRateDirectFee is EntranceRateFeeBase { constructor(address _feeManager) public EntranceRateFeeBase(_feeManager, IFeeManager.SettlementType.Direct) {} /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "ENTRANCE_RATE_DIRECT"; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "./utils/EntranceRateFeeBase.sol"; /// @title EntranceRateBurnFee Contract /// @author Enzyme Council <[email protected]> /// @notice An EntranceRateFee that burns the fee shares contract EntranceRateBurnFee is EntranceRateFeeBase { constructor(address _feeManager) public EntranceRateFeeBase(_feeManager, IFeeManager.SettlementType.Burn) {} /// @notice Provides a constant string identifier for a fee /// @return identifier_ The identifier string function identifier() external pure override returns (string memory identifier_) { return "ENTRANCE_RATE_BURN"; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; contract MockChaiPriceSource { using SafeMath for uint256; uint256 private chiStored = 10**27; uint256 private rhoStored = now; function drip() external returns (uint256) { require(now >= rhoStored, "drip: invalid now"); rhoStored = now; chiStored = chiStored.mul(99).div(100); return chi(); } //////////////////// // STATE GETTERS // /////////////////// function chi() public view returns (uint256) { return chiStored; } function rho() public view returns (uint256) { return rhoStored; } } // SPDX-License-Identifier: GPL-3.0 /* This file is part of the Enzyme Protocol. (c) Enzyme Council <[email protected]> For the full license information, please view the LICENSE file that was distributed with this source code. */ pragma solidity 0.6.12; import "../../utils/DispatcherOwnerMixin.sol"; import "./IAggregatedDerivativePriceFeed.sol"; /// @title AggregatedDerivativePriceFeed Contract /// @author Enzyme Council <[email protected]> /// @notice Aggregates multiple derivative price feeds (e.g., Compound, Chai) and dispatches /// rate requests to the appropriate feed contract AggregatedDerivativePriceFeed is IAggregatedDerivativePriceFeed, DispatcherOwnerMixin { event DerivativeAdded(address indexed derivative, address priceFeed); event DerivativeRemoved(address indexed derivative); event DerivativeUpdated( address indexed derivative, address prevPriceFeed, address nextPriceFeed ); mapping(address => address) private derivativeToPriceFeed; constructor( address _dispatcher, address[] memory _derivatives, address[] memory _priceFeeds ) public DispatcherOwnerMixin(_dispatcher) { if (_derivatives.length > 0) { __addDerivatives(_derivatives, _priceFeeds); } } /// @notice Gets the rates for 1 unit of the derivative to its underlying assets /// @param _derivative The derivative for which to get the rates /// @return underlyings_ The underlying assets for the _derivative /// @return underlyingAmounts_ The rates for the _derivative to the underlyings_ function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount) external override returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_) { address derivativePriceFeed = derivativeToPriceFeed[_derivative]; require( derivativePriceFeed != address(0), "calcUnderlyingValues: _derivative is not supported" ); return IDerivativePriceFeed(derivativePriceFeed).calcUnderlyingValues( _derivative, _derivativeAmount ); } /// @notice Checks whether an asset is a supported derivative /// @param _asset The asset to check /// @return isSupported_ True if the asset is a supported derivative /// @dev This should be as low-cost and simple as possible function isSupportedAsset(address _asset) external view override returns (bool isSupported_) { return derivativeToPriceFeed[_asset] != address(0); } ////////////////////////// // DERIVATIVES REGISTRY // ////////////////////////// /// @notice Adds a list of derivatives with the given price feed values /// @param _derivatives The derivatives to add /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function addDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds) external onlyDispatcherOwner { require(_derivatives.length > 0, "addDerivatives: _derivatives cannot be empty"); __addDerivatives(_derivatives, _priceFeeds); } /// @notice Removes a list of derivatives /// @param _derivatives The derivatives to remove function removeDerivatives(address[] calldata _derivatives) external onlyDispatcherOwner { require(_derivatives.length > 0, "removeDerivatives: _derivatives cannot be empty"); for (uint256 i = 0; i < _derivatives.length; i++) { require( derivativeToPriceFeed[_derivatives[i]] != address(0), "removeDerivatives: Derivative not yet added" ); delete derivativeToPriceFeed[_derivatives[i]]; emit DerivativeRemoved(_derivatives[i]); } } /// @notice Updates a list of derivatives with the given price feed values /// @param _derivatives The derivatives to update /// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives function updateDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds) external onlyDispatcherOwner { require(_derivatives.length > 0, "updateDerivatives: _derivatives cannot be empty"); require( _derivatives.length == _priceFeeds.length, "updateDerivatives: Unequal _derivatives and _priceFeeds array lengths" ); for (uint256 i = 0; i < _derivatives.length; i++) { address prevPriceFeed = derivativeToPriceFeed[_derivatives[i]]; require(prevPriceFeed != address(0), "updateDerivatives: Derivative not yet added"); require(_priceFeeds[i] != prevPriceFeed, "updateDerivatives: Value already set"); __validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]); derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i]; emit DerivativeUpdated(_derivatives[i], prevPriceFeed, _priceFeeds[i]); } } /// @dev Helper to add derivative-feed pairs function __addDerivatives(address[] memory _derivatives, address[] memory _priceFeeds) private { require( _derivatives.length == _priceFeeds.length, "__addDerivatives: Unequal _derivatives and _priceFeeds array lengths" ); for (uint256 i = 0; i < _derivatives.length; i++) { require( derivativeToPriceFeed[_derivatives[i]] == address(0), "__addDerivatives: Already added" ); __validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]); derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i]; emit DerivativeAdded(_derivatives[i], _priceFeeds[i]); } } /// @dev Helper to validate a derivative price feed function __validateDerivativePriceFeed(address _derivative, address _priceFeed) private view { require(_derivative != address(0), "__validateDerivativePriceFeed: Empty _derivative"); require(_priceFeed != address(0), "__validateDerivativePriceFeed: Empty _priceFeed"); require( IDerivativePriceFeed(_priceFeed).isSupportedAsset(_derivative), "__validateDerivativePriceFeed: Unsupported derivative" ); } /////////////////// // STATE GETTERS // /////////////////// /// @notice Gets the registered price feed for a given derivative /// @return priceFeed_ The price feed contract address function getPriceFeedForDerivative(address _derivative) external view override returns (address priceFeed_) { return derivativeToPriceFeed[_derivative]; } }
Provides a constant string identifier for an adapter return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) { return "CHAI"; }
1,698,254
./full_match/80001/0xC158A41ea8e573E0cE5B3e09FDEeB8ffbF35B1d7/sources/contracts/ERC721A.sol
See {IERC721Metadata-tokenURI}./
function tokenURI( uint256 tokenId ) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; }
857,419
./full_match/80001/0xdCdf0B3d68A4E11eF2703b87020dC5a9c66babf7/sources/@superfluid-finance/ethereum-contracts/contracts/apps/SuperTokenV1Library.sol
Increases the flow rate allowance for flow operator allowing userData to be a parameter here triggered stack too deep error token The token used in flow flowOperator The address whose flow rate allowance is increased addedFlowRateAllowance amount to increase allowance by/
function increaseFlowRateAllowance(ISuperToken token, address flowOperator, int96 addedFlowRateAllowance) internal returns (bool) { return increaseFlowRateAllowance(token, flowOperator, addedFlowRateAllowance, new bytes(0)); }
855,947
./full_match/80001/0xa85310809BF2CFdecC61b249048F5Db33bf8012c/sources/project_/contracts/Orderbook.sol
Decode calldata settleInfo & calldata priceUpdateData. pyth.updatePriceFeeds{value: pyth_fee}(priceUpdateData); PythStructs.Price memory closingPrice = pyth.getPrice( makersLegs[maker.order_ID][i].feedID );
function orderbook_settle_order( bytes calldata settleInfo, bytes[] calldata priceUpdateData, bytes32[] calldata maker_leg_feed_ids ) external onlyVault returns ( HDGXStructs.MakerOrder memory _maker, HDGXStructs.TakerOrder memory _taker, HDGXStructs.Payout memory _payout ) { (address sender, uint256 takerOrder_ID) = abi.decode( settleInfo, (address, uint256) ); HDGXStructs.TakerOrder memory taker = takerOrdersByID[takerOrder_ID]; HDGXStructs.MakerOrder memory maker = makerOrdersByID[ taker.makerOrder_ID ]; require( block.timestamp > (taker.timeStampTaken + maker.lockUpPeriod), "13" ); require(takerOrderIDSettled[takerOrder_ID] == false, "14"); require(priceUpdateData.length == maker.num_legs, "15"); uint256 pyth_fee = pyth.getUpdateFee(priceUpdateData); address payable winnerAddress; for (uint256 i = 0; i < maker.num_legs; i++) { makersClosingPrices[maker.order_ID].push( HDGXStructs.ClosePrice( makersLegs[maker.order_ID][i].feedID, historical_prices[i].price ) ); } bytes memory encodedForSettler = abi.encode( makersLegs[maker.order_ID], makersClosingPrices[maker.order_ID], maker, taker ); winnerAddress = Settler.settlement_evaluation(encodedForSettler); takerOrderIDSettled[takerOrder_ID] = true; HDGXStructs.Payout memory payout = Payout.orderbook_calculate_payout( winnerAddress, maker, taker ); takerSettleOrder[taker.order_ID] = HDGXStructs.SettleOrder( maker.order_ID, taker.order_ID, maker.user, taker.user, winnerAddress, sender, payout.maker_rebate, payout.settler_fee, payout.winning_payout, block.timestamp ); userSettlerFeesEarned[sender] += payout.settler_fee; return (maker, taker, payout); }
863,928
pragma solidity ^0.5.0; library Pairing { struct G1Point { uint X; uint Y; } // Encoding of field elements is: X[0] * z + X[1] struct G2Point { uint[2] X; uint[2] Y; } /// @return the generator of G1 function P1() internal pure returns (G1Point memory) { return G1Point(1, 2); } /// @return the generator of G2 function P2() internal pure returns (G2Point memory) { return G2Point( [11559732032986387107991004021392285783925812861821192530917403151452391805634, 10857046999023057135944570762232829481370756359578518086990519993285655852781], [4082367875863433681332203403145435568316851327593401208105741076214120093531, 8495653923123431417604973247489272438418190587263600148770280649306958101930] ); } /// @return the negation of p, i.e. p.add(p.negate()) should be zero. function negate(G1Point memory p) internal pure returns (G1Point memory) { // The prime q in the base field F_q for G1 uint q = 21888242871839275222246405745257275088696311157297823662689037894645226208583; if (p.X == 0 && p.Y == 0) return G1Point(0, 0); return G1Point(p.X, q - (p.Y % q)); } /// @return the sum of two points of G1 function pointAdd(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory r) { uint[4] memory input; input[0] = p1.X; input[1] = p1.Y; input[2] = p2.X; input[3] = p2.Y; bool success; assembly { success := staticcall(sub(gas, 2000), 6, input, 0xc0, r, 0x60) } require(success); } /// @return the product of a point on G1 and a scalar, i.e. /// p == p.mul(1) and p.add(p) == p.mul(2) for all points p. function pointMul(G1Point memory p, uint s) internal view returns (G1Point memory r) { uint[3] memory input; input[0] = p.X; input[1] = p.Y; input[2] = s; bool success; assembly { success := staticcall(sub(gas, 2000), 7, input, 0x80, r, 0x60) } require (success); } /// @return the result of computing the pairing check /// e(p1[0], p2[0]) * .... * e(p1[n], p2[n]) == 1 /// For example pairing([P1(), P1().negate()], [P2(), P2()]) should /// return true. function pairing(G1Point[] memory p1, G2Point[] memory p2) internal view returns (bool) { require(p1.length == p2.length); uint elements = p1.length; uint inputSize = elements * 6; uint[] memory input = new uint[](inputSize); for (uint i = 0; i < elements; i++) { input[i * 6 + 0] = p1[i].X; input[i * 6 + 1] = p1[i].Y; input[i * 6 + 2] = p2[i].X[0]; input[i * 6 + 3] = p2[i].X[1]; input[i * 6 + 4] = p2[i].Y[0]; input[i * 6 + 5] = p2[i].Y[1]; } uint[1] memory out; bool success; assembly { success := staticcall(sub(gas, 2000), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20) } require(success); return out[0] != 0; } /// Convenience method for a pairing check for two pairs. function pairingProd2(G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2) internal view returns (bool) { G1Point[] memory p1 = new G1Point[](2); G2Point[] memory p2 = new G2Point[](2); p1[0] = a1; p1[1] = b1; p2[0] = a2; p2[1] = b2; return pairing(p1, p2); } /// Convenience method for a pairing check for three pairs. function pairingProd3( G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2, G1Point memory c1, G2Point memory c2 ) internal view returns (bool) { G1Point[] memory p1 = new G1Point[](3); G2Point[] memory p2 = new G2Point[](3); p1[0] = a1; p1[1] = b1; p1[2] = c1; p2[0] = a2; p2[1] = b2; p2[2] = c2; return pairing(p1, p2); } /// Convenience method for a pairing check for four pairs. function pairingProd4( G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2, G1Point memory c1, G2Point memory c2, G1Point memory d1, G2Point memory d2 ) internal view returns (bool) { G1Point[] memory p1 = new G1Point[](4); G2Point[] memory p2 = new G2Point[](4); p1[0] = a1; p1[1] = b1; p1[2] = c1; p1[3] = d1; p2[0] = a2; p2[1] = b2; p2[2] = c2; p2[3] = d2; return pairing(p1, p2); } } library Verifier { using Pairing for Pairing.G1Point; using Pairing for Pairing.G2Point; function scalarField () internal pure returns (uint256) { return 21888242871839275222246405745257275088548364400416034343698204186575808495617; } struct VerifyingKey { Pairing.G1Point alpha; Pairing.G2Point beta; Pairing.G2Point gamma; Pairing.G2Point delta; Pairing.G1Point[] gammaABC; } struct Proof { Pairing.G1Point A; Pairing.G2Point B; Pairing.G1Point C; } struct ProofWithInput { Proof proof; uint256[] input; } function negateY( uint256 Y ) internal pure returns (uint256) { uint q = 21888242871839275222246405745257275088696311157297823662689037894645226208583; return q - (Y % q); } /* * This implements the Solidity equivalent of the following Python code: from py_ecc.bn128 import * data = # ... arguments to function [in_vk, vk_gammaABC, in_proof, proof_inputs] vk = [int(_, 16) for _ in data[0]] ic = [FQ(int(_, 16)) for _ in data[1]] proof = [int(_, 16) for _ in data[2]] inputs = [int(_, 16) for _ in data[3]] it = iter(ic) ic = [(_, next(it)) for _ in it] vk_alpha = [FQ(_) for _ in vk[:2]] vk_beta = (FQ2(vk[2:4][::-1]), FQ2(vk[4:6][::-1])) vk_gamma = (FQ2(vk[6:8][::-1]), FQ2(vk[8:10][::-1])) vk_delta = (FQ2(vk[10:12][::-1]), FQ2(vk[12:14][::-1])) assert is_on_curve(vk_alpha, b) assert is_on_curve(vk_beta, b2) assert is_on_curve(vk_gamma, b2) assert is_on_curve(vk_delta, b2) proof_A = [FQ(_) for _ in proof[:2]] proof_B = (FQ2(proof[2:4][::-1]), FQ2(proof[4:-2][::-1])) proof_C = [FQ(_) for _ in proof[-2:]] assert is_on_curve(proof_A, b) assert is_on_curve(proof_B, b2) assert is_on_curve(proof_C, b) vk_x = ic[0] for i, s in enumerate(inputs): vk_x = add(vk_x, multiply(ic[i + 1], s)) check_1 = pairing(proof_B, proof_A) check_2 = pairing(vk_beta, neg(vk_alpha)) check_3 = pairing(vk_gamma, neg(vk_x)) check_4 = pairing(vk_delta, neg(proof_C)) ok = check_1 * check_2 * check_3 * check_4 assert ok == FQ12.one() */ function verify (uint256[14] memory in_vk, uint256[] memory vk_gammaABC, uint256[8] memory in_proof, uint256[] memory proof_inputs) internal view returns (bool) { require( ((vk_gammaABC.length / 2) - 1) == proof_inputs.length ); // Compute the linear combination vk_x uint256[3] memory mul_input; uint256[4] memory add_input; bool success; uint m = 2; // First two fields are used as the sum add_input[0] = vk_gammaABC[0]; add_input[1] = vk_gammaABC[1]; // Performs a sum of gammaABC[0] + sum[ gammaABC[i+1]^proof_inputs[i] ] for (uint i = 0; i < proof_inputs.length; i++) { mul_input[0] = vk_gammaABC[m++]; mul_input[1] = vk_gammaABC[m++]; mul_input[2] = proof_inputs[i]; assembly { // ECMUL, output to last 2 elements of `add_input` success := staticcall(sub(gas, 2000), 7, mul_input, 0x80, add(add_input, 0x40), 0x60) } require(success); assembly { // ECADD success := staticcall(sub(gas, 2000), 6, add_input, 0xc0, add_input, 0x60) } require(success); } uint[24] memory input = [ // (proof.A, proof.B) in_proof[0], in_proof[1], // proof.A (G1) in_proof[2], in_proof[3], in_proof[4], in_proof[5], // proof.B (G2) // (-vk.alpha, vk.beta) in_vk[0], negateY(in_vk[1]), // -vk.alpha (G1) in_vk[2], in_vk[3], in_vk[4], in_vk[5], // vk.beta (G2) // (-vk_x, vk.gamma) add_input[0], negateY(add_input[1]), // -vk_x (G1) in_vk[6], in_vk[7], in_vk[8], in_vk[9], // vk.gamma (G2) // (-proof.C, vk.delta) in_proof[6], negateY(in_proof[7]), // -proof.C (G1) in_vk[10], in_vk[11], in_vk[12], in_vk[13] // vk.delta (G2) ]; uint[1] memory out; assembly { success := staticcall(sub(gas, 2000), 8, input, 768, out, 0x20) } require(success); return out[0] != 0; } function verify(VerifyingKey memory vk, ProofWithInput memory pwi) internal view returns (bool) { return verify(vk, pwi.proof, pwi.input); } function verify(VerifyingKey memory vk, Proof memory proof, uint256[] memory input) internal view returns (bool) { require(input.length + 1 == vk.gammaABC.length); // Compute the linear combination vk_x Pairing.G1Point memory vk_x = vk.gammaABC[0]; for (uint i = 0; i < input.length; i++) vk_x = Pairing.pointAdd(vk_x, Pairing.pointMul(vk.gammaABC[i + 1], input[i])); // Verify proof return Pairing.pairingProd4( proof.A, proof.B, vk_x.negate(), vk.gamma, proof.C.negate(), vk.delta, vk.alpha.negate(), vk.beta); } } library MiMC { function getScalarField () internal pure returns (uint256) { return 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001; } /** * MiMC-p/p with exponent of 7 * * Recommended at least 46 rounds, for a polynomial degree of 2^126 */ function MiMCpe7( uint256 in_x, uint256 in_k, uint256 in_seed, uint256 round_count ) internal pure returns(uint256 out_x) { assembly { if lt(round_count, 1) { revert(0, 0) } // Initialise round constants, k will be hashed let c := mload(0x40) mstore(0x40, add(c, 32)) mstore(c, in_seed) let localQ := 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001 let t let a // Further n-2 subsequent rounds include a round constant for { let i := round_count } gt(i, 0) { i := sub(i, 1) } { // c = H(c) mstore(c, keccak256(c, 32)) // x = pow(x + c_i, 7, p) + k t := addmod(addmod(in_x, mload(c), localQ), in_k, localQ) // t = x + c_i + k a := mulmod(t, t, localQ) // t^2 in_x := mulmod(mulmod(a, mulmod(a, a, localQ), localQ), t, localQ) // t^7 } // Result adds key again as blinding factor out_x := addmod(in_x, in_k, localQ) } } function MiMCpe7_mp( uint256[] memory in_x, uint256 in_k, uint256 in_seed, uint256 round_count ) internal pure returns (uint256) { uint256 r = in_k; uint256 localQ = 0x30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001; for( uint256 i = 0; i < in_x.length; i++ ) { r = (r + in_x[i] + MiMCpe7(in_x[i], r, in_seed, round_count)) % localQ; } // uint256 x0 = in_x[0]; // uint256 x1 = in_x[1]; // uint256 m0 = MiMCpe7(x0, r, in_seed, round_count); // assembly { // r := addmod(addmod(r, x0, localQ), m0, localQ) // } // uint256 m1 = MiMCpe7(x1, r, in_seed, round_count); // assembly { // r := addmod(addmod(r, x1, localQ), m1, localQ) // } return r; } function Hash( uint256[] memory in_msgs, uint256 in_key ) internal pure returns (uint256) { return MiMCpe7_mp(in_msgs, in_key, uint256(keccak256("mimc")), 91); } function Hash( uint256[] memory in_msgs ) internal pure returns (uint256) { return Hash(in_msgs, 0); } } library MerkleTree { // ceil(log2(1<<15)) uint constant internal TREE_DEPTH = 15; // 1<<15 leaves uint constant internal MAX_LEAF_COUNT = 32768; struct Data { uint cur; uint256[32768][16] nodes; // first column = leaves, second column = leaves' parents, etc } function treeDepth() internal pure returns (uint256) { return TREE_DEPTH; } function fillLevelIVs (uint256[15] memory IVs) internal pure { IVs[0] = 149674538925118052205057075966660054952481571156186698930522557832224430770; IVs[1] = 9670701465464311903249220692483401938888498641874948577387207195814981706974; IVs[2] = 18318710344500308168304415114839554107298291987930233567781901093928276468271; IVs[3] = 6597209388525824933845812104623007130464197923269180086306970975123437805179; IVs[4] = 21720956803147356712695575768577036859892220417043839172295094119877855004262; IVs[5] = 10330261616520855230513677034606076056972336573153777401182178891807369896722; IVs[6] = 17466547730316258748333298168566143799241073466140136663575045164199607937939; IVs[7] = 18881017304615283094648494495339883533502299318365959655029893746755475886610; IVs[8] = 21580915712563378725413940003372103925756594604076607277692074507345076595494; IVs[9] = 12316305934357579015754723412431647910012873427291630993042374701002287130550; IVs[10] = 18905410889238873726515380969411495891004493295170115920825550288019118582494; IVs[11] = 12819107342879320352602391015489840916114959026915005817918724958237245903353; IVs[12] = 8245796392944118634696709403074300923517437202166861682117022548371601758802; IVs[13] = 16953062784314687781686527153155644849196472783922227794465158787843281909585; IVs[14] = 19346880451250915556764413197424554385509847473349107460608536657852472800734; } function hashImpl (uint256 left, uint256 right, uint256 IV) internal pure returns (uint256) { uint256[] memory x = new uint256[](2); x[0] = left; x[1] = right; return MiMC.Hash(x, IV); } function insert(Data storage self, uint256 leaf) internal returns (uint256 new_root, uint256 offset) { require(leaf != 0); uint256[15] memory IVs; fillLevelIVs(IVs); offset = self.cur; require(offset != MAX_LEAF_COUNT - 1); self.nodes[0][offset] = leaf; new_root = updateTree(self, IVs); self.cur = offset + 1; } /** * Returns calculated merkle root */ function verifyPath(uint256 leaf, uint256[15] memory in_path, bool[15] memory address_bits) internal pure returns (uint256 merkleRoot) { uint256[15] memory IVs; fillLevelIVs(IVs); merkleRoot = leaf; for (uint depth = 0; depth < TREE_DEPTH; depth++) { if (address_bits[depth]) { merkleRoot = hashImpl(in_path[depth], merkleRoot, IVs[depth]); } else { merkleRoot = hashImpl(merkleRoot, in_path[depth], IVs[depth]); } } } function verifyPath(Data storage self, uint256 leaf, uint256[15] memory in_path, bool[15] memory address_bits) internal view returns (bool) { return verifyPath(leaf, in_path, address_bits) == getRoot(self); } function getLeaf(Data storage self, uint depth, uint offset) internal view returns (uint256) { return getUniqueLeaf(depth, offset, self.nodes[depth][offset]); } function getMerkleProof(Data storage self, uint index) internal view returns (uint256[15] memory proof_path) { for (uint depth = 0; depth < TREE_DEPTH; depth++) { if (index % 2 == 0) { proof_path[depth] = getLeaf(self, depth, index + 1); } else { proof_path[depth] = getLeaf(self, depth, index - 1); } index = uint(index / 2); } } function getUniqueLeaf(uint256 depth, uint256 offset, uint256 leaf) internal pure returns (uint256) { if (leaf == 0x0) { leaf = uint256( sha256( abi.encodePacked( uint16(depth), uint240(offset)))) % MiMC.getScalarField(); } return leaf; } function updateTree(Data storage self, uint256[15] memory IVs) internal returns(uint256 root) { uint currentIndex = self.cur; uint256 leaf1; uint256 leaf2; for (uint depth = 0; depth < TREE_DEPTH; depth++) { if (currentIndex%2 == 0) { leaf1 = self.nodes[depth][currentIndex]; leaf2 = getUniqueLeaf(depth, currentIndex + 1, self.nodes[depth][currentIndex + 1]); } else { leaf1 = getUniqueLeaf(depth, currentIndex - 1, self.nodes[depth][currentIndex - 1]); leaf2 = self.nodes[depth][currentIndex]; } uint nextIndex = uint(currentIndex/2); self.nodes[depth+1][nextIndex] = hashImpl(leaf1, leaf2, IVs[depth]); currentIndex = nextIndex; } return self.nodes[TREE_DEPTH][0]; } function getRoot (Data storage self) internal view returns (uint256) { return self.nodes[TREE_DEPTH][0]; } function getNextLeafIndex (Data storage self) internal view returns (uint256) { return self.cur; } } contract Mixer { using MerkleTree for MerkleTree.Data; uint constant public AMOUNT = 1 ether; uint256[14] vk; uint256[] gammaABC; mapping (uint256 => bool) public nullifiers; mapping (address => uint256[]) public pendingDeposits; MerkleTree.Data internal tree; event CommitmentAdded(address indexed _fundingWallet, uint256 _leaf); event LeafAdded(uint256 _leaf, uint256 _leafIndex); constructor(uint256[14] memory in_vk, uint256[] memory in_gammaABC) public { vk = in_vk; gammaABC = in_gammaABC; } function getRoot() public view returns (uint256) { return tree.getRoot(); } /** * Save a commitment (leaf) that needs to be funded later on */ function commit(uint256 leaf, address fundingWallet) public payable { require(leaf > 0, "null leaf"); pendingDeposits[fundingWallet].push(leaf); emit CommitmentAdded(fundingWallet, leaf); if (msg.value > 0) fundCommitment(); } function fundCommitment() private { require(msg.value == AMOUNT, "wrong value"); uint256[] storage leaves = pendingDeposits[msg.sender]; require(leaves.length > 0, "commitment must be sent first"); uint256 leaf = leaves[leaves.length - 1]; leaves.length--; (, uint256 leafIndex) = tree.insert(leaf); emit LeafAdded(leaf, leafIndex); } /* * Used by the funding wallet to fund a previously saved commitment */ function () external payable { fundCommitment(); } function makeLeafHash(uint256 nullifier_secret, address wallet_address) external pure returns (uint256) { bytes32 digest = sha256(abi.encodePacked(nullifier_secret, uint256(wallet_address))); uint256 mask = uint256(-1) >> 4; // clear the first 4 bits to make sure we stay within the prime field return uint256(digest) & mask; } function makeNullifierHash(uint256 nullifier_secret) external pure returns (uint256) { uint256[] memory vals = new uint256[](2); vals[0] = nullifier_secret; vals[1] = nullifier_secret; return MiMC.Hash(vals, 0); } function getMerklePath(uint256 leafIndex) external view returns (uint256[15] memory out_path) { out_path = tree.getMerkleProof(leafIndex); } function isSpent(uint256 nullifier) public view returns (bool) { return nullifiers[nullifier]; } function verifyProof(uint256 in_root, address in_wallet_address, uint256 in_nullifier, uint256[8] memory proof) public view returns (bool) { uint256[] memory snark_input = new uint256[](3); snark_input[0] = in_root; snark_input[1] = uint256(in_wallet_address); snark_input[2] = in_nullifier; return Verifier.verify(vk, gammaABC, proof, snark_input); } function withdraw( address payable in_withdraw_address, uint256 in_nullifier, uint256[8] memory proof ) public { uint startGas = gasleft(); require(!nullifiers[in_nullifier], "Nullifier used"); require(verifyProof(getRoot(), in_withdraw_address, in_nullifier, proof), "Proof verification failed"); nullifiers[in_nullifier] = true; uint gasUsed = startGas - gasleft() + 82775; uint relayerRefund = gasUsed * tx.gasprice; if(relayerRefund > AMOUNT/20) relayerRefund = AMOUNT/20; in_withdraw_address.transfer(AMOUNT - relayerRefund); // leaf withdrawal msg.sender.transfer(relayerRefund); // relayer refund } function treeDepth() external pure returns (uint256) { return MerkleTree.treeDepth(); } function getNextLeafIndex() external view returns (uint256) { return tree.getNextLeafIndex(); } }
return the generator of G1
function P1() internal pure returns (G1Point memory) { return G1Point(1, 2); }
7,233,453
// SPDX-License-Identifier: MIT /** * Stick Fighter .m. (;) (;) (;) . (;) . |\_(;)_/| |/ )|( \| ( o ) )8( ( o ) )8( ;|S|; ||S|| ||S|| ||S|< ||S|| ||S|| ||S|| ||S|| ||S|| ||S|| ||S|| \\ // \V/ V */ pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/access/Ownable.sol@v4.3.2 pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File @openzeppelin/contracts/utils/introspection/IERC165.sol@v4.3.2 pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/token/ERC721/IERC721.sol@v4.3.2 pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol@v4.3.2 pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol@v4.3.2 pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File @openzeppelin/contracts/utils/Address.sol@v4.3.2 pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/utils/Strings.sol@v4.3.2 pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File @openzeppelin/contracts/utils/introspection/ERC165.sol@v4.3.2 pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File @openzeppelin/contracts/token/ERC721/ERC721.sol@v4.3.2 pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. creds Ba * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol@v4.3.2 pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol@v4.3.2 pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } //Join our socials! //Website : stickfighter.io/ //Twitter : twitter.com/stickfighternft //Discord : https://discord.gg/dPpUGbvs pragma solidity ^0.8.0; contract StickFighter is ERC721Enumerable, Ownable { using Strings for uint256; event Mint(address indexed sender, uint256 startWith, uint256 times); //supply counters total max supply = totalcount - 1 uint256 public totalMints; uint256 public totalCount = 10001; //Max mints per batch uint256 public maxBatch = 10; //Token price of each token converted to WEI uint256 public price = 0.05 * 10 ** 18; //Token price of each token in the pre sale converted to WEI //The presale is reserved for the OG holders uint256 public presalePrice = 0.0 ether; //String for the baseURI string public baseURI; //Booleans for the sale and the presale bool private saleActive; bool private presaleActive; //List of addresses that have a number of reserved tokens for presale mapping (address => uint16) public presaleAddresses; //constructor args constructor(string memory name_, string memory symbol_, string memory baseURI_) ERC721(name_, symbol_) { baseURI = baseURI_; } //basic functions. function _baseURI() internal view virtual override returns (string memory){ return baseURI; } function setBaseURI(string memory _newURI) public onlyOwner { baseURI = _newURI; } //Returns a tokenURI of a specific token function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token."); string memory baseURI2 = _baseURI(); return bytes(baseURI2).length > 0 ? string(abi.encodePacked(baseURI2, tokenId.toString(), ".json")) : '.json'; } //Function to activate or deactivate the sale function setSaleActive(bool _start) public onlyOwner { saleActive = _start; } //Function to activate or deactivate the presale function setPresaleActive(bool _start) public onlyOwner { presaleActive = _start; } function tokensOfOwner(address owner) public view returns (uint256[] memory) { uint256 count = balanceOf(owner); uint256[] memory ids = new uint256[](count); for (uint256 i = 0; i < count; i++) { ids[i] = tokenOfOwnerByIndex(owner, i); } return ids; } //Exclusive Presale mint for the OG's || Moet nog testen of het goe dgaat met de total suplly function mintPresaleToken(uint16 _amount) public payable { require( presaleActive, "Presale is not active" ); uint16 reservedAmt = presaleAddresses[msg.sender]; require( reservedAmt > 0, "No tokens reserved for your address" ); require( _amount < reservedAmt, "max reserved token supply reached!" ); require( totalMints + _amount < totalCount, "Cannot mint more than max supply" ); require( msg.value == presalePrice * _amount, "Wrong amount of ETH sent" ); presaleAddresses[msg.sender] = reservedAmt - _amount; for(uint16 i; i < _amount; i++){ _safeMint( msg.sender, 1 + totalMints++); } } //Mint function function mint(uint16 _amount) public payable { require( saleActive,"Sale is not active" ); require( _amount < maxBatch, "You can only Mint 10 tokens at once" ); require( totalMints + _amount < totalCount,"Cannot mint more than max supply" ); require( msg.value == price * _amount,"Wrong amount of ETH sent" ); for(uint16 i; i < _amount; i++){ _safeMint( msg.sender, 1+ totalMints++); } } //Set reserved presale spots for OG's function setPresaleReservedAddresses(address[] memory _a, uint16[] memory _amount) public onlyOwner { uint16 length = uint16(_a.length); for(uint16 i; i < length; i++){ presaleAddresses[_a[i]] = _amount[i]; } } }
Returns a tokenURI of a specific token
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token."); string memory baseURI2 = _baseURI(); return bytes(baseURI2).length > 0 ? string(abi.encodePacked(baseURI2, tokenId.toString(), ".json")) : '.json'; }
11,752,500
pragma solidity 0.6.7; pragma experimental ABIEncoderV2; contract ControllerV4 { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public constant burn = 0x000000000000000000000000000000000000dEaD; address public onesplit = 0xC586BeF4a0992C495Cf22e1aeEE4E446CECDee0E; address public governance; address public strategist; address public devfund; address public treasury; address public timelock; // Convenience fee 0.1% uint256 public convenienceFee = 100; uint256 public constant convenienceFeeMax = 100000; mapping(address => address) public jars; mapping(address => address) public strategies; mapping(address => mapping(address => address)) public converters; mapping(address => mapping(address => bool)) public approvedStrategies; mapping(address => bool) public approvedJarConverters; uint256 public split = 500; uint256 public constant max = 10000; constructor( address _governance, address _strategist, address _timelock, address _devfund, address _treasury ) public { governance = _governance; strategist = _strategist; timelock = _timelock; devfund = _devfund; treasury = _treasury; } function setDevFund(address _devfund) public { require(msg.sender == governance, "!governance"); devfund = _devfund; } function setTreasury(address _treasury) public { require(msg.sender == governance, "!governance"); treasury = _treasury; } function setStrategist(address _strategist) public { require(msg.sender == governance, "!governance"); strategist = _strategist; } function setSplit(uint256 _split) public { require(msg.sender == governance, "!governance"); split = _split; } function setOneSplit(address _onesplit) public { require(msg.sender == governance, "!governance"); onesplit = _onesplit; } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function setTimelock(address _timelock) public { require(msg.sender == timelock, "!timelock"); timelock = _timelock; } function setJar(address _token, address _jar) public { require( msg.sender == strategist || msg.sender == governance, "!strategist" ); require(jars[_token] == address(0), "jar"); jars[_token] = _jar; } function approveJarConverter(address _converter) public { require(msg.sender == governance, "!governance"); approvedJarConverters[_converter] = true; } function revokeJarConverter(address _converter) public { require(msg.sender == governance, "!governance"); approvedJarConverters[_converter] = false; } function approveStrategy(address _token, address _strategy) public { require(msg.sender == timelock, "!timelock"); approvedStrategies[_token][_strategy] = true; } function revokeStrategy(address _token, address _strategy) public { require(msg.sender == governance, "!governance"); approvedStrategies[_token][_strategy] = false; } function setConvenienceFee(uint256 _convenienceFee) external { require(msg.sender == timelock, "!timelock"); convenienceFee = _convenienceFee; } function setStrategy(address _token, address _strategy) public { require( msg.sender == strategist || msg.sender == governance, "!strategist" ); require(approvedStrategies[_token][_strategy] == true, "!approved"); address _current = strategies[_token]; if (_current != address(0)) { IStrategy(_current).withdrawAll(); } strategies[_token] = _strategy; } function earn(address _token, uint256 _amount) public { address _strategy = strategies[_token]; address _want = IStrategy(_strategy).want(); if (_want != _token) { address converter = converters[_token][_want]; IERC20(_token).safeTransfer(converter, _amount); _amount = Converter(converter).convert(_strategy); IERC20(_want).safeTransfer(_strategy, _amount); } else { IERC20(_token).safeTransfer(_strategy, _amount); } IStrategy(_strategy).deposit(); } function balanceOf(address _token) external view returns (uint256) { return IStrategy(strategies[_token]).balanceOf(); } function withdrawAll(address _token) public { require( msg.sender == strategist || msg.sender == governance, "!strategist" ); IStrategy(strategies[_token]).withdrawAll(); } function inCaseTokensGetStuck(address _token, uint256 _amount) public { require( msg.sender == strategist || msg.sender == governance, "!governance" ); IERC20(_token).safeTransfer(msg.sender, _amount); } function inCaseStrategyTokenGetStuck(address _strategy, address _token) public { require( msg.sender == strategist || msg.sender == governance, "!governance" ); IStrategy(_strategy).withdraw(_token); } function getExpectedReturn( address _strategy, address _token, uint256 parts ) public view returns (uint256 expected) { uint256 _balance = IERC20(_token).balanceOf(_strategy); address _want = IStrategy(_strategy).want(); (expected, ) = OneSplitAudit(onesplit).getExpectedReturn( _token, _want, _balance, parts, 0 ); } // Only allows to withdraw non-core strategy tokens ~ this is over and above normal yield function yearn( address _strategy, address _token, uint256 parts ) public { require( msg.sender == strategist || msg.sender == governance, "!governance" ); // This contract should never have value in it, but just incase since this is a public call uint256 _before = IERC20(_token).balanceOf(address(this)); IStrategy(_strategy).withdraw(_token); uint256 _after = IERC20(_token).balanceOf(address(this)); if (_after > _before) { uint256 _amount = _after.sub(_before); address _want = IStrategy(_strategy).want(); uint256[] memory _distribution; uint256 _expected; _before = IERC20(_want).balanceOf(address(this)); IERC20(_token).safeApprove(onesplit, 0); IERC20(_token).safeApprove(onesplit, _amount); (_expected, _distribution) = OneSplitAudit(onesplit) .getExpectedReturn(_token, _want, _amount, parts, 0); OneSplitAudit(onesplit).swap( _token, _want, _amount, _expected, _distribution, 0 ); _after = IERC20(_want).balanceOf(address(this)); if (_after > _before) { _amount = _after.sub(_before); uint256 _treasury = _amount.mul(split).div(max); earn(_want, _amount.sub(_treasury)); IERC20(_want).safeTransfer(treasury, _treasury); } } } function withdraw(address _token, uint256 _amount) public { require(msg.sender == jars[_token], "!jar"); IStrategy(strategies[_token]).withdraw(_amount); } // Function to swap between jars function swapExactJarForJar( address _fromJar, // From which Jar address _toJar, // To which Jar uint256 _fromJarAmount, // How much jar tokens to swap uint256 _toJarMinAmount, // How much jar tokens you'd like at a minimum address payable[] calldata _targets, bytes[] calldata _data ) external returns (uint256) { require(_targets.length == _data.length, "!length"); // Only return last response for (uint256 i = 0; i < _targets.length; i++) { require(_targets[i] != address(0), "!converter"); require(approvedJarConverters[_targets[i]], "!converter"); } address _fromJarToken = IJar(_fromJar).token(); address _toJarToken = IJar(_toJar).token(); // Get pTokens from msg.sender IERC20(_fromJar).safeTransferFrom( msg.sender, address(this), _fromJarAmount ); // Calculate how much underlying // is the amount of pTokens worth uint256 _fromJarUnderlyingAmount = _fromJarAmount .mul(IJar(_fromJar).getRatio()) .div(10**uint256(IJar(_fromJar).decimals())); // Call 'withdrawForSwap' on Jar's current strategy if Jar // doesn't have enough initial capital. // This has moves the funds from the strategy to the Jar's // 'earnable' amount. Enabling 'free' withdrawals uint256 _fromJarAvailUnderlying = IERC20(_fromJarToken).balanceOf( _fromJar ); if (_fromJarAvailUnderlying < _fromJarUnderlyingAmount) { IStrategy(strategies[_fromJarToken]).withdrawForSwap( _fromJarUnderlyingAmount.sub(_fromJarAvailUnderlying) ); } // Withdraw from Jar // Note: this is free since its still within the "earnable" amount // as we transferred the access IERC20(_fromJar).safeApprove(_fromJar, 0); IERC20(_fromJar).safeApprove(_fromJar, _fromJarAmount); IJar(_fromJar).withdraw(_fromJarAmount); // Calculate fee uint256 _fromUnderlyingBalance = IERC20(_fromJarToken).balanceOf( address(this) ); uint256 _convenienceFee = _fromUnderlyingBalance.mul(convenienceFee).div( convenienceFeeMax ); if (_convenienceFee > 1) { IERC20(_fromJarToken).safeTransfer(devfund, _convenienceFee.div(2)); IERC20(_fromJarToken).safeTransfer(treasury, _convenienceFee.div(2)); } // Executes sequence of logic for (uint256 i = 0; i < _targets.length; i++) { _execute(_targets[i], _data[i]); } // Deposit into new Jar uint256 _toBal = IERC20(_toJarToken).balanceOf(address(this)); IERC20(_toJarToken).safeApprove(_toJar, 0); IERC20(_toJarToken).safeApprove(_toJar, _toBal); IJar(_toJar).deposit(_toBal); // Send Jar Tokens to user uint256 _toJarBal = IJar(_toJar).balanceOf(address(this)); if (_toJarBal < _toJarMinAmount) { revert("!min-jar-amount"); } IJar(_toJar).transfer(msg.sender, _toJarBal); return _toJarBal; } function _execute(address _target, bytes memory _data) internal returns (bytes memory response) { require(_target != address(0), "!target"); // call contract in current context assembly { let succeeded := delegatecall( sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0 ) let size := returndatasize() response := mload(0x40) mstore( 0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f))) ) mstore(response, size) returndatacopy(add(response, 0x20), 0, size) switch iszero(succeeded) case 1 { // throw if delegatecall failed revert(add(response, 0x20), size) } } } } contract Timelock { using SafeMath for uint; event NewAdmin(address indexed newAdmin); event NewPendingAdmin(address indexed newPendingAdmin); event NewDelay(uint indexed newDelay); event CancelTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); event QueueTransaction(bytes32 indexed txHash, address indexed target, uint value, string signature, bytes data, uint eta); uint public constant GRACE_PERIOD = 14 days; uint public constant MINIMUM_DELAY = 2 days; uint public constant MAXIMUM_DELAY = 30 days; address public admin; address public pendingAdmin; uint public delay; bool public admin_initialized; mapping (bytes32 => bool) public queuedTransactions; constructor(address admin_, uint delay_) public { require(delay_ >= MINIMUM_DELAY, "Timelock::constructor: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::constructor: Delay must not exceed maximum delay."); admin = admin_; delay = delay_; admin_initialized = false; } // XXX: function() external payable { } receive() external payable { } function setDelay(uint delay_) public { require(msg.sender == address(this), "Timelock::setDelay: Call must come from Timelock."); require(delay_ >= MINIMUM_DELAY, "Timelock::setDelay: Delay must exceed minimum delay."); require(delay_ <= MAXIMUM_DELAY, "Timelock::setDelay: Delay must not exceed maximum delay."); delay = delay_; emit NewDelay(delay); } function acceptAdmin() public { require(msg.sender == pendingAdmin, "Timelock::acceptAdmin: Call must come from pendingAdmin."); admin = msg.sender; pendingAdmin = address(0); emit NewAdmin(admin); } function setPendingAdmin(address pendingAdmin_) public { // allows one time setting of admin for deployment purposes if (admin_initialized) { require(msg.sender == address(this), "Timelock::setPendingAdmin: Call must come from Timelock."); } else { require(msg.sender == admin, "Timelock::setPendingAdmin: First call must come from admin."); admin_initialized = true; } pendingAdmin = pendingAdmin_; emit NewPendingAdmin(pendingAdmin); } function queueTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public returns (bytes32) { require(msg.sender == admin, "Timelock::queueTransaction: Call must come from admin."); require(eta >= getBlockTimestamp().add(delay), "Timelock::queueTransaction: Estimated execution block must satisfy delay."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = true; emit QueueTransaction(txHash, target, value, signature, data, eta); return txHash; } function cancelTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public { require(msg.sender == admin, "Timelock::cancelTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); queuedTransactions[txHash] = false; emit CancelTransaction(txHash, target, value, signature, data, eta); } function executeTransaction(address target, uint value, string memory signature, bytes memory data, uint eta) public payable returns (bytes memory) { require(msg.sender == admin, "Timelock::executeTransaction: Call must come from admin."); bytes32 txHash = keccak256(abi.encode(target, value, signature, data, eta)); require(queuedTransactions[txHash], "Timelock::executeTransaction: Transaction hasn't been queued."); require(getBlockTimestamp() >= eta, "Timelock::executeTransaction: Transaction hasn't surpassed time lock."); require(getBlockTimestamp() <= eta.add(GRACE_PERIOD), "Timelock::executeTransaction: Transaction is stale."); queuedTransactions[txHash] = false; bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked(bytes4(keccak256(bytes(signature))), data); } // solium-disable-next-line security/no-call-value (bool success, bytes memory returnData) = target.call.value(value)(callData); require(success, "Timelock::executeTransaction: Transaction execution reverted."); emit ExecuteTransaction(txHash, target, value, signature, data, eta); return returnData; } function getBlockTimestamp() internal view returns (uint) { // solium-disable-next-line security/no-block-members return block.timestamp; } } interface ICToken { function totalSupply() external view returns (uint256); function totalBorrows() external returns (uint256); function borrowIndex() external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function mint(uint256 mintAmount) external returns (uint256); function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function getCash() external view returns (uint256); function accrueInterest() external returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); } interface ICEther { function mint() external payable; /** * @notice Sender redeems cTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of cTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint256 redeemTokens) external returns (uint256); /** * @notice Sender redeems cTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint256 redeemAmount) external returns (uint256); /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint256 borrowAmount) external returns (uint256); /** * @notice Sender repays their own borrow * @dev Reverts upon any failure */ function repayBorrow() external payable; /** * @notice Sender repays a borrow belonging to borrower * @dev Reverts upon any failure * @param borrower the account with the debt being payed off */ function repayBorrowBehalf(address borrower) external payable; /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @dev Reverts upon any failure * @param borrower The borrower of this cToken to be liquidated * @param cTokenCollateral The market in which to seize collateral from the borrower */ function liquidateBorrow(address borrower, address cTokenCollateral) external payable; } interface IComptroller { function compAccrued(address) external view returns (uint256); function compSupplierIndex(address, address) external view returns (uint256); function compBorrowerIndex(address, address) external view returns (uint256); function compSpeeds(address) external view returns (uint256); function compBorrowState(address) external view returns (uint224, uint32); function compSupplyState(address) external view returns (uint224, uint32); /*** Assets You Are In ***/ function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); /*** Policy Hooks ***/ function mintAllowed( address cToken, address minter, uint256 mintAmount ) external returns (uint256); function mintVerify( address cToken, address minter, uint256 mintAmount, uint256 mintTokens ) external; function redeemAllowed( address cToken, address redeemer, uint256 redeemTokens ) external returns (uint256); function redeemVerify( address cToken, address redeemer, uint256 redeemAmount, uint256 redeemTokens ) external; function borrowAllowed( address cToken, address borrower, uint256 borrowAmount ) external returns (uint256); function borrowVerify( address cToken, address borrower, uint256 borrowAmount ) external; function repayBorrowAllowed( address cToken, address payer, address borrower, uint256 repayAmount ) external returns (uint256); function repayBorrowVerify( address cToken, address payer, address borrower, uint256 repayAmount, uint256 borrowerIndex ) external; function liquidateBorrowAllowed( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount ) external returns (uint256); function liquidateBorrowVerify( address cTokenBorrowed, address cTokenCollateral, address liquidator, address borrower, uint256 repayAmount, uint256 seizeTokens ) external; function seizeAllowed( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function seizeVerify( address cTokenCollateral, address cTokenBorrowed, address liquidator, address borrower, uint256 seizeTokens ) external; function transferAllowed( address cToken, address src, address dst, uint256 transferTokens ) external returns (uint256); function transferVerify( address cToken, address src, address dst, uint256 transferTokens ) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint256 repayAmount ) external view returns (uint256, uint256); // Claim all the COMP accrued by holder in all markets function claimComp(address holder) external; // Claim all the COMP accrued by holder in specific markets function claimComp(address holder, address[] calldata cTokens) external; // Claim all the COMP accrued by specific holders in specific markets for their supplies and/or borrows function claimComp( address[] calldata holders, address[] calldata cTokens, bool borrowers, bool suppliers ) external; function markets(address cTokenAddress) external view returns (bool, uint256); } interface ICompoundLens { function getCompBalanceMetadataExt( address comp, address comptroller, address account ) external returns ( uint256 balance, uint256 votes, address delegate, uint256 allocated ); } interface IController { function jars(address) external view returns (address); function rewards() external view returns (address); function devfund() external view returns (address); function treasury() external view returns (address); function balanceOf(address) external view returns (uint256); function withdraw(address, uint256) external; function earn(address, uint256) external; } interface Converter { function convert(address) external returns (uint256); } interface ICurveFi_2 { function get_virtual_price() external view returns (uint256); function add_liquidity(uint256[2] calldata amounts, uint256 min_mint_amount) external; function remove_liquidity_imbalance( uint256[2] calldata amounts, uint256 max_burn_amount ) external; function remove_liquidity(uint256 _amount, uint256[2] calldata amounts) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function balances(int128) external view returns (uint256); } interface ICurveFi_3 { function get_virtual_price() external view returns (uint256); function add_liquidity(uint256[3] calldata amounts, uint256 min_mint_amount) external; function remove_liquidity_imbalance( uint256[3] calldata amounts, uint256 max_burn_amount ) external; function remove_liquidity(uint256 _amount, uint256[3] calldata amounts) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function balances(uint256) external view returns (uint256); } interface ICurveFi_4 { function get_virtual_price() external view returns (uint256); function add_liquidity(uint256[4] calldata amounts, uint256 min_mint_amount) external; function remove_liquidity_imbalance( uint256[4] calldata amounts, uint256 max_burn_amount ) external; function remove_liquidity(uint256 _amount, uint256[4] calldata amounts) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function balances(int128) external view returns (uint256); } interface ICurveZap_4 { function add_liquidity( uint256[4] calldata uamounts, uint256 min_mint_amount ) external; function remove_liquidity(uint256 _amount, uint256[4] calldata min_uamounts) external; function remove_liquidity_imbalance( uint256[4] calldata uamounts, uint256 max_burn_amount ) external; function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external returns (uint256); function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_uamount ) external; function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_uamount, bool donate_dust ) external; function withdraw_donated_dust() external; function coins(int128 arg0) external returns (address); function underlying_coins(int128 arg0) external returns (address); function curve() external returns (address); function token() external returns (address); } interface ICurveZap { function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_uamount ) external; } interface ICurveGauge { function deposit(uint256 _value) external; function deposit(uint256 _value, address addr) external; function balanceOf(address arg0) external view returns (uint256); function withdraw(uint256 _value) external; function withdraw(uint256 _value, bool claim_rewards) external; function claim_rewards() external; function claim_rewards(address addr) external; function claimable_tokens(address addr) external returns (uint256); function claimable_reward(address addr) external view returns (uint256); function integrate_fraction(address arg0) external view returns (uint256); } interface ICurveMintr { function mint(address) external; function minted(address arg0, address arg1) external view returns (uint256); } interface ICurveVotingEscrow { function locked(address arg0) external view returns (int128 amount, uint256 end); function locked__end(address _addr) external view returns (uint256); function create_lock(uint256, uint256) external; function increase_amount(uint256) external; function increase_unlock_time(uint256 _unlock_time) external; function withdraw() external; function smart_wallet_checker() external returns (address); } interface ICurveSmartContractChecker { function wallets(address) external returns (bool); function approveWallet(address _wallet) external; } interface IJarConverter { function convert( address _refundExcess, // address to send the excess amount when adding liquidity uint256 _amount, // UNI LP Amount bytes calldata _data ) external returns (uint256); } interface IMasterchef { function BONUS_MULTIPLIER() external view returns (uint256); function add( uint256 _allocPoint, address _lpToken, bool _withUpdate ) external; function bonusEndBlock() external view returns (uint256); function deposit(uint256 _pid, uint256 _amount) external; function dev(address _devaddr) external; function devFundDivRate() external view returns (uint256); function devaddr() external view returns (address); function emergencyWithdraw(uint256 _pid) external; function getMultiplier(uint256 _from, uint256 _to) external view returns (uint256); function massUpdatePools() external; function owner() external view returns (address); function pendingPickle(uint256 _pid, address _user) external view returns (uint256); function pickle() external view returns (address); function picklePerBlock() external view returns (uint256); function poolInfo(uint256) external view returns ( address lpToken, uint256 allocPoint, uint256 lastRewardBlock, uint256 accPicklePerShare ); function poolLength() external view returns (uint256); function renounceOwnership() external; function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external; function setBonusEndBlock(uint256 _bonusEndBlock) external; function setDevFundDivRate(uint256 _devFundDivRate) external; function setPicklePerBlock(uint256 _picklePerBlock) external; function startBlock() external view returns (uint256); function totalAllocPoint() external view returns (uint256); function transferOwnership(address newOwner) external; function updatePool(uint256 _pid) external; function userInfo(uint256, address) external view returns (uint256 amount, uint256 rewardDebt); function withdraw(uint256 _pid, uint256 _amount) external; } interface OneSplitAudit { function getExpectedReturn( address fromToken, address toToken, uint256 amount, uint256 parts, uint256 featureFlags ) external view returns (uint256 returnAmount, uint256[] memory distribution); function swap( address fromToken, address toToken, uint256 amount, uint256 minReturn, uint256[] calldata distribution, uint256 featureFlags ) external payable; } interface Proxy { function execute( address to, uint256 value, bytes calldata data ) external returns (bool, bytes memory); function increaseAmount(uint256) external; } interface IStakingRewards { function balanceOf(address account) external view returns (uint256); function earned(address account) external view returns (uint256); function exit() external; function getReward() external; function getRewardForDuration() external view returns (uint256); function lastTimeRewardApplicable() external view returns (uint256); function lastUpdateTime() external view returns (uint256); function notifyRewardAmount(uint256 reward) external; function periodFinish() external view returns (uint256); function rewardPerToken() external view returns (uint256); function rewardPerTokenStored() external view returns (uint256); function rewardRate() external view returns (uint256); function rewards(address) external view returns (uint256); function rewardsDistribution() external view returns (address); function rewardsDuration() external view returns (uint256); function rewardsToken() external view returns (address); function stake(uint256 amount) external; function stakeWithPermit( uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function stakingToken() external view returns (address); function totalSupply() external view returns (uint256); function userRewardPerTokenPaid(address) external view returns (uint256); function withdraw(uint256 amount) external; } interface IStakingRewardsFactory { function deploy(address stakingToken, uint256 rewardAmount) external; function isOwner() external view returns (bool); function notifyRewardAmount(address stakingToken) external; function notifyRewardAmounts() external; function owner() external view returns (address); function renounceOwnership() external; function rewardsToken() external view returns (address); function stakingRewardsGenesis() external view returns (uint256); function stakingRewardsInfoByStakingToken(address) external view returns (address stakingRewards, uint256 rewardAmount); function stakingTokens(uint256) external view returns (address); function transferOwnership(address newOwner) external; } interface IStrategy { function rewards() external view returns (address); function gauge() external view returns (address); function want() external view returns (address); function timelock() external view returns (address); function deposit() external; function withdrawForSwap(uint256) external returns (uint256); function withdraw(address) external; function withdraw(uint256) external; function skim() external; function withdrawAll() external returns (uint256); function balanceOf() external view returns (uint256); function harvest() external; function setTimelock(address) external; function setController(address _controller) external; function execute(address _target, bytes calldata _data) external payable returns (bytes memory response); function execute(bytes calldata _data) external payable returns (bytes memory response); } interface UniswapRouterV2 { function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); } interface IUniswapV2Pair { event Approval( address indexed owner, address indexed spender, uint256 value ); event Transfer(address indexed from, address indexed to, uint256 value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint256); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external; function skim(address to) external; function sync() external; } interface IUniswapV2Factory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function createPair(address tokenA, address tokenB) external returns (address pair); } interface USDT { function approve(address guy, uint256 wad) external; function transfer(address _to, uint256 _value) external; } interface WETH { function name() external view returns (string memory); function approve(address guy, uint256 wad) external returns (bool); function totalSupply() external view returns (uint256); function transferFrom( address src, address dst, uint256 wad ) external returns (bool); function withdraw(uint256 wad) external; function decimals() external view returns (uint8); function balanceOf(address) external view returns (uint256); function symbol() external view returns (string memory); function transfer(address dst, uint256 wad) external returns (bool); function deposit() external payable; function allowance(address, address) external view returns (uint256); } contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Adds two exponentials, returning a new exponential. */ function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = addUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Subtracts two exponentials, returning a new exponential. */ function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError error, uint result) = subUInt(a.mantissa, b.mantissa); return (error, Exp({mantissa: result})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer. */ function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return addUInt(truncate(product), addend); } /** * @dev Divide an Exp by a scalar, returning a new Exp. */ function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa})); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer. */ function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) { (MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(fraction)); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Multiplies three exponentials, returning a new exponential. */ function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) { (MathError err, Exp memory ab) = mulExp(a, b); if (err != MathError.NO_ERROR) { return (err, ab); } return mulExp(ab, c); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } /** * @dev Checks if first Exp is less than second Exp. */ function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa < right.mantissa; } /** * @dev Checks if left Exp <= right Exp. */ function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa <= right.mantissa; } /** * @dev Checks if left Exp > right Exp. */ function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) { return left.mantissa > right.mantissa; } /** * @dev returns true if Exp is exactly zero */ function isZeroExp(Exp memory value) pure internal returns (bool) { return value.mantissa == 0; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function safe32(uint n, string memory errorMessage) pure internal returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract Owned { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require( msg.sender == nominatedOwner, "You must be nominated before you can accept ownership" ); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { _onlyOwner(); _; } function _onlyOwner() private view { require( msg.sender == owner, "Only the contract owner may perform this action" ); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } abstract contract Pausable is Owned { uint256 public lastPauseTime; bool public paused; constructor() internal { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "Owner must be set"); // Paused will be false, and lastPauseTime will be 0 upon initialisation } /** * @notice Change the paused state of the contract * @dev Only the contract owner may call this. */ function setPaused(bool _paused) external onlyOwner { // Ensure we're actually changing the state before we do anything if (_paused == paused) { return; } // Set our paused state. paused = _paused; // If applicable, set the last pause time. if (paused) { lastPauseTime = now; } // Let everyone know that our pause state has changed. emit PauseChanged(paused); } event PauseChanged(bool isPaused); modifier notPaused { require( !paused, "This action cannot be performed while the contract is paused" ); _; } } contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract PickleJar is ERC20 { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; IERC20 public token; uint256 public min = 9500; uint256 public constant max = 10000; address public governance; address public timelock; address public controller; constructor(address _token, address _governance, address _timelock, address _controller) public ERC20( string(abi.encodePacked("pickling ", ERC20(_token).name())), string(abi.encodePacked("p", ERC20(_token).symbol())) ) { _setupDecimals(ERC20(_token).decimals()); token = IERC20(_token); governance = _governance; timelock = _timelock; controller = _controller; } function balance() public view returns (uint256) { return token.balanceOf(address(this)).add( IController(controller).balanceOf(address(token)) ); } function setMin(uint256 _min) external { require(msg.sender == governance, "!governance"); min = _min; } function setGovernance(address _governance) public { require(msg.sender == governance, "!governance"); governance = _governance; } function setTimelock(address _timelock) public { require(msg.sender == timelock, "!timelock"); timelock = _timelock; } function setController(address _controller) public { require(msg.sender == timelock, "!timelock"); controller = _controller; } // Custom logic in here for how much the jars allows to be borrowed // Sets minimum required on-hand to keep small withdrawals cheap function available() public view returns (uint256) { return token.balanceOf(address(this)).mul(min).div(max); } function earn() public { uint256 _bal = available(); token.safeTransfer(controller, _bal); IController(controller).earn(address(token), _bal); } function depositAll() external { deposit(token.balanceOf(msg.sender)); } function deposit(uint256 _amount) public { uint256 _pool = balance(); uint256 _before = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), _amount); uint256 _after = token.balanceOf(address(this)); _amount = _after.sub(_before); // Additional check for deflationary tokens uint256 shares = 0; if (totalSupply() == 0) { shares = _amount; } else { shares = (_amount.mul(totalSupply())).div(_pool); } _mint(msg.sender, shares); } function withdrawAll() external { withdraw(balanceOf(msg.sender)); } // Used to swap any borrowed reserve over the debt limit to liquidate to 'token' function harvest(address reserve, uint256 amount) external { require(msg.sender == controller, "!controller"); require(reserve != address(token), "token"); IERC20(reserve).safeTransfer(controller, amount); } // No rebalance implementation for lower fees and faster swaps function withdraw(uint256 _shares) public { uint256 r = (balance().mul(_shares)).div(totalSupply()); _burn(msg.sender, _shares); // Check balance uint256 b = token.balanceOf(address(this)); if (b < r) { uint256 _withdraw = r.sub(b); IController(controller).withdraw(address(token), _withdraw); uint256 _after = token.balanceOf(address(this)); uint256 _diff = _after.sub(b); if (_diff < _withdraw) { r = b.add(_diff); } } token.safeTransfer(msg.sender, r); } function getRatio() public view returns (uint256) { return balance().mul(1e18).div(totalSupply()); } } contract PickleSwap { using SafeERC20 for IERC20; UniswapRouterV2 router = UniswapRouterV2( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; function convertWETHPair( address fromLP, address toLP, uint256 value ) public { IUniswapV2Pair fromPair = IUniswapV2Pair(fromLP); IUniswapV2Pair toPair = IUniswapV2Pair(toLP); // Only for WETH/<TOKEN> pairs if (!(fromPair.token0() == weth || fromPair.token1() == weth)) { revert("!eth-from"); } if (!(toPair.token0() == weth || toPair.token1() == weth)) { revert("!eth-to"); } // Get non-eth token from pairs address _from = fromPair.token0() != weth ? fromPair.token0() : fromPair.token1(); address _to = toPair.token0() != weth ? toPair.token0() : toPair.token1(); // Transfer IERC20(fromLP).safeTransferFrom(msg.sender, address(this), value); // Remove liquidity IERC20(fromLP).safeApprove(address(router), 0); IERC20(fromLP).safeApprove(address(router), value); router.removeLiquidity( fromPair.token0(), fromPair.token1(), value, 0, 0, address(this), now + 60 ); // Convert to target token address[] memory path = new address[](3); path[0] = _from; path[1] = weth; path[2] = _to; IERC20(_from).safeApprove(address(router), 0); IERC20(_from).safeApprove(address(router), uint256(-1)); router.swapExactTokensForTokens( IERC20(_from).balanceOf(address(this)), 0, path, address(this), now + 60 ); // Supply liquidity IERC20(weth).safeApprove(address(router), 0); IERC20(weth).safeApprove(address(router), uint256(-1)); IERC20(_to).safeApprove(address(router), 0); IERC20(_to).safeApprove(address(router), uint256(-1)); router.addLiquidity( weth, _to, IERC20(weth).balanceOf(address(this)), IERC20(_to).balanceOf(address(this)), 0, 0, msg.sender, now + 60 ); // Refund sender any remaining tokens IERC20(weth).safeTransfer( msg.sender, IERC20(weth).balanceOf(address(this)) ); IERC20(_to).safeTransfer(msg.sender, IERC20(_to).balanceOf(address(this))); } } contract CurveProxyLogic { using SafeMath for uint256; using SafeERC20 for IERC20; function remove_liquidity_one_coin( address curve, address curveLp, int128 index ) public { uint256 lpAmount = IERC20(curveLp).balanceOf(address(this)); IERC20(curveLp).safeApprove(curve, 0); IERC20(curveLp).safeApprove(curve, lpAmount); ICurveZap(curve).remove_liquidity_one_coin(lpAmount, index, 0); } function add_liquidity( address curve, bytes4 curveFunctionSig, uint256 curvePoolSize, uint256 curveUnderlyingIndex, address underlying ) public { uint256 underlyingAmount = IERC20(underlying).balanceOf(address(this)); // curveFunctionSig should be the abi.encodedFormat of // add_liquidity(uint256[N_COINS],uint256) // The reason why its here is because different curve pools // have a different function signature uint256[] memory liquidity = new uint256[](curvePoolSize); liquidity[curveUnderlyingIndex] = underlyingAmount; bytes memory callData = abi.encodePacked( curveFunctionSig, liquidity, uint256(0) ); IERC20(underlying).safeApprove(curve, 0); IERC20(underlying).safeApprove(curve, underlyingAmount); (bool success, ) = curve.call(callData); require(success, "!success"); } } contract UniswapV2ProxyLogic { using SafeMath for uint256; using SafeERC20 for IERC20; IUniswapV2Factory public constant factory = IUniswapV2Factory( 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f ); UniswapRouterV2 public constant router = UniswapRouterV2( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } function getSwapAmt(uint256 amtA, uint256 resA) internal pure returns (uint256) { return sqrt(amtA.mul(resA.mul(3988000).add(amtA.mul(3988009)))) .sub(amtA.mul(1997)) .div(1994); } // https://blog.alphafinance.io/onesideduniswap/ // https://github.com/AlphaFinanceLab/alphahomora/blob/88a8dfe4d4fa62b13b40f7983ee2c646f83e63b5/contracts/StrategyAddETHOnly.sol#L39 // AlphaFinance is gripbook licensed function optimalOneSideSupply( IUniswapV2Pair pair, address from, address to ) public { address[] memory path = new address[](2); // 1. Compute optimal amount of WETH to be converted (uint256 r0, uint256 r1, ) = pair.getReserves(); uint256 rIn = pair.token0() == from ? r0 : r1; uint256 aIn = getSwapAmt(rIn, IERC20(from).balanceOf(address(this))); // 2. Convert that from -> to path[0] = from; path[1] = to; IERC20(from).safeApprove(address(router), 0); IERC20(from).safeApprove(address(router), aIn); router.swapExactTokensForTokens(aIn, 0, path, address(this), now + 60); } function swapUniswap(address from, address to) public { require(to != address(0)); address[] memory path; if (from == weth || to == weth) { path = new address[](2); path[0] = from; path[1] = to; } else { path = new address[](3); path[0] = from; path[1] = weth; path[2] = to; } uint256 amount = IERC20(from).balanceOf(address(this)); IERC20(from).safeApprove(address(router), 0); IERC20(from).safeApprove(address(router), amount); router.swapExactTokensForTokens( amount, 0, path, address(this), now + 60 ); } function removeLiquidity(IUniswapV2Pair pair) public { uint256 _balance = pair.balanceOf(address(this)); pair.approve(address(router), _balance); router.removeLiquidity( pair.token0(), pair.token1(), _balance, 0, 0, address(this), now + 60 ); } function supplyLiquidity( address token0, address token1 ) public returns (uint256) { // Add liquidity to uniswap IERC20(token0).safeApprove(address(router), 0); IERC20(token0).safeApprove( address(router), IERC20(token0).balanceOf(address(this)) ); IERC20(token1).safeApprove(address(router), 0); IERC20(token1).safeApprove( address(router), IERC20(token1).balanceOf(address(this)) ); (, , uint256 _to) = router.addLiquidity( token0, token1, IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), 0, 0, address(this), now + 60 ); return _to; } function refundDust(IUniswapV2Pair pair, address recipient) public { address token0 = pair.token0(); address token1 = pair.token1(); IERC20(token0).safeTransfer( recipient, IERC20(token0).balanceOf(address(this)) ); IERC20(token1).safeTransfer( recipient, IERC20(token1).balanceOf(address(this)) ); } function lpTokensToPrimitive( IUniswapV2Pair from, address to ) public { if (from.token0() != weth && from.token1() != weth) { revert("!from-weth-pair"); } address fromOther = from.token0() == weth ? from.token1() : from.token0(); // Removes liquidity removeLiquidity(from); // Swap from WETH to other swapUniswap(weth, to); // If from is not to, we swap them too if (fromOther != to) { swapUniswap(fromOther, to); } } function primitiveToLpTokens( address from, IUniswapV2Pair to, address dustRecipient ) public { if (to.token0() != weth && to.token1() != weth) { revert("!to-weth-pair"); } address toOther = to.token0() == weth ? to.token1() : to.token0(); // Swap to WETH swapUniswap(from, weth); // Optimal supply from WETH to optimalOneSideSupply(to, weth, toOther); // Supply tokens supplyLiquidity(weth, toOther); // Dust refundDust(to, dustRecipient); } function swapUniLPTokens( IUniswapV2Pair from, IUniswapV2Pair to, address dustRecipient ) public { if (from.token0() != weth && from.token1() != weth) { revert("!from-weth-pair"); } if (to.token0() != weth && to.token1() != weth) { revert("!to-weth-pair"); } address fromOther = from.token0() == weth ? from.token1() : from.token0(); address toOther = to.token0() == weth ? to.token1() : to.token0(); // Remove weth-<token> pair removeLiquidity(from); // Swap <token> to WETH swapUniswap(fromOther, weth); // Optimal supply from WETH to <other-token> optimalOneSideSupply(to, weth, toOther); // Supply weth-<other-token> pair supplyLiquidity(weth, toOther); // Refund dust refundDust(to, dustRecipient); } } contract StakingRewards is ReentrancyGuard, Pausable { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ IERC20 public rewardsToken; IERC20 public stakingToken; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public rewardsDuration = 7 days; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 private _totalSupply; mapping(address => uint256) private _balances; /* ========== CONSTRUCTOR ========== */ constructor( address _owner, address _rewardsToken, address _stakingToken ) public Owned(_owner) { rewardsToken = IERC20(_rewardsToken); stakingToken = IERC20(_stakingToken); } /* ========== VIEWS ========== */ function totalSupply() external view returns (uint256) { return _totalSupply; } function balanceOf(address account) external view returns (uint256) { return _balances[account]; } function lastTimeRewardApplicable() public view returns (uint256) { return min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable() .sub(lastUpdateTime) .mul(rewardRate) .mul(1e18) .div(_totalSupply) ); } function earned(address account) public view returns (uint256) { return _balances[account] .mul(rewardPerToken().sub(userRewardPerTokenPaid[account])) .div(1e18) .add(rewards[account]); } function getRewardForDuration() external view returns (uint256) { return rewardRate.mul(rewardsDuration); } function min(uint256 a, uint256 b) public pure returns (uint256) { return a < b ? a : b; } /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint256 amount) external nonReentrant notPaused updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public nonReentrant updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakingToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } function getReward() public nonReentrant updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; rewardsToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function exit() external { withdraw(_balances[msg.sender]); getReward(); } /* ========== RESTRICTED FUNCTIONS ========== */ function notifyRewardAmount(uint256 reward) external onlyOwner updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(rewardsDuration); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(rewardsDuration); } // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint256 balance = rewardsToken.balanceOf(address(this)); require( rewardRate <= balance.div(rewardsDuration), "Provided reward too high" ); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardsDuration); emit RewardAdded(reward); } // Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyOwner { // Cannot recover the staking token or the rewards token require( tokenAddress != address(stakingToken) && tokenAddress != address(rewardsToken), "Cannot withdraw the staking or rewards tokens" ); IERC20(tokenAddress).safeTransfer(owner, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } function setRewardsDuration(uint256 _rewardsDuration) external onlyOwner { require( block.timestamp > periodFinish, "Previous rewards period must be complete before changing the duration for the new period" ); rewardsDuration = _rewardsDuration; emit RewardsDurationUpdated(rewardsDuration); } /* ========== MODIFIERS ========== */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event RewardsDurationUpdated(uint256 newDuration); event Recovered(address token, uint256 amount); } contract CRVLocker { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public constant mintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; address public constant crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant escrow = 0x5f3b5DfEb7B28CDbD7FAba78963EE202a494e2A2; address public governance; mapping(address => bool) public voters; constructor(address _governance) public { governance = _governance; } function getName() external pure returns (string memory) { return "CRVLocker"; } function addVoter(address _voter) external { require(msg.sender == governance, "!governance"); voters[_voter] = true; } function removeVoter(address _voter) external { require(msg.sender == governance, "!governance"); voters[_voter] = false; } function withdraw(address _asset) external returns (uint256 balance) { require(voters[msg.sender], "!voter"); balance = IERC20(_asset).balanceOf(address(this)); IERC20(_asset).safeTransfer(msg.sender, balance); } function createLock(uint256 _value, uint256 _unlockTime) external { require(voters[msg.sender] || msg.sender == governance, "!authorized"); IERC20(crv).safeApprove(escrow, 0); IERC20(crv).safeApprove(escrow, _value); ICurveVotingEscrow(escrow).create_lock(_value, _unlockTime); } function increaseAmount(uint256 _value) external { require(voters[msg.sender] || msg.sender == governance, "!authorized"); IERC20(crv).safeApprove(escrow, 0); IERC20(crv).safeApprove(escrow, _value); ICurveVotingEscrow(escrow).increase_amount(_value); } function increaseUnlockTime(uint256 _unlockTime) external { require(voters[msg.sender] || msg.sender == governance, "!authorized"); ICurveVotingEscrow(escrow).increase_unlock_time(_unlockTime); } function release() external { require(voters[msg.sender] || msg.sender == governance, "!authorized"); ICurveVotingEscrow(escrow).withdraw(); } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function execute( address to, uint256 value, bytes calldata data ) external returns (bool, bytes memory) { require(voters[msg.sender] || msg.sender == governance, "!governance"); (bool success, bytes memory result) = to.call{value: value}(data); require(success, "!execute-success"); return (success, result); } } contract SCRVVoter { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; CRVLocker public crvLocker; address public constant want = 0xC25a3A3b969415c80451098fa907EC722572917F; address public constant mintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; address public constant crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant snx = 0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F; address public constant gaugeController = 0x2F50D538606Fa9EDD2B11E2446BEb18C9D5846bB; address public constant scrvGauge = 0xA90996896660DEcC6E997655E065b23788857849; mapping(address => bool) public strategies; address public governance; constructor(address _governance, address _crvLocker) public { governance = _governance; crvLocker = CRVLocker(_crvLocker); } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function approveStrategy(address _strategy) external { require(msg.sender == governance, "!governance"); strategies[_strategy] = true; } function revokeStrategy(address _strategy) external { require(msg.sender == governance, "!governance"); strategies[_strategy] = false; } function lock() external { crvLocker.increaseAmount(IERC20(crv).balanceOf(address(crvLocker))); } function vote(address _gauge, uint256 _amount) public { require(strategies[msg.sender], "!strategy"); crvLocker.execute( gaugeController, 0, abi.encodeWithSignature( "vote_for_gauge_weights(address,uint256)", _gauge, _amount ) ); } function max() external { require(strategies[msg.sender], "!strategy"); vote(scrvGauge, 10000); } function withdraw( address _gauge, address _token, uint256 _amount ) public returns (uint256) { require(strategies[msg.sender], "!strategy"); uint256 _before = IERC20(_token).balanceOf(address(crvLocker)); crvLocker.execute( _gauge, 0, abi.encodeWithSignature("withdraw(uint256)", _amount) ); uint256 _after = IERC20(_token).balanceOf(address(crvLocker)); uint256 _net = _after.sub(_before); crvLocker.execute( _token, 0, abi.encodeWithSignature( "transfer(address,uint256)", msg.sender, _net ) ); return _net; } function balanceOf(address _gauge) public view returns (uint256) { return IERC20(_gauge).balanceOf(address(crvLocker)); } function withdrawAll(address _gauge, address _token) external returns (uint256) { require(strategies[msg.sender], "!strategy"); return withdraw(_gauge, _token, balanceOf(_gauge)); } function deposit(address _gauge, address _token) external { uint256 _balance = IERC20(_token).balanceOf(address(this)); IERC20(_token).safeTransfer(address(crvLocker), _balance); _balance = IERC20(_token).balanceOf(address(crvLocker)); crvLocker.execute( _token, 0, abi.encodeWithSignature("approve(address,uint256)", _gauge, 0) ); crvLocker.execute( _token, 0, abi.encodeWithSignature( "approve(address,uint256)", _gauge, _balance ) ); crvLocker.execute( _gauge, 0, abi.encodeWithSignature("deposit(uint256)", _balance) ); } function harvest(address _gauge) external { require(strategies[msg.sender], "!strategy"); uint256 _before = IERC20(crv).balanceOf(address(crvLocker)); crvLocker.execute( mintr, 0, abi.encodeWithSignature("mint(address)", _gauge) ); uint256 _after = IERC20(crv).balanceOf(address(crvLocker)); uint256 _balance = _after.sub(_before); crvLocker.execute( crv, 0, abi.encodeWithSignature( "transfer(address,uint256)", msg.sender, _balance ) ); } function claimRewards() external { require(strategies[msg.sender], "!strategy"); uint256 _before = IERC20(snx).balanceOf(address(crvLocker)); crvLocker.execute(scrvGauge, 0, abi.encodeWithSignature("claim_rewards()")); uint256 _after = IERC20(snx).balanceOf(address(crvLocker)); uint256 _balance = _after.sub(_before); crvLocker.execute( snx, 0, abi.encodeWithSignature( "transfer(address,uint256)", msg.sender, _balance ) ); } } abstract contract StrategyBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Perfomance fees - start with 4.5% uint256 public performanceTreasuryFee = 450; uint256 public constant performanceTreasuryMax = 10000; uint256 public performanceDevFee = 0; uint256 public constant performanceDevMax = 10000; // Withdrawal fee 0.5% // - 0.325% to treasury // - 0.175% to dev fund uint256 public withdrawalTreasuryFee = 325; uint256 public constant withdrawalTreasuryMax = 100000; uint256 public withdrawalDevFundFee = 175; uint256 public constant withdrawalDevFundMax = 100000; // Tokens address public want; address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // User accounts address public governance; address public controller; address public strategist; address public timelock; // Dex address public univ2Router2 = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor( address _want, address _governance, address _strategist, address _controller, address _timelock ) public { require(_want != address(0)); require(_governance != address(0)); require(_strategist != address(0)); require(_controller != address(0)); require(_timelock != address(0)); want = _want; governance = _governance; strategist = _strategist; controller = _controller; timelock = _timelock; } // **** Modifiers **** // modifier onlyBenevolent { require( msg.sender == tx.origin || msg.sender == governance || msg.sender == strategist ); _; } // **** Views **** // function balanceOfWant() public view returns (uint256) { return IERC20(want).balanceOf(address(this)); } function balanceOfPool() public virtual view returns (uint256); function balanceOf() public view returns (uint256) { return balanceOfWant().add(balanceOfPool()); } function getName() external virtual pure returns (string memory); // **** Setters **** // function setWithdrawalDevFundFee(uint256 _withdrawalDevFundFee) external { require(msg.sender == timelock, "!timelock"); withdrawalDevFundFee = _withdrawalDevFundFee; } function setWithdrawalTreasuryFee(uint256 _withdrawalTreasuryFee) external { require(msg.sender == timelock, "!timelock"); withdrawalTreasuryFee = _withdrawalTreasuryFee; } function setPerformanceDevFee(uint256 _performanceDevFee) external { require(msg.sender == timelock, "!timelock"); performanceDevFee = _performanceDevFee; } function setPerformanceTreasuryFee(uint256 _performanceTreasuryFee) external { require(msg.sender == timelock, "!timelock"); performanceTreasuryFee = _performanceTreasuryFee; } function setStrategist(address _strategist) external { require(msg.sender == governance, "!governance"); strategist = _strategist; } function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setTimelock(address _timelock) external { require(msg.sender == timelock, "!timelock"); timelock = _timelock; } function setController(address _controller) external { require(msg.sender == timelock, "!timelock"); controller = _controller; } // **** State mutations **** // function deposit() public virtual; // Controller only function for creating additional rewards from dust function withdraw(IERC20 _asset) external returns (uint256 balance) { require(msg.sender == controller, "!controller"); require(want != address(_asset), "want"); balance = _asset.balanceOf(address(this)); _asset.safeTransfer(controller, balance); } // Withdraw partial funds, normally used with a jar withdrawal function withdraw(uint256 _amount) external { require(msg.sender == controller, "!controller"); uint256 _balance = IERC20(want).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } uint256 _feeDev = _amount.mul(withdrawalDevFundFee).div( withdrawalDevFundMax ); IERC20(want).safeTransfer(IController(controller).devfund(), _feeDev); uint256 _feeTreasury = _amount.mul(withdrawalTreasuryFee).div( withdrawalTreasuryMax ); IERC20(want).safeTransfer( IController(controller).treasury(), _feeTreasury ); address _jar = IController(controller).jars(address(want)); require(_jar != address(0), "!jar"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_jar, _amount.sub(_feeDev).sub(_feeTreasury)); } // Withdraw funds, used to swap between strategies function withdrawForSwap(uint256 _amount) external returns (uint256 balance) { require(msg.sender == controller, "!controller"); _withdrawSome(_amount); balance = IERC20(want).balanceOf(address(this)); address _jar = IController(controller).jars(address(want)); require(_jar != address(0), "!jar"); IERC20(want).safeTransfer(_jar, balance); } // Withdraw all funds, normally used when migrating strategies function withdrawAll() external returns (uint256 balance) { require(msg.sender == controller, "!controller"); _withdrawAll(); balance = IERC20(want).balanceOf(address(this)); address _jar = IController(controller).jars(address(want)); require(_jar != address(0), "!jar"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_jar, balance); } function _withdrawAll() internal { _withdrawSome(balanceOfPool()); } function _withdrawSome(uint256 _amount) internal virtual returns (uint256); function harvest() public virtual; // **** Emergency functions **** function execute(address _target, bytes memory _data) public payable returns (bytes memory response) { require(msg.sender == timelock, "!timelock"); require(_target != address(0), "!target"); // call contract in current context assembly { let succeeded := delegatecall( sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0 ) let size := returndatasize() response := mload(0x40) mstore( 0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f))) ) mstore(response, size) returndatacopy(add(response, 0x20), 0, size) switch iszero(succeeded) case 1 { // throw if delegatecall failed revert(add(response, 0x20), size) } } } // **** Internal functions **** function _swapUniswap( address _from, address _to, uint256 _amount ) internal { require(_to != address(0)); // Swap with uniswap IERC20(_from).safeApprove(univ2Router2, 0); IERC20(_from).safeApprove(univ2Router2, _amount); address[] memory path; if (_from == weth || _to == weth) { path = new address[](2); path[0] = _from; path[1] = _to; } else { path = new address[](3); path[0] = _from; path[1] = weth; path[2] = _to; } UniswapRouterV2(univ2Router2).swapExactTokensForTokens( _amount, 0, path, address(this), now.add(60) ); } function _distributePerformanceFeesAndDeposit() internal { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { // Treasury fees IERC20(want).safeTransfer( IController(controller).treasury(), _want.mul(performanceTreasuryFee).div(performanceTreasuryMax) ); // Performance fee IERC20(want).safeTransfer( IController(controller).devfund(), _want.mul(performanceDevFee).div(performanceDevMax) ); deposit(); } } } abstract contract StrategyCurveBase is StrategyBase { // curve dao address public gauge; address public curve; address public mintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // stablecoins address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address public susd = 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51; // bitcoins address public wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; address public renbtc = 0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D; // rewards address public crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; // How much CRV tokens to keep uint256 public keepCRV = 0; uint256 public keepCRVMax = 10000; constructor( address _curve, address _gauge, address _want, address _governance, address _strategist, address _controller, address _timelock ) public StrategyBase(_want, _governance, _strategist, _controller, _timelock) { curve = _curve; gauge = _gauge; } // **** Getters **** function balanceOfPool() public override view returns (uint256) { return ICurveGauge(gauge).balanceOf(address(this)); } function getHarvestable() external returns (uint256) { return ICurveGauge(gauge).claimable_tokens(address(this)); } function getMostPremium() public virtual view returns (address, uint256); // **** Setters **** function setKeepCRV(uint256 _keepCRV) external { require(msg.sender == governance, "!governance"); keepCRV = _keepCRV; } // **** State Mutation functions **** function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(gauge, 0); IERC20(want).safeApprove(gauge, _want); ICurveGauge(gauge).deposit(_want); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { ICurveGauge(gauge).withdraw(_amount); return _amount; } } abstract contract StrategyStakingRewardsBase is StrategyBase { address public rewards; // **** Getters **** constructor( address _rewards, address _want, address _governance, address _strategist, address _controller, address _timelock ) public StrategyBase(_want, _governance, _strategist, _controller, _timelock) { rewards = _rewards; } function balanceOfPool() public override view returns (uint256) { return IStakingRewards(rewards).balanceOf(address(this)); } function getHarvestable() external view returns (uint256) { return IStakingRewards(rewards).earned(address(this)); } // **** Setters **** function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(rewards, 0); IERC20(want).safeApprove(rewards, _want); IStakingRewards(rewards).stake(_want); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { IStakingRewards(rewards).withdraw(_amount); return _amount; } } abstract contract StrategyUniFarmBase is StrategyStakingRewardsBase { // Token addresses address public uni = 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984; // WETH/<token1> pair address public token1; // How much UNI tokens to keep? uint256 public keepUNI = 0; uint256 public constant keepUNIMax = 10000; constructor( address _token1, address _rewards, address _lp, address _governance, address _strategist, address _controller, address _timelock ) public StrategyStakingRewardsBase( _rewards, _lp, _governance, _strategist, _controller, _timelock ) { token1 = _token1; } // **** Setters **** function setKeepUNI(uint256 _keepUNI) external { require(msg.sender == timelock, "!timelock"); keepUNI = _keepUNI; } // **** State Mutations **** function harvest() public override onlyBenevolent { // Anyone can harvest it at any given time. // I understand the possibility of being frontrun // But ETH is a dark forest, and I wanna see how this plays out // i.e. will be be heavily frontrunned? // if so, a new strategy will be deployed. // Collects UNI tokens IStakingRewards(rewards).getReward(); uint256 _uni = IERC20(uni).balanceOf(address(this)); if (_uni > 0) { // 10% is locked up for future gov uint256 _keepUNI = _uni.mul(keepUNI).div(keepUNIMax); IERC20(uni).safeTransfer( IController(controller).treasury(), _keepUNI ); _swapUniswap(uni, weth, _uni.sub(_keepUNI)); } // Swap half WETH for DAI uint256 _weth = IERC20(weth).balanceOf(address(this)); if (_weth > 0) { _swapUniswap(weth, token1, _weth.div(2)); } // Adds in liquidity for ETH/DAI _weth = IERC20(weth).balanceOf(address(this)); uint256 _token1 = IERC20(token1).balanceOf(address(this)); if (_weth > 0 && _token1 > 0) { IERC20(weth).safeApprove(univ2Router2, 0); IERC20(weth).safeApprove(univ2Router2, _weth); IERC20(token1).safeApprove(univ2Router2, 0); IERC20(token1).safeApprove(univ2Router2, _token1); UniswapRouterV2(univ2Router2).addLiquidity( weth, token1, _weth, _token1, 0, 0, address(this), now + 60 ); // Donates DUST IERC20(weth).transfer( IController(controller).treasury(), IERC20(weth).balanceOf(address(this)) ); IERC20(token1).safeTransfer( IController(controller).treasury(), IERC20(token1).balanceOf(address(this)) ); } // We want to get back UNI LP tokens _distributePerformanceFeesAndDeposit(); } } contract StrategyUniEthDaiLpV4 is StrategyUniFarmBase { // Token addresses address public uni_rewards = 0xa1484C3aa22a66C62b77E0AE78E15258bd0cB711; address public uni_eth_dai_lp = 0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11; address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyUniFarmBase( dai, uni_rewards, uni_eth_dai_lp, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getName() external override pure returns (string memory) { return "StrategyUniEthDaiLpV4"; } } contract StrategyUniEthUsdcLpV4 is StrategyUniFarmBase { // Token addresses address public uni_rewards = 0x7FBa4B8Dc5E7616e59622806932DBea72537A56b; address public uni_eth_usdc_lp = 0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc; address public usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyUniFarmBase( usdc, uni_rewards, uni_eth_usdc_lp, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getName() external override pure returns (string memory) { return "StrategyUniEthUsdcLpV4"; } } contract StrategyUniEthUsdtLpV4 is StrategyUniFarmBase { // Token addresses address public uni_rewards = 0x6C3e4cb2E96B01F4b866965A91ed4437839A121a; address public uni_eth_usdt_lp = 0x0d4a11d5EEaaC28EC3F61d100daF4d40471f1852; address public usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyUniFarmBase( usdt, uni_rewards, uni_eth_usdt_lp, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getName() external override pure returns (string memory) { return "StrategyUniEthUsdtLpV4"; } } contract StrategyUniEthWBtcLpV2 is StrategyUniFarmBase { // Token addresses address public uni_rewards = 0xCA35e32e7926b96A9988f61d510E038108d8068e; address public uni_eth_wbtc_lp = 0xBb2b8038a1640196FbE3e38816F3e67Cba72D940; address public wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyUniFarmBase( wbtc, uni_rewards, uni_eth_wbtc_lp, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getName() external override pure returns (string memory) { return "StrategyUniEthWBtcLpV2"; } } interface Hevm { function warp(uint256) external; function roll(uint x) external; function store(address c, bytes32 loc, bytes32 val) external; } contract MockERC20 is ERC20 { constructor(string memory name, string memory symbol) public ERC20(name, symbol) {} function mint(address recipient, uint256 amount) public { _mint(recipient, amount); } } contract DSTest { event eventListener (address target, bool exact); event logs (bytes); event log_bytes32 (bytes32); event log_named_address (bytes32 key, address val); event log_named_bytes32 (bytes32 key, bytes32 val); event log_named_decimal_int (bytes32 key, int val, uint decimals); event log_named_decimal_uint (bytes32 key, uint val, uint decimals); event log_named_int (bytes32 key, int val); event log_named_uint (bytes32 key, uint val); event log_named_string (bytes32 key, string val); bool public IS_TEST; bool public failed; constructor() internal { IS_TEST = true; } function fail() internal { failed = true; } function expectEventsExact(address target) internal { emit eventListener(target, true); } modifier logs_gas() { uint startGas = gasleft(); _; uint endGas = gasleft(); emit log_named_uint("gas", startGas - endGas); } function assertTrue(bool condition) internal { if (!condition) { emit log_bytes32("Assertion failed"); fail(); } } function assertEq(address a, address b) internal { if (a != b) { emit log_bytes32("Error: Wrong `address' value"); emit log_named_address(" Expected", b); emit log_named_address(" Actual", a); fail(); } } function assertEq32(bytes32 a, bytes32 b) internal { assertEq(a, b); } function assertEq(bytes32 a, bytes32 b) internal { if (a != b) { emit log_bytes32("Error: Wrong `bytes32' value"); emit log_named_bytes32(" Expected", b); emit log_named_bytes32(" Actual", a); fail(); } } function assertEqDecimal(int a, int b, uint decimals) internal { if (a != b) { emit log_bytes32("Error: Wrong fixed-point decimal"); emit log_named_decimal_int(" Expected", b, decimals); emit log_named_decimal_int(" Actual", a, decimals); fail(); } } function assertEqDecimal(uint a, uint b, uint decimals) internal { if (a != b) { emit log_bytes32("Error: Wrong fixed-point decimal"); emit log_named_decimal_uint(" Expected", b, decimals); emit log_named_decimal_uint(" Actual", a, decimals); fail(); } } function assertEq(int a, int b) internal { if (a != b) { emit log_bytes32("Error: Wrong `int' value"); emit log_named_int(" Expected", b); emit log_named_int(" Actual", a); fail(); } } function assertEq(uint a, uint b) internal { if (a != b) { emit log_bytes32("Error: Wrong `uint' value"); emit log_named_uint(" Expected", b); emit log_named_uint(" Actual", a); fail(); } } function assertEq(string memory a, string memory b) internal { if (keccak256(abi.encodePacked(a)) != keccak256(abi.encodePacked(b))) { emit log_bytes32("Error: Wrong `string' value"); emit log_named_string(" Expected", b); emit log_named_string(" Actual", a); fail(); } } function assertEq0(bytes memory a, bytes memory b) internal { bool ok = true; if (a.length == b.length) { for (uint i = 0; i < a.length; i++) { if (a[i] != b[i]) { ok = false; } } } else { ok = false; } if (!ok) { emit log_bytes32("Error: Wrong `bytes' value"); emit log_named_bytes32(" Expected", "[cannot show `bytes' value]"); emit log_named_bytes32(" Actual", "[cannot show `bytes' value]"); fail(); } } } contract User { function execute( address target, uint256 value, string memory signature, bytes memory data ) public payable returns (bytes memory) { bytes memory callData; if (bytes(signature).length == 0) { callData = data; } else { callData = abi.encodePacked( bytes4(keccak256(bytes(signature))), data ); } (bool success, bytes memory returnData) = target.call{value: value}( callData ); require(success, "!user-execute"); return returnData; } } contract StakngRewardsTest is DSTest { using SafeMath for uint256; MockERC20 stakingToken; MockERC20 rewardsToken; StakingRewards stakingRewards; address owner; Hevm hevm = Hevm(0x7109709ECfa91a80626fF3989D68f67F5b1DD12D); function setUp() public { owner = address(this); stakingToken = new MockERC20("staking", "STAKE"); rewardsToken = new MockERC20("rewards", "RWD"); stakingRewards = new StakingRewards( owner, address(rewardsToken), address(stakingToken) ); } function test_staking() public { uint256 stakeAmount = 100 ether; uint256 rewardAmount = 100 ether; stakingToken.mint(owner, stakeAmount); rewardsToken.mint(owner, rewardAmount); stakingToken.approve(address(stakingRewards), stakeAmount); stakingRewards.stake(stakeAmount); // // Make sure nothing is earned uint256 _before = stakingRewards.earned(owner); assertEq(_before, 0); // Fast forward hevm.warp(block.timestamp + 1 days); // No funds until we actually supply funds uint256 _after = stakingRewards.earned(owner); assertEq(_after, _before); // Give rewards rewardsToken.transfer(address(stakingRewards), rewardAmount); stakingRewards.notifyRewardAmount(rewardAmount); uint256 _rateBefore = stakingRewards.getRewardForDuration(); assertTrue(_rateBefore > 0); // Fast forward _before = stakingRewards.earned(owner); hevm.warp(block.timestamp + 1 days); _after = stakingRewards.earned(owner); assertTrue(_after > _before); assertTrue(_after > 0); // Add more rewards, rate should increase rewardsToken.mint(owner, rewardAmount); rewardsToken.transfer(address(stakingRewards), rewardAmount); stakingRewards.notifyRewardAmount(rewardAmount); uint256 _rateAfter = stakingRewards.getRewardForDuration(); assertTrue(_rateAfter > _rateBefore); // Warp to period finish hevm.warp(stakingRewards.periodFinish() + 1 days); // Retrieve tokens stakingRewards.getReward(); _before = stakingRewards.earned(owner); hevm.warp(block.timestamp + 1 days); _after = stakingRewards.earned(owner); // Earn 0 after period finished assertEq(_before, 0); assertEq(_after, 0); } } contract UniCurveConverter { using SafeMath for uint256; using SafeERC20 for IERC20; UniswapRouterV2 public router = UniswapRouterV2( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); // Stablecoins address public constant dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public constant usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address public constant susd = 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51; // Wrapped stablecoins address public constant scrv = 0xC25a3A3b969415c80451098fa907EC722572917F; // Weth address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // susd v2 pool ICurveFi_4 public curve = ICurveFi_4( 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD ); // UNI LP -> Curve LP // Assume th function convert(address _lp, uint256 _amount) public { // Get LP Tokens IERC20(_lp).safeTransferFrom(msg.sender, address(this), _amount); // Get Uniswap pair IUniswapV2Pair fromPair = IUniswapV2Pair(_lp); // Only for WETH/<TOKEN> pairs if (!(fromPair.token0() == weth || fromPair.token1() == weth)) { revert("!eth-from"); } // Remove liquidity IERC20(_lp).safeApprove(address(router), 0); IERC20(_lp).safeApprove(address(router), _amount); router.removeLiquidity( fromPair.token0(), fromPair.token1(), _amount, 0, 0, address(this), now + 60 ); // Most premium stablecoin (address premiumStablecoin, ) = getMostPremium(); // Convert weth -> most premium stablecoin address[] memory path = new address[](2); path[0] = weth; path[1] = premiumStablecoin; IERC20(weth).safeApprove(address(router), 0); IERC20(weth).safeApprove(address(router), uint256(-1)); router.swapExactTokensForTokens( IERC20(weth).balanceOf(address(this)), 0, path, address(this), now + 60 ); // Convert the other asset into stablecoin if its not a stablecoin address _from = fromPair.token0() != weth ? fromPair.token0() : fromPair.token1(); if (_from != dai && _from != usdc && _from != usdt && _from != susd) { path = new address[](3); path[0] = _from; path[1] = weth; path[2] = premiumStablecoin; IERC20(_from).safeApprove(address(router), 0); IERC20(_from).safeApprove(address(router), uint256(-1)); router.swapExactTokensForTokens( IERC20(_from).balanceOf(address(this)), 0, path, address(this), now + 60 ); } // Add liquidity to curve IERC20(dai).safeApprove(address(curve), 0); IERC20(dai).safeApprove(address(curve), uint256(-1)); IERC20(usdc).safeApprove(address(curve), 0); IERC20(usdc).safeApprove(address(curve), uint256(-1)); IERC20(usdt).safeApprove(address(curve), 0); IERC20(usdt).safeApprove(address(curve), uint256(-1)); IERC20(susd).safeApprove(address(curve), 0); IERC20(susd).safeApprove(address(curve), uint256(-1)); curve.add_liquidity( [ IERC20(dai).balanceOf(address(this)), IERC20(usdc).balanceOf(address(this)), IERC20(usdt).balanceOf(address(this)), IERC20(susd).balanceOf(address(this)) ], 0 ); // Sends token back to user IERC20(scrv).transfer( msg.sender, IERC20(scrv).balanceOf(address(this)) ); } function getMostPremium() public view returns (address, uint256) { uint256[] memory balances = new uint256[](4); balances[0] = ICurveFi_4(curve).balances(0); // DAI balances[1] = ICurveFi_4(curve).balances(1).mul(10**12); // USDC balances[2] = ICurveFi_4(curve).balances(2).mul(10**12); // USDT balances[3] = ICurveFi_4(curve).balances(3); // sUSD // DAI if ( balances[0] < balances[1] && balances[0] < balances[2] && balances[0] < balances[3] ) { return (dai, 0); } // USDC if ( balances[1] < balances[0] && balances[1] < balances[2] && balances[1] < balances[3] ) { return (usdc, 1); } // USDT if ( balances[2] < balances[0] && balances[2] < balances[1] && balances[2] < balances[3] ) { return (usdt, 2); } // SUSD if ( balances[3] < balances[0] && balances[3] < balances[1] && balances[3] < balances[2] ) { return (susd, 3); } // If they're somehow equal, we just want DAI return (dai, 0); } } interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval( address indexed owner, address indexed spender, uint256 value ); } interface MasterChef { function userInfo(uint256, address) external view returns (uint256, uint256); } contract PickleVoteProxy { // ETH/PICKLE token IERC20 public constant votes = IERC20( 0xdc98556Ce24f007A5eF6dC1CE96322d65832A819 ); // Pickle's masterchef contract MasterChef public constant chef = MasterChef( 0xbD17B1ce622d73bD438b9E658acA5996dc394b0d ); // Pool 0 is the ETH/PICKLE pool uint256 public constant pool = uint256(0); // Using 9 decimals as we're square rooting the votes function decimals() external pure returns (uint8) { return uint8(9); } function name() external pure returns (string memory) { return "PICKLEs In The Citadel"; } function symbol() external pure returns (string memory) { return "PICKLE C"; } function totalSupply() external view returns (uint256) { return sqrt(votes.totalSupply()); } function balanceOf(address _voter) external view returns (uint256) { (uint256 _votes, ) = chef.userInfo(pool, _voter); return sqrt(_votes); } function sqrt(uint256 x) public pure returns (uint256 y) { uint256 z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } constructor() public {} } contract MasterChef is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of PICKLEs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accPicklePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accPicklePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. PICKLEs to distribute per block. uint256 lastRewardBlock; // Last block number that PICKLEs distribution occurs. uint256 accPicklePerShare; // Accumulated PICKLEs per share, times 1e12. See below. } // The PICKLE TOKEN! PickleToken public pickle; // Dev fund (2%, initially) uint256 public devFundDivRate = 50; // Dev address. address public devaddr; // Block number when bonus PICKLE period ends. uint256 public bonusEndBlock; // PICKLE tokens created per block. uint256 public picklePerBlock; // Bonus muliplier for early pickle makers. uint256 public constant BONUS_MULTIPLIER = 10; // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; // The block number when PICKLE mining starts. uint256 public startBlock; // Events event Recovered(address token, uint256 amount); event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); constructor( PickleToken _pickle, address _devaddr, uint256 _picklePerBlock, uint256 _startBlock, uint256 _bonusEndBlock ) public { pickle = _pickle; devaddr = _devaddr; picklePerBlock = _picklePerBlock; bonusEndBlock = _bonusEndBlock; startBlock = _startBlock; } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add( uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push( PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accPicklePerShare: 0 }) ); } // Update the given pool's PICKLE allocation point. Can only be called by the owner. function set( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add( _allocPoint ); poolInfo[_pid].allocPoint = _allocPoint; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) { if (_to <= bonusEndBlock) { return _to.sub(_from).mul(BONUS_MULTIPLIER); } else if (_from >= bonusEndBlock) { return _to.sub(_from); } else { return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add( _to.sub(bonusEndBlock) ); } } // View function to see pending PICKLEs on frontend. function pendingPickle(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accPicklePerShare = pool.accPicklePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = getMultiplier( pool.lastRewardBlock, block.number ); uint256 pickleReward = multiplier .mul(picklePerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); accPicklePerShare = accPicklePerShare.add( pickleReward.mul(1e12).div(lpSupply) ); } return user.amount.mul(accPicklePerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 pickleReward = multiplier .mul(picklePerBlock) .mul(pool.allocPoint) .div(totalAllocPoint); pickle.mint(devaddr, pickleReward.div(devFundDivRate)); pickle.mint(address(this), pickleReward); pool.accPicklePerShare = pool.accPicklePerShare.add( pickleReward.mul(1e12).div(lpSupply) ); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for PICKLE allocation. function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user .amount .mul(pool.accPicklePerShare) .div(1e12) .sub(user.rewardDebt); safePickleTransfer(msg.sender, pending); } pool.lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accPicklePerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pending = user.amount.mul(pool.accPicklePerShare).div(1e12).sub( user.rewardDebt ); safePickleTransfer(msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accPicklePerShare).div(1e12); pool.lpToken.safeTransfer(address(msg.sender), _amount); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; pool.lpToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; } // Safe pickle transfer function, just in case if rounding error causes pool to not have enough PICKLEs. function safePickleTransfer(address _to, uint256 _amount) internal { uint256 pickleBal = pickle.balanceOf(address(this)); if (_amount > pickleBal) { pickle.transfer(_to, pickleBal); } else { pickle.transfer(_to, _amount); } } // Update dev address by the previous dev. function dev(address _devaddr) public { require(msg.sender == devaddr, "dev: wut?"); devaddr = _devaddr; } // **** Additional functions separate from the original masterchef contract **** function setPicklePerBlock(uint256 _picklePerBlock) public onlyOwner { require(_picklePerBlock > 0, "!picklePerBlock-0"); picklePerBlock = _picklePerBlock; } function setBonusEndBlock(uint256 _bonusEndBlock) public onlyOwner { bonusEndBlock = _bonusEndBlock; } function setDevFundDivRate(uint256 _devFundDivRate) public onlyOwner { require(_devFundDivRate > 0, "!devFundDivRate-0"); devFundDivRate = _devFundDivRate; } } contract PickleToken is ERC20("PickleToken", "PICKLE"), Ownable { /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); } } interface IJar is IERC20 { function token() external view returns (address); function claimInsurance() external; // NOTE: Only yDelegatedVault implements this function getRatio() external view returns (uint256); function deposit(uint256) external; function withdraw(uint256) external; function earn() external; function decimals() external view returns (uint8); } contract StrategyCmpdDaiV2 is StrategyBase, Exponential { address public constant comptroller = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; address public constant lens = 0xd513d22422a3062Bd342Ae374b4b9c20E0a9a074; address public constant dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant comp = 0xc00e94Cb662C3520282E6f5717214004A7f26888; address public constant cdai = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; address public constant cether = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; // Require a 0.1 buffer between // market collateral factor and strategy's collateral factor // when leveraging uint256 colFactorLeverageBuffer = 100; uint256 colFactorLeverageBufferMax = 1000; // Allow a 0.05 buffer // between market collateral factor and strategy's collateral factor // until we have to deleverage // This is so we can hit max leverage and keep accruing interest uint256 colFactorSyncBuffer = 50; uint256 colFactorSyncBufferMax = 1000; // Keeper bots // Maintain leverage within buffer mapping(address => bool) keepers; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyBase(dai, _governance, _strategist, _controller, _timelock) { // Enter cDAI Market address[] memory ctokens = new address[](1); ctokens[0] = cdai; IComptroller(comptroller).enterMarkets(ctokens); } // **** Modifiers **** // modifier onlyKeepers { require( keepers[msg.sender] || msg.sender == address(this) || msg.sender == strategist || msg.sender == governance, "!keepers" ); _; } // **** Views **** // function getName() external override pure returns (string memory) { return "StrategyCmpdDaiV2"; } function getSuppliedView() public view returns (uint256) { (, uint256 cTokenBal, , uint256 exchangeRate) = ICToken(cdai) .getAccountSnapshot(address(this)); (, uint256 bal) = mulScalarTruncate( Exp({mantissa: exchangeRate}), cTokenBal ); return bal; } function getBorrowedView() public view returns (uint256) { return ICToken(cdai).borrowBalanceStored(address(this)); } function balanceOfPool() public override view returns (uint256) { uint256 supplied = getSuppliedView(); uint256 borrowed = getBorrowedView(); return supplied.sub(borrowed); } // Given an unleveraged supply balance, return the target // leveraged supply balance which is still within the safety buffer function getLeveragedSupplyTarget(uint256 supplyBalance) public view returns (uint256) { uint256 leverage = getMaxLeverage(); return supplyBalance.mul(leverage).div(1e18); } function getSafeLeverageColFactor() public view returns (uint256) { uint256 colFactor = getMarketColFactor(); // Collateral factor within the buffer uint256 safeColFactor = colFactor.sub( colFactorLeverageBuffer.mul(1e18).div(colFactorLeverageBufferMax) ); return safeColFactor; } function getSafeSyncColFactor() public view returns (uint256) { uint256 colFactor = getMarketColFactor(); // Collateral factor within the buffer uint256 safeColFactor = colFactor.sub( colFactorSyncBuffer.mul(1e18).div(colFactorSyncBufferMax) ); return safeColFactor; } function getMarketColFactor() public view returns (uint256) { (, uint256 colFactor) = IComptroller(comptroller).markets(cdai); return colFactor; } // Max leverage we can go up to, w.r.t safe buffer function getMaxLeverage() public view returns (uint256) { uint256 safeLeverageColFactor = getSafeLeverageColFactor(); // Infinite geometric series uint256 leverage = uint256(1e36).div(1e18 - safeLeverageColFactor); return leverage; } // **** Pseudo-view functions (use `callStatic` on these) **** // /* The reason why these exists is because of the nature of the interest accruing supply + borrow balance. The "view" methods are technically snapshots and don't represent the real value. As such there are pseudo view methods where you can retrieve the results by calling `callStatic`. */ function getCompAccrued() public returns (uint256) { (, , , uint256 accrued) = ICompoundLens(lens).getCompBalanceMetadataExt( comp, comptroller, address(this) ); return accrued; } function getColFactor() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); return borrowed.mul(1e18).div(supplied); } function getSuppliedUnleveraged() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); return supplied.sub(borrowed); } function getSupplied() public returns (uint256) { return ICToken(cdai).balanceOfUnderlying(address(this)); } function getBorrowed() public returns (uint256) { return ICToken(cdai).borrowBalanceCurrent(address(this)); } function getBorrowable() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); (, uint256 colFactor) = IComptroller(comptroller).markets(cdai); // 99.99% just in case some dust accumulates return supplied.mul(colFactor).div(1e18).sub(borrowed).mul(9999).div( 10000 ); } function getCurrentLeverage() public returns (uint256) { uint256 supplied = getSupplied(); uint256 borrowed = getBorrowed(); return supplied.mul(1e18).div(supplied.sub(borrowed)); } // **** Setters **** // function addKeeper(address _keeper) public { require( msg.sender == governance || msg.sender == strategist, "!governance" ); keepers[_keeper] = true; } function removeKeeper(address _keeper) public { require( msg.sender == governance || msg.sender == strategist, "!governance" ); keepers[_keeper] = false; } function setColFactorLeverageBuffer(uint256 _colFactorLeverageBuffer) public { require( msg.sender == governance || msg.sender == strategist, "!governance" ); colFactorLeverageBuffer = _colFactorLeverageBuffer; } function setColFactorSyncBuffer(uint256 _colFactorSyncBuffer) public { require( msg.sender == governance || msg.sender == strategist, "!governance" ); colFactorSyncBuffer = _colFactorSyncBuffer; } // **** State mutations **** // // Do a `callStatic` on this. // If it returns true then run it for realz. (i.e. eth_signedTx, not eth_call) function sync() public returns (bool) { uint256 colFactor = getColFactor(); uint256 safeSyncColFactor = getSafeSyncColFactor(); // If we're not safe if (colFactor > safeSyncColFactor) { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 idealSupply = getLeveragedSupplyTarget(unleveragedSupply); deleverageUntil(idealSupply); return true; } return false; } function leverageToMax() public { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 idealSupply = getLeveragedSupplyTarget(unleveragedSupply); leverageUntil(idealSupply); } // Leverages until we're supplying <x> amount // 1. Redeem <x> DAI // 2. Repay <x> DAI function leverageUntil(uint256 _supplyAmount) public onlyKeepers { // 1. Borrow out <X> DAI // 2. Supply <X> DAI uint256 leverage = getMaxLeverage(); uint256 unleveragedSupply = getSuppliedUnleveraged(); require( _supplyAmount >= unleveragedSupply && _supplyAmount <= unleveragedSupply.mul(leverage).div(1e18), "!leverage" ); // Since we're only leveraging one asset // Supplied = borrowed uint256 _borrowAndSupply; uint256 supplied = getSupplied(); while (supplied < _supplyAmount) { _borrowAndSupply = getBorrowable(); if (supplied.add(_borrowAndSupply) > _supplyAmount) { _borrowAndSupply = _supplyAmount.sub(supplied); } ICToken(cdai).borrow(_borrowAndSupply); deposit(); supplied = supplied.add(_borrowAndSupply); } } function deleverageToMin() public { uint256 unleveragedSupply = getSuppliedUnleveraged(); deleverageUntil(unleveragedSupply); } // Deleverages until we're supplying <x> amount // 1. Redeem <x> DAI // 2. Repay <x> DAI function deleverageUntil(uint256 _supplyAmount) public onlyKeepers { uint256 unleveragedSupply = getSuppliedUnleveraged(); uint256 supplied = getSupplied(); require( _supplyAmount >= unleveragedSupply && _supplyAmount <= supplied, "!deleverage" ); // Since we're only leveraging on 1 asset // redeemable = borrowable uint256 _redeemAndRepay = getBorrowable(); do { if (supplied.sub(_redeemAndRepay) < _supplyAmount) { _redeemAndRepay = supplied.sub(_supplyAmount); } require( ICToken(cdai).redeemUnderlying(_redeemAndRepay) == 0, "!redeem" ); IERC20(dai).safeApprove(cdai, 0); IERC20(dai).safeApprove(cdai, _redeemAndRepay); require(ICToken(cdai).repayBorrow(_redeemAndRepay) == 0, "!repay"); supplied = supplied.sub(_redeemAndRepay); } while (supplied > _supplyAmount); } function harvest() public override onlyBenevolent { address[] memory ctokens = new address[](1); ctokens[0] = cdai; IComptroller(comptroller).claimComp(address(this), ctokens); uint256 _comp = IERC20(comp).balanceOf(address(this)); if (_comp > 0) { _swapUniswap(comp, want, _comp); } _distributePerformanceFeesAndDeposit(); } function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(cdai, 0); IERC20(want).safeApprove(cdai, _want); require(ICToken(cdai).mint(_want) == 0, "!deposit"); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { uint256 _want = balanceOfWant(); if (_want < _amount) { uint256 _redeem = _amount.sub(_want); // Make sure market can cover liquidity require(ICToken(cdai).getCash() >= _redeem, "!cash-liquidity"); // How much borrowed amount do we need to free? uint256 borrowed = getBorrowed(); uint256 supplied = getSupplied(); uint256 curLeverage = getCurrentLeverage(); uint256 borrowedToBeFree = _redeem.mul(curLeverage).div(1e18); // If the amount we need to free is > borrowed // Just free up all the borrowed amount if (borrowedToBeFree > borrowed) { this.deleverageToMin(); } else { // Otherwise just keep freeing up borrowed amounts until // we hit a safe number to redeem our underlying this.deleverageUntil(supplied.sub(borrowedToBeFree)); } // Redeems underlying require(ICToken(cdai).redeemUnderlying(_redeem) == 0, "!redeem"); } return _amount; } } contract StrategyCurve3CRVv2 is StrategyCurveBase { // Curve stuff address public three_pool = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; address public three_gauge = 0xbFcF63294aD7105dEa65aA58F8AE5BE2D9d0952A; address public three_crv = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyCurveBase( three_pool, three_gauge, three_crv, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getMostPremium() public override view returns (address, uint256) { uint256[] memory balances = new uint256[](3); balances[0] = ICurveFi_3(curve).balances(0); // DAI balances[1] = ICurveFi_3(curve).balances(1).mul(10**12); // USDC balances[2] = ICurveFi_3(curve).balances(2).mul(10**12); // USDT // DAI if ( balances[0] < balances[1] && balances[0] < balances[2] ) { return (dai, 0); } // USDC if ( balances[1] < balances[0] && balances[1] < balances[2] ) { return (usdc, 1); } // USDT if ( balances[2] < balances[0] && balances[2] < balances[1] ) { return (usdt, 2); } // If they're somehow equal, we just want DAI return (dai, 0); } function getName() external override pure returns (string memory) { return "StrategyCurve3CRVv2"; } // **** State Mutations **** function harvest() public onlyBenevolent override { // Anyone can harvest it at any given time. // I understand the possibility of being frontrun // But ETH is a dark forest, and I wanna see how this plays out // i.e. will be be heavily frontrunned? // if so, a new strategy will be deployed. // stablecoin we want to convert to (address to, uint256 toIndex) = getMostPremium(); // Collects crv tokens // Don't bother voting in v1 ICurveMintr(mintr).mint(gauge); uint256 _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { // x% is sent back to the rewards holder // to be used to lock up in as veCRV in a future date uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax); if (_keepCRV > 0) { IERC20(crv).safeTransfer( IController(controller).treasury(), _keepCRV ); } _crv = _crv.sub(_keepCRV); _swapUniswap(crv, to, _crv); } // Adds liquidity to curve.fi's pool // to get back want (scrv) uint256 _to = IERC20(to).balanceOf(address(this)); if (_to > 0) { IERC20(to).safeApprove(curve, 0); IERC20(to).safeApprove(curve, _to); uint256[3] memory liquidity; liquidity[toIndex] = _to; ICurveFi_3(curve).add_liquidity(liquidity, 0); } _distributePerformanceFeesAndDeposit(); } } contract StrategyCurveRenCRVv2 is StrategyCurveBase { // https://www.curve.fi/ren // Curve stuff address public ren_pool = 0x93054188d876f558f4a66B2EF1d97d16eDf0895B; address public ren_gauge = 0xB1F2cdeC61db658F091671F5f199635aEF202CAC; address public ren_crv = 0x49849C98ae39Fff122806C06791Fa73784FB3675; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyCurveBase( ren_pool, ren_gauge, ren_crv, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getMostPremium() public override view returns (address, uint256) { // Both 8 decimals, so doesn't matter uint256[] memory balances = new uint256[](3); balances[0] = ICurveFi_2(curve).balances(0); // RENBTC balances[1] = ICurveFi_2(curve).balances(1); // WBTC // renbtc if (balances[0] < balances[1]) { return (renbtc, 0); } // WBTC if (balances[1] < balances[0]) { return (wbtc, 1); } // If they're somehow equal, we just want RENBTC return (renbtc, 0); } function getName() external override pure returns (string memory) { return "StrategyCurveRenCRVv2"; } // **** State Mutations **** function harvest() public override onlyBenevolent { // Anyone can harvest it at any given time. // I understand the possibility of being frontrun // But ETH is a dark forest, and I wanna see how this plays out // i.e. will be be heavily frontrunned? // if so, a new strategy will be deployed. // stablecoin we want to convert to (address to, uint256 toIndex) = getMostPremium(); // Collects crv tokens // Don't bother voting in v1 ICurveMintr(mintr).mint(gauge); uint256 _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { // x% is sent back to the rewards holder // to be used to lock up in as veCRV in a future date uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax); if (_keepCRV > 0) { IERC20(crv).safeTransfer( IController(controller).treasury(), _keepCRV ); } _crv = _crv.sub(_keepCRV); _swapUniswap(crv, to, _crv); } // Adds liquidity to curve.fi's pool // to get back want (scrv) uint256 _to = IERC20(to).balanceOf(address(this)); if (_to > 0) { IERC20(to).safeApprove(curve, 0); IERC20(to).safeApprove(curve, _to); uint256[2] memory liquidity; liquidity[toIndex] = _to; ICurveFi_2(curve).add_liquidity(liquidity, 0); } _distributePerformanceFeesAndDeposit(); } } contract StrategyCurveSCRVv3_2 is StrategyCurveBase { // Curve stuff address public susdv2_pool = 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD; address public susdv2_gauge = 0xA90996896660DEcC6E997655E065b23788857849; address public scrv = 0xC25a3A3b969415c80451098fa907EC722572917F; // Harvesting address public snx = 0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F; constructor( address _governance, address _strategist, address _controller, address _timelock ) public StrategyCurveBase( susdv2_pool, susdv2_gauge, scrv, _governance, _strategist, _controller, _timelock ) {} // **** Views **** function getMostPremium() public override view returns (address, uint256) { uint256[] memory balances = new uint256[](4); balances[0] = ICurveFi_4(curve).balances(0); // DAI balances[1] = ICurveFi_4(curve).balances(1).mul(10**12); // USDC balances[2] = ICurveFi_4(curve).balances(2).mul(10**12); // USDT balances[3] = ICurveFi_4(curve).balances(3); // sUSD // DAI if ( balances[0] < balances[1] && balances[0] < balances[2] && balances[0] < balances[3] ) { return (dai, 0); } // USDC if ( balances[1] < balances[0] && balances[1] < balances[2] && balances[1] < balances[3] ) { return (usdc, 1); } // USDT if ( balances[2] < balances[0] && balances[2] < balances[1] && balances[2] < balances[3] ) { return (usdt, 2); } // SUSD if ( balances[3] < balances[0] && balances[3] < balances[1] && balances[3] < balances[2] ) { return (susd, 3); } // If they're somehow equal, we just want DAI return (dai, 0); } function getName() external override pure returns (string memory) { return "StrategyCurveSCRVv3_2"; } // **** State Mutations **** function harvest() public onlyBenevolent override { // Anyone can harvest it at any given time. // I understand the possibility of being frontrun // But ETH is a dark forest, and I wanna see how this plays out // i.e. will be be heavily frontrunned? // if so, a new strategy will be deployed. // stablecoin we want to convert to (address to, uint256 toIndex) = getMostPremium(); // Collects crv tokens // Don't bother voting in v1 ICurveMintr(mintr).mint(gauge); uint256 _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { // x% is sent back to the rewards holder // to be used to lock up in as veCRV in a future date uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax); if (_keepCRV > 0) { IERC20(crv).safeTransfer( IController(controller).treasury(), _keepCRV ); } _crv = _crv.sub(_keepCRV); _swapUniswap(crv, to, _crv); } // Collects SNX tokens ICurveGauge(gauge).claim_rewards(address(this)); uint256 _snx = IERC20(snx).balanceOf(address(this)); if (_snx > 0) { _swapUniswap(snx, to, _snx); } // Adds liquidity to curve.fi's susd pool // to get back want (scrv) uint256 _to = IERC20(to).balanceOf(address(this)); if (_to > 0) { IERC20(to).safeApprove(curve, 0); IERC20(to).safeApprove(curve, _to); uint256[4] memory liquidity; liquidity[toIndex] = _to; ICurveFi_4(curve).add_liquidity(liquidity, 0); } // We want to get back sCRV _distributePerformanceFeesAndDeposit(); } } contract StrategyCurveSCRVv4_1 is StrategyBase { // Curve address public scrv = 0xC25a3A3b969415c80451098fa907EC722572917F; address public susdv2_gauge = 0xA90996896660DEcC6E997655E065b23788857849; address public susdv2_pool = 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD; address public escrow = 0x5f3b5DfEb7B28CDbD7FAba78963EE202a494e2A2; // curve dao address public gauge; address public curve; address public mintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0; // tokens we're farming address public constant crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant snx = 0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F; // stablecoins address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address public susd = 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51; // How much CRV tokens to keep uint256 public keepCRV = 500; uint256 public keepCRVMax = 10000; // crv-locker and voter address public scrvVoter; address public crvLocker; constructor( address _scrvVoter, address _crvLocker, address _governance, address _strategist, address _controller, address _timelock ) public StrategyBase(scrv, _governance, _strategist, _controller, _timelock) { curve = susdv2_pool; gauge = susdv2_gauge; scrvVoter = _scrvVoter; crvLocker = _crvLocker; } // **** Getters **** function balanceOfPool() public override view returns (uint256) { return SCRVVoter(scrvVoter).balanceOf(gauge); } function getName() external override pure returns (string memory) { return "StrategyCurveSCRVv4_1"; } function getHarvestable() external returns (uint256) { return ICurveGauge(gauge).claimable_tokens(crvLocker); } function getMostPremium() public view returns (address, uint8) { uint256[] memory balances = new uint256[](4); balances[0] = ICurveFi_4(curve).balances(0); // DAI balances[1] = ICurveFi_4(curve).balances(1).mul(10**12); // USDC balances[2] = ICurveFi_4(curve).balances(2).mul(10**12); // USDT balances[3] = ICurveFi_4(curve).balances(3); // sUSD // DAI if ( balances[0] < balances[1] && balances[0] < balances[2] && balances[0] < balances[3] ) { return (dai, 0); } // USDC if ( balances[1] < balances[0] && balances[1] < balances[2] && balances[1] < balances[3] ) { return (usdc, 1); } // USDT if ( balances[2] < balances[0] && balances[2] < balances[1] && balances[2] < balances[3] ) { return (usdt, 2); } // SUSD if ( balances[3] < balances[0] && balances[3] < balances[1] && balances[3] < balances[2] ) { return (susd, 3); } // If they're somehow equal, we just want DAI return (dai, 0); } // **** Setters **** function setKeepCRV(uint256 _keepCRV) external { require(msg.sender == governance, "!governance"); keepCRV = _keepCRV; } // **** State Mutations **** function deposit() public override { uint256 _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeTransfer(scrvVoter, _want); SCRVVoter(scrvVoter).deposit(gauge, want); } } function _withdrawSome(uint256 _amount) internal override returns (uint256) { return SCRVVoter(scrvVoter).withdraw(gauge, want, _amount); } function harvest() public override onlyBenevolent { // Anyone can harvest it at any given time. // I understand the possibility of being frontrun / sandwiched // But ETH is a dark forest, and I wanna see how this plays out // i.e. will be be heavily frontrunned/sandwiched? // if so, a new strategy will be deployed. // stablecoin we want to convert to (address to, uint256 toIndex) = getMostPremium(); // Collects crv tokens // Don't bother voting in v1 SCRVVoter(scrvVoter).harvest(gauge); uint256 _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { // How much CRV to keep to restake? uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax); IERC20(crv).safeTransfer(address(crvLocker), _keepCRV); // How much CRV to swap? _crv = _crv.sub(_keepCRV); _swapUniswap(crv, to, _crv); } // Collects SNX tokens SCRVVoter(scrvVoter).claimRewards(); uint256 _snx = IERC20(snx).balanceOf(address(this)); if (_snx > 0) { _swapUniswap(snx, to, _snx); } // Adds liquidity to curve.fi's susd pool // to get back want (scrv) uint256 _to = IERC20(to).balanceOf(address(this)); if (_to > 0) { IERC20(to).safeApprove(curve, 0); IERC20(to).safeApprove(curve, _to); uint256[4] memory liquidity; liquidity[toIndex] = _to; ICurveFi_4(curve).add_liquidity(liquidity, 0); } // We want to get back sCRV _distributePerformanceFeesAndDeposit(); } } contract DSTestApprox is DSTest { function assertEqApprox(uint256 a, uint256 b) internal { if (a == 0 && b == 0) { return; } // +/- 5% uint256 bMax = (b * 105) / 100; uint256 bMin = (b * 95) / 100; if (!(a > bMin && a < bMax)) { emit log_bytes32("Error: Wrong `a-uint` value!"); emit log_named_uint(" Expected", b); emit log_named_uint(" Actual", a); fail(); } } function assertEqVerbose(bool a, bytes memory b) internal { if (!a) { emit log_bytes32("Error: assertion error!"); emit logs(b); fail(); } } } contract DSTestDefiBase is DSTestApprox { using SafeERC20 for IERC20; using SafeMath for uint256; address pickle = 0x429881672B9AE42b8EbA0E26cD9C73711b891Ca5; address burn = 0x000000000000000000000000000000000000dEaD; address susdv2_deposit = 0xFCBa3E75865d2d561BE8D220616520c171F12851; address susdv2_pool = 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD; address three_pool = 0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7; address ren_pool = 0x93054188d876f558f4a66B2EF1d97d16eDf0895B; address scrv = 0xC25a3A3b969415c80451098fa907EC722572917F; address three_crv = 0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490; address ren_crv = 0x49849C98ae39Fff122806C06791Fa73784FB3675; address eth = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; address weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; address crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; address snx = 0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F; address dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address susd = 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51; address uni = 0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984; address wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; address renbtc = 0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D; Hevm hevm = Hevm(0x7109709ECfa91a80626fF3989D68f67F5b1DD12D); UniswapRouterV2 univ2 = UniswapRouterV2( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); IUniswapV2Factory univ2Factory = IUniswapV2Factory( 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f ); ICurveFi_4 curveSusdV2 = ICurveFi_4( 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD ); uint256 startTime = block.timestamp; receive() external payable {} fallback () external payable {} function _swap( address _from, address _to, uint256 _amount ) internal { address[] memory path; if (_from == eth || _from == weth) { path = new address[](2); path[0] = weth; path[1] = _to; univ2.swapExactETHForTokens{value: _amount}( 0, path, address(this), now + 60 ); } else { path = new address[](3); path[0] = _from; path[1] = weth; path[2] = _to; IERC20(_from).safeApprove(address(univ2), 0); IERC20(_from).safeApprove(address(univ2), _amount); univ2.swapExactTokensForTokens( _amount, 0, path, address(this), now + 60 ); } } function _getERC20(address token, uint256 _amount) internal { address[] memory path = new address[](2); path[0] = weth; path[1] = token; uint256[] memory ins = univ2.getAmountsIn(_amount, path); uint256 ethAmount = ins[0]; univ2.swapETHForExactTokens{value: ethAmount}( _amount, path, address(this), now + 60 ); } function _getERC20WithETH(address token, uint256 _ethAmount) internal { address[] memory path = new address[](2); path[0] = weth; path[1] = token; univ2.swapExactETHForTokens{value: _ethAmount}( 0, path, address(this), now + 60 ); } function _getUniV2LPToken(address lpToken, uint256 _ethAmount) internal { address token0 = IUniswapV2Pair(lpToken).token0(); address token1 = IUniswapV2Pair(lpToken).token1(); if (token0 != weth) { _getERC20WithETH(token0, _ethAmount.div(2)); } else { WETH(weth).deposit{value: _ethAmount.div(2)}(); } if (token1 != weth) { _getERC20WithETH(token1, _ethAmount.div(2)); } else { WETH(weth).deposit{value: _ethAmount.div(2)}(); } IERC20(token0).safeApprove(address(univ2), uint256(0)); IERC20(token0).safeApprove(address(univ2), uint256(-1)); IERC20(token1).safeApprove(address(univ2), uint256(0)); IERC20(token1).safeApprove(address(univ2), uint256(-1)); univ2.addLiquidity( token0, token1, IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), 0, 0, address(this), now + 60 ); } function _getUniV2LPToken( address token0, address token1, uint256 _ethAmount ) internal { _getUniV2LPToken(univ2Factory.getPair(token0, token1), _ethAmount); } function _getFunctionSig(string memory sig) internal pure returns (bytes4) { return bytes4(keccak256(bytes(sig))); } function _getDynamicArray(address payable one) internal pure returns (address payable[] memory) { address payable[] memory targets = new address payable[](1); targets[0] = one; return targets; } function _getDynamicArray(bytes memory one) internal pure returns (bytes[] memory) { bytes[] memory data = new bytes[](1); data[0] = one; return data; } function _getDynamicArray(address payable one, address payable two) internal pure returns (address payable[] memory) { address payable[] memory targets = new address payable[](2); targets[0] = one; targets[1] = two; return targets; } function _getDynamicArray(bytes memory one, bytes memory two) internal pure returns (bytes[] memory) { bytes[] memory data = new bytes[](2); data[0] = one; data[1] = two; return data; } function _getDynamicArray( address payable one, address payable two, address payable three ) internal pure returns (address payable[] memory) { address payable[] memory targets = new address payable[](3); targets[0] = one; targets[1] = two; targets[2] = three; return targets; } function _getDynamicArray( bytes memory one, bytes memory two, bytes memory three ) internal pure returns (bytes[] memory) { bytes[] memory data = new bytes[](3); data[0] = one; data[1] = two; data[2] = three; return data; } } contract StrategyCurveFarmTestBase is DSTestDefiBase { address governance; address strategist; address timelock; address devfund; address treasury; address want; PickleJar pickleJar; ControllerV4 controller; IStrategy strategy; // **** Tests **** function _test_withdraw() internal { uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); // Deposits to strategy pickleJar.earn(); // Fast forwards hevm.warp(block.timestamp + 1 weeks); strategy.harvest(); // Withdraws back to pickleJar uint256 _before = IERC20(want).balanceOf(address(pickleJar)); controller.withdrawAll(want); uint256 _after = IERC20(want).balanceOf(address(pickleJar)); assertTrue(_after > _before); _before = IERC20(want).balanceOf(address(this)); pickleJar.withdrawAll(); _after = IERC20(want).balanceOf(address(this)); assertTrue(_after > _before); // Gained some interest assertTrue(_after > _want); } function _test_get_earn_harvest_rewards() internal { uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); // Fast forward one week hevm.warp(block.timestamp + 1 weeks); // Call the harvest function uint256 _before = pickleJar.balance(); uint256 _treasuryBefore = IERC20(want).balanceOf(treasury); strategy.harvest(); uint256 _after = pickleJar.balance(); uint256 _treasuryAfter = IERC20(want).balanceOf(treasury); uint256 earned = _after.sub(_before).mul(1000).div(955); uint256 earnedRewards = earned.mul(45).div(1000); // 4.5% uint256 actualRewardsEarned = _treasuryAfter.sub(_treasuryBefore); // 4.5% performance fee is given assertEqApprox(earnedRewards, actualRewardsEarned); // Withdraw uint256 _devBefore = IERC20(want).balanceOf(devfund); _treasuryBefore = IERC20(want).balanceOf(treasury); uint256 _stratBal = strategy.balanceOf(); pickleJar.withdrawAll(); uint256 _devAfter = IERC20(want).balanceOf(devfund); _treasuryAfter = IERC20(want).balanceOf(treasury); // 0.175% goes to dev uint256 _devFund = _devAfter.sub(_devBefore); assertEq(_devFund, _stratBal.mul(175).div(100000)); // 0.325% goes to treasury uint256 _treasuryFund = _treasuryAfter.sub(_treasuryBefore); assertEq(_treasuryFund, _stratBal.mul(325).div(100000)); } } contract StrategyUniFarmTestBase is DSTestDefiBase { address want; address token1; address governance; address strategist; address timelock; address devfund; address treasury; PickleJar pickleJar; ControllerV4 controller; IStrategy strategy; function _getWant(uint256 ethAmount, uint256 amount) internal { _getERC20(token1, amount); uint256 _token1 = IERC20(token1).balanceOf(address(this)); IERC20(token1).safeApprove(address(univ2), 0); IERC20(token1).safeApprove(address(univ2), _token1); univ2.addLiquidityETH{value: ethAmount}( token1, _token1, 0, 0, address(this), now + 60 ); } // **** Tests **** function _test_timelock() internal { assertTrue(strategy.timelock() == timelock); strategy.setTimelock(address(1)); assertTrue(strategy.timelock() == address(1)); } function _test_withdraw_release() internal { uint256 decimals = ERC20(token1).decimals(); _getWant(10 ether, 4000 * (10**decimals)); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).safeApprove(address(pickleJar), 0); IERC20(want).safeApprove(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); hevm.warp(block.timestamp + 1 weeks); strategy.harvest(); // Checking withdraw uint256 _before = IERC20(want).balanceOf(address(pickleJar)); controller.withdrawAll(want); uint256 _after = IERC20(want).balanceOf(address(pickleJar)); assertTrue(_after > _before); _before = IERC20(want).balanceOf(address(this)); pickleJar.withdrawAll(); _after = IERC20(want).balanceOf(address(this)); assertTrue(_after > _before); // Check if we gained interest assertTrue(_after > _want); } function _test_get_earn_harvest_rewards() internal { uint256 decimals = ERC20(token1).decimals(); _getWant(10 ether, 4000 * (10**decimals)); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).safeApprove(address(pickleJar), 0); IERC20(want).safeApprove(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); hevm.warp(block.timestamp + 1 weeks); // Call the harvest function uint256 _before = pickleJar.balance(); uint256 _treasuryBefore = IERC20(want).balanceOf(treasury); strategy.harvest(); uint256 _after = pickleJar.balance(); uint256 _treasuryAfter = IERC20(want).balanceOf(treasury); uint256 earned = _after.sub(_before).mul(1000).div(955); uint256 earnedRewards = earned.mul(45).div(1000); // 4.5% uint256 actualRewardsEarned = _treasuryAfter.sub(_treasuryBefore); // 4.5% performance fee is given assertEqApprox(earnedRewards, actualRewardsEarned); // Withdraw uint256 _devBefore = IERC20(want).balanceOf(devfund); _treasuryBefore = IERC20(want).balanceOf(treasury); uint256 _stratBal = strategy.balanceOf(); pickleJar.withdrawAll(); uint256 _devAfter = IERC20(want).balanceOf(devfund); _treasuryAfter = IERC20(want).balanceOf(treasury); // 0.175% goes to dev uint256 _devFund = _devAfter.sub(_devBefore); assertEq(_devFund, _stratBal.mul(175).div(100000)); // 0.325% goes to treasury uint256 _treasuryFund = _treasuryAfter.sub(_treasuryBefore); assertEq(_treasuryFund, _stratBal.mul(325).div(100000)); } } contract PickleSwapTest is DSTestDefiBase { PickleSwap pickleSwap; function setUp() public { pickleSwap = new PickleSwap(); } function _test_uni_lp_swap(address lp1, address lp2) internal { _getUniV2LPToken(lp1, 20 ether); uint256 _balance = IERC20(lp1).balanceOf(address(this)); uint256 _before = IERC20(lp2).balanceOf(address(this)); IERC20(lp1).safeIncreaseAllowance(address(pickleSwap), _balance); pickleSwap.convertWETHPair(lp1, lp2, _balance); uint256 _after = IERC20(lp2).balanceOf(address(this)); assertTrue(_after > _before); assertTrue(_after > 0); } function test_pickleswap_dai_usdc() public { _test_uni_lp_swap( univ2Factory.getPair(weth, dai), univ2Factory.getPair(weth, usdc) ); } function test_pickleswap_dai_usdt() public { _test_uni_lp_swap( univ2Factory.getPair(weth, dai), univ2Factory.getPair(weth, usdt) ); } function test_pickleswap_usdt_susd() public { _test_uni_lp_swap( univ2Factory.getPair(weth, usdt), univ2Factory.getPair(weth, susd) ); } } contract StrategyCmpndDaiV1 is DSTestDefiBase { StrategyCmpdDaiV2 strategy; ControllerV4 controller; PickleJar pickleJar; address governance; address strategist; address timelock; address devfund; address treasury; address want; function setUp() public { want = dai; governance = address(this); strategist = address(new User()); timelock = address(this); devfund = address(new User()); treasury = address(new User()); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = new StrategyCmpdDaiV2( governance, strategist, address(controller), timelock ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); } function testFail_cmpnd_dai_v1_onlyKeeper_leverage() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); User randomUser = new User(); randomUser.execute(address(strategy), 0, "leverageToMax()", ""); } function testFail_cmpnd_dai_v1_onlyKeeper_deleverage() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); strategy.leverageToMax(); User randomUser = new User(); randomUser.execute(address(strategy), 0, "deleverageToMin()", ""); } function test_cmpnd_dai_v1_comp_accrued() public { _getERC20(want, 1000000e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); strategy.leverageToMax(); uint256 compAccrued = strategy.getCompAccrued(); assertEq(compAccrued, 0); hevm.warp(block.timestamp + 1 days); hevm.roll(block.number + 6171); // Roughly number of blocks per day compAccrued = strategy.getCompAccrued(); assertTrue(compAccrued > 0); } function test_cmpnd_dai_v1_comp_sync() public { _getERC20(want, 1000000e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); // Sets colFactor Buffer to be 3% (safeSync is 5%) strategy.setColFactorLeverageBuffer(30); strategy.leverageToMax(); // Back to 10% strategy.setColFactorLeverageBuffer(100); uint256 colFactor = strategy.getColFactor(); uint256 safeColFactor = strategy.getSafeLeverageColFactor(); assertTrue(colFactor > safeColFactor); // Sync automatically fixes the colFactor for us bool shouldSync = strategy.sync(); assertTrue(shouldSync); colFactor = strategy.getColFactor(); assertEqApprox(colFactor, safeColFactor); shouldSync = strategy.sync(); assertTrue(!shouldSync); } function test_cmpnd_dai_v1_leverage() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); uint256 _stratInitialBal = strategy.balanceOf(); uint256 _beforeCR = strategy.getColFactor(); uint256 _beforeLev = strategy.getCurrentLeverage(); strategy.leverageToMax(); uint256 _afterCR = strategy.getColFactor(); uint256 _afterLev = strategy.getCurrentLeverage(); uint256 _safeLeverageColFactor = strategy.getSafeLeverageColFactor(); assertTrue(_afterCR > _beforeCR); assertTrue(_afterLev > _beforeLev); assertEqApprox(_safeLeverageColFactor, _afterCR); uint256 _maxLeverage = strategy.getMaxLeverage(); assertTrue(_maxLeverage > 2e18); // Should be ~2.6, depending on colFactorLeverageBuffer uint256 leverageTarget = strategy.getLeveragedSupplyTarget( _stratInitialBal ); uint256 leverageSupplied = strategy.getSupplied(); assertEqApprox( leverageSupplied, _stratInitialBal.mul(_maxLeverage).div(1e18) ); assertEqApprox(leverageSupplied, leverageTarget); uint256 unleveragedSupplied = strategy.getSuppliedUnleveraged(); assertEqApprox(unleveragedSupplied, _stratInitialBal); } function test_cmpnd_dai_v1_deleverage() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); strategy.leverageToMax(); uint256 _beforeCR = strategy.getColFactor(); uint256 _beforeLev = strategy.getCurrentLeverage(); strategy.deleverageToMin(); uint256 _afterCR = strategy.getColFactor(); uint256 _afterLev = strategy.getCurrentLeverage(); assertTrue(_afterCR < _beforeCR); assertTrue(_afterLev < _beforeLev); assertEq(0, _afterCR); // 0 since we're not borrowing anything uint256 unleveragedSupplied = strategy.getSuppliedUnleveraged(); uint256 supplied = strategy.getSupplied(); assertEqApprox(unleveragedSupplied, supplied); } function test_cmpnd_dai_v1_withdrawSome() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); strategy.leverageToMax(); uint256 _before = IERC20(want).balanceOf(address(this)); pickleJar.withdraw(25e18); uint256 _after = IERC20(want).balanceOf(address(this)); assertTrue(_after > _before); assertEqApprox(_after.sub(_before), 25e18); _before = IERC20(want).balanceOf(address(this)); pickleJar.withdraw(10e18); _after = IERC20(want).balanceOf(address(this)); assertTrue(_after > _before); assertEqApprox(_after.sub(_before), 10e18); _before = IERC20(want).balanceOf(address(this)); pickleJar.withdraw(30e18); _after = IERC20(want).balanceOf(address(this)); assertTrue(_after > _before); assertEqApprox(_after.sub(_before), 30e18); // Make sure we're still leveraging uint256 _leverage = strategy.getCurrentLeverage(); assertTrue(_leverage > 1e18); } function test_cmpnd_dai_v1_withdrawAll() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); strategy.leverageToMax(); hevm.warp(block.timestamp + 1 days); hevm.roll(block.number + 6171); // Roughly number of blocks per day strategy.harvest(); // Withdraws back to pickleJar uint256 _before = IERC20(want).balanceOf(address(pickleJar)); controller.withdrawAll(want); uint256 _after = IERC20(want).balanceOf(address(pickleJar)); assertTrue(_after > _before); _before = IERC20(want).balanceOf(address(this)); pickleJar.withdrawAll(); _after = IERC20(want).balanceOf(address(this)); assertTrue(_after > _before); // Gained some interest assertTrue(_after > _want); } function test_cmpnd_dai_v1_earn_harvest_rewards() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); // Fast forward one week hevm.warp(block.timestamp + 1 days); hevm.roll(block.number + 6171); // Roughly number of blocks per day // Call the harvest function uint256 _before = strategy.getSupplied(); uint256 _treasuryBefore = IERC20(want).balanceOf(treasury); strategy.harvest(); uint256 _after = strategy.getSupplied(); uint256 _treasuryAfter = IERC20(want).balanceOf(treasury); uint256 earned = _after.sub(_before).mul(1000).div(955); uint256 earnedRewards = earned.mul(45).div(1000); // 4.5% uint256 actualRewardsEarned = _treasuryAfter.sub(_treasuryBefore); // 4.5% performance fee is given assertEqApprox(earnedRewards, actualRewardsEarned); // Withdraw uint256 _devBefore = IERC20(want).balanceOf(devfund); _treasuryBefore = IERC20(want).balanceOf(treasury); uint256 _stratBal = strategy.balanceOf(); pickleJar.withdrawAll(); uint256 _devAfter = IERC20(want).balanceOf(devfund); _treasuryAfter = IERC20(want).balanceOf(treasury); // 0.175% goes to dev uint256 _devFund = _devAfter.sub(_devBefore); assertEq(_devFund, _stratBal.mul(175).div(100000)); // 0.325% goes to treasury uint256 _treasuryFund = _treasuryAfter.sub(_treasuryBefore); assertEq(_treasuryFund, _stratBal.mul(325).div(100000)); } function test_cmpnd_dai_v1_functions() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); uint256 initialSupplied = strategy.getSupplied(); uint256 initialBorrowed = strategy.getBorrowed(); uint256 initialBorrowable = strategy.getBorrowable(); uint256 marketColFactor = strategy.getMarketColFactor(); uint256 maxLeverage = strategy.getMaxLeverage(); // Earn deposits 95% into strategy assertEqApprox(initialSupplied, 95e18); assertEqApprox( initialBorrowable, initialSupplied.mul(marketColFactor).div(1e18) ); assertEqApprox(initialBorrowed, 0); // Leverage to Max strategy.leverageToMax(); uint256 supplied = strategy.getSupplied(); uint256 borrowed = strategy.getBorrowed(); uint256 borrowable = strategy.getBorrowable(); uint256 currentColFactor = strategy.getColFactor(); uint256 safeLeverageColFactor = strategy.getSafeLeverageColFactor(); assertEqApprox(supplied, initialSupplied.mul(maxLeverage).div(1e18)); assertEqApprox(borrowed, supplied.mul(safeLeverageColFactor).div(1e18)); assertEqApprox( borrowable, supplied.mul(marketColFactor.sub(currentColFactor)).div(1e18) ); assertEqApprox(currentColFactor, safeLeverageColFactor); assertTrue(marketColFactor > currentColFactor); assertTrue(marketColFactor > safeLeverageColFactor); // Deleverage strategy.deleverageToMin(); uint256 deleverageSupplied = strategy.getSupplied(); uint256 deleverageBorrowed = strategy.getBorrowed(); uint256 deleverageBorrowable = strategy.getBorrowable(); assertEqApprox(deleverageSupplied, initialSupplied); assertEqApprox(deleverageBorrowed, initialBorrowed); assertEqApprox(deleverageBorrowable, initialBorrowable); } function test_cmpnd_dai_v1_deleverage_stepping() public { _getERC20(want, 100e18); uint256 _want = IERC20(want).balanceOf(address(this)); IERC20(want).approve(address(pickleJar), _want); pickleJar.deposit(_want); pickleJar.earn(); strategy.leverageToMax(); strategy.deleverageUntil(200e18); uint256 supplied = strategy.getSupplied(); assertEqApprox(supplied, 200e18); strategy.deleverageUntil(180e18); supplied = strategy.getSupplied(); assertEqApprox(supplied, 180e18); strategy.deleverageUntil(120e18); supplied = strategy.getSupplied(); assertEqApprox(supplied, 120e18); } } contract StrategyCurve3CRVv2Test is StrategyCurveFarmTestBase { function setUp() public { governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); want = three_crv; controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = IStrategy( address( new StrategyCurve3CRVv2( governance, strategist, address(controller), timelock ) ) ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); hevm.warp(startTime); _getWant(10000000 ether); } function _getWant(uint256 daiAmount) internal { _getERC20(dai, daiAmount); uint256[3] memory liquidity; liquidity[0] = IERC20(dai).balanceOf(address(this)); IERC20(dai).approve(three_pool, liquidity[0]); ICurveFi_3(three_pool).add_liquidity(liquidity, 0); } // **** Tests **** // function test_3crv_v1_withdraw() public { _test_withdraw(); } function test_3crv_v1_earn_harvest_rewards() public { _test_get_earn_harvest_rewards(); } } contract StrategyCurveRenCRVv2Test is StrategyCurveFarmTestBase { function setUp() public { governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); want = ren_crv; controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = IStrategy( address( new StrategyCurveRenCRVv2( governance, strategist, address(controller), timelock ) ) ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); hevm.warp(startTime); _getWant(10e8); // 10 wbtc } function _getWant(uint256 btcAmount) internal { _getERC20(wbtc, btcAmount); uint256[2] memory liquidity; liquidity[1] = IERC20(wbtc).balanceOf(address(this)); IERC20(wbtc).approve(ren_pool, liquidity[1]); ICurveFi_2(ren_pool).add_liquidity(liquidity, 0); } // **** Tests **** // function test_rencrv_v1_withdraw() public { _test_withdraw(); } function test_rencrv_v1_earn_harvest_rewards() public { _test_get_earn_harvest_rewards(); } } contract StrategyCurveSCRVv3_2Test is StrategyCurveFarmTestBase { function setUp() public { governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); want = scrv; controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = IStrategy( address( new StrategyCurveSCRVv3_2( governance, strategist, address(controller), timelock ) ) ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); hevm.warp(startTime); _getWant(10000000 ether); } function _getWant(uint256 daiAmount) internal { _getERC20(dai, daiAmount); uint256[4] memory liquidity; liquidity[0] = IERC20(dai).balanceOf(address(this)); IERC20(dai).approve(susdv2_pool, liquidity[0]); ICurveFi_4(susdv2_pool).add_liquidity(liquidity, 0); } // **** Tests **** // function test_scrv_v3_1_withdraw() public { _test_withdraw(); } function test_scrv_v3_1_earn_harvest_rewards() public { _test_get_earn_harvest_rewards(); } } contract StrategyCurveSCRVv4Test is DSTestDefiBase { address escrow = 0x5f3b5DfEb7B28CDbD7FAba78963EE202a494e2A2; address curveSmartContractChecker = 0xca719728Ef172d0961768581fdF35CB116e0B7a4; address governance; address strategist; address timelock; address devfund; address treasury; PickleJar pickleJar; ControllerV4 controller; StrategyCurveSCRVv4_1 strategy; SCRVVoter scrvVoter; CRVLocker crvLocker; function setUp() public { governance = address(this); strategist = address(new User()); timelock = address(this); devfund = address(new User()); treasury = address(new User()); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); crvLocker = new CRVLocker(governance); scrvVoter = new SCRVVoter(governance, address(crvLocker)); strategy = new StrategyCurveSCRVv4_1( address(scrvVoter), address(crvLocker), governance, strategist, address(controller), timelock ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); scrvVoter.approveStrategy(address(strategy)); scrvVoter.approveStrategy(governance); crvLocker.addVoter(address(scrvVoter)); hevm.warp(startTime); // Approve our strategy on smartContractWhitelist // Modify storage value so we are approved by the smart-wallet-white-list // storage in solidity - https://ethereum.stackexchange.com/a/41304 bytes32 key = bytes32(uint256(address(crvLocker))); bytes32 pos = bytes32(0); // pos 0 as its the first state variable bytes32 loc = keccak256(abi.encodePacked(key, pos)); hevm.store(curveSmartContractChecker, loc, bytes32(uint256(1))); // Make sure our crvLocker is whitelisted assertTrue( ICurveSmartContractChecker(curveSmartContractChecker).wallets( address(crvLocker) ) ); } function _getSCRV(uint256 daiAmount) internal { _getERC20(dai, daiAmount); uint256[4] memory liquidity; liquidity[0] = IERC20(dai).balanceOf(address(this)); IERC20(dai).approve(susdv2_pool, liquidity[0]); ICurveFi_4(susdv2_pool).add_liquidity(liquidity, 0); } // **** Tests **** function test_scrv_v4_1_withdraw() public { _getSCRV(10000000 ether); // 1 million DAI uint256 _scrv = IERC20(scrv).balanceOf(address(this)); IERC20(scrv).approve(address(pickleJar), _scrv); pickleJar.deposit(_scrv); // Deposits to strategy pickleJar.earn(); // Fast forwards hevm.warp(block.timestamp + 1 weeks); strategy.harvest(); // Withdraws back to pickleJar uint256 _before = IERC20(scrv).balanceOf(address(pickleJar)); controller.withdrawAll(scrv); uint256 _after = IERC20(scrv).balanceOf(address(pickleJar)); assertTrue(_after > _before); _before = IERC20(scrv).balanceOf(address(this)); pickleJar.withdrawAll(); _after = IERC20(scrv).balanceOf(address(this)); assertTrue(_after > _before); // Gained some interest assertTrue(_after > _scrv); } function test_scrv_v4_1_get_earn_harvest_rewards() public { address dev = controller.devfund(); // Deposit sCRV, and earn _getSCRV(10000000 ether); // 1 million DAI uint256 _scrv = IERC20(scrv).balanceOf(address(this)); IERC20(scrv).approve(address(pickleJar), _scrv); pickleJar.deposit(_scrv); pickleJar.earn(); // Fast forward one week hevm.warp(block.timestamp + 1 weeks); // Call the harvest function uint256 _before = pickleJar.balance(); uint256 _rewardsBefore = IERC20(scrv).balanceOf(treasury); User(strategist).execute(address(strategy), 0, "harvest()", ""); uint256 _after = pickleJar.balance(); uint256 _rewardsAfter = IERC20(scrv).balanceOf(treasury); uint256 earned = _after.sub(_before).mul(1000).div(955); uint256 earnedRewards = earned.mul(45).div(1000); // 4.5% uint256 actualRewardsEarned = _rewardsAfter.sub(_rewardsBefore); // 4.5% performance fee is given assertEqApprox(earnedRewards, actualRewardsEarned); // Withdraw uint256 _devBefore = IERC20(scrv).balanceOf(dev); uint256 _stratBal = strategy.balanceOf(); pickleJar.withdrawAll(); uint256 _devAfter = IERC20(scrv).balanceOf(dev); // 0.175% goes to dev uint256 _devFund = _devAfter.sub(_devBefore); assertEq(_devFund, _stratBal.mul(175).div(100000)); } function test_scrv_v4_1_lock() public { // Deposit sCRV, and earn _getSCRV(10000000 ether); // 1 million DAI uint256 _scrv = IERC20(scrv).balanceOf(address(this)); IERC20(scrv).approve(address(pickleJar), _scrv); pickleJar.deposit(_scrv); pickleJar.earn(); // Fast forward one week hevm.warp(block.timestamp + 1 weeks); uint256 _before = IERC20(crv).balanceOf(address(crvLocker)); // Call the harvest function strategy.harvest(); // Make sure we can open lock uint256 _after = IERC20(crv).balanceOf(address(crvLocker)); assertTrue(_after > _before); // Create a lock crvLocker.createLock(_after, block.timestamp + 5 weeks); // Harvest etc hevm.warp(block.timestamp + 1 weeks); strategy.harvest(); // Increase amount crvLocker.increaseAmount(IERC20(crv).balanceOf(address(crvLocker))); // Increase unlockTime crvLocker.increaseUnlockTime(block.timestamp + 5 weeks); // Fast forward hevm.warp(block.timestamp + 5 weeks + 1 hours); // Withdraw _before = IERC20(crv).balanceOf(address(crvLocker)); crvLocker.release(); _after = IERC20(crv).balanceOf(address(crvLocker)); assertTrue(_after > _before); } } contract StrategyUniEthDaiLpV4Test is StrategyUniFarmTestBase { function setUp() public { want = 0xA478c2975Ab1Ea89e8196811F51A7B7Ade33eB11; token1 = dai; governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = IStrategy( address( new StrategyUniEthDaiLpV4( governance, strategist, address(controller), timelock ) ) ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); // Set time hevm.warp(startTime); } // **** Tests **** function test_ethdaiv3_1_timelock() public { _test_timelock(); } function test_ethdaiv3_1_withdraw_release() public { _test_withdraw_release(); } function test_ethdaiv3_1_get_earn_harvest_rewards() public { _test_get_earn_harvest_rewards(); } } contract StrategyUniEthUsdcLpV4Test is StrategyUniFarmTestBase { function setUp() public { want = 0xB4e16d0168e52d35CaCD2c6185b44281Ec28C9Dc; token1 = usdc; governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = IStrategy( address( new StrategyUniEthUsdcLpV4( governance, strategist, address(controller), timelock ) ) ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); // Set time hevm.warp(startTime); } // **** Tests **** function test_ethusdcv3_1_timelock() public { _test_timelock(); } function test_ethusdcv3_1_withdraw_release() public { _test_withdraw_release(); } function test_ethusdcv3_1_get_earn_harvest_rewards() public { _test_get_earn_harvest_rewards(); } } contract StrategyUniEthUsdtLpV4Test is StrategyUniFarmTestBase { function setUp() public { want = 0x0d4a11d5EEaaC28EC3F61d100daF4d40471f1852; token1 = usdt; governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = IStrategy( address( new StrategyUniEthUsdtLpV4( governance, strategist, address(controller), timelock ) ) ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); // Set time hevm.warp(startTime); } // **** Tests **** function test_ethusdtv3_1_timelock() public { _test_timelock(); } function test_ethusdtv3_1_withdraw_release() public { _test_withdraw_release(); } function test_ethusdtv3_1_get_earn_harvest_rewards() public { _test_get_earn_harvest_rewards(); } } contract StrategyUniEthWBtcLpV2Test is StrategyUniFarmTestBase { function setUp() public { want = 0xBb2b8038a1640196FbE3e38816F3e67Cba72D940; token1 = wbtc; governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); strategy = IStrategy( address( new StrategyUniEthWBtcLpV2( governance, strategist, address(controller), timelock ) ) ); pickleJar = new PickleJar( strategy.want(), governance, timelock, address(controller) ); controller.setJar(strategy.want(), address(pickleJar)); controller.approveStrategy(strategy.want(), address(strategy)); controller.setStrategy(strategy.want(), address(strategy)); // Set time hevm.warp(startTime); } // **** Tests **** function test_ethwbtcv1_timelock() public { _test_timelock(); } function test_ethwbtcv1_withdraw_release() public { _test_withdraw_release(); } function test_ethwbtcv1_get_earn_harvest_rewards() public { _test_get_earn_harvest_rewards(); } } contract UniCurveConverterTest is DSTestDefiBase { UniCurveConverter uniCurveConverter; function setUp() public { uniCurveConverter = new UniCurveConverter(); } function _test_uni_curve_converter(address token0, address token1) internal { address lp = univ2Factory.getPair(token0, token1); _getUniV2LPToken(lp, 100 ether); uint256 _balance = IERC20(lp).balanceOf(address(this)); IERC20(lp).safeApprove(address(uniCurveConverter), 0); IERC20(lp).safeApprove(address(uniCurveConverter), uint256(-1)); uint256 _before = IERC20(scrv).balanceOf(address(this)); uniCurveConverter.convert(lp, _balance); uint256 _after = IERC20(scrv).balanceOf(address(this)); // Gets scrv assertTrue(_after > _before); assertTrue(_after > 0); // No token left behind in router assertEq(IERC20(token0).balanceOf(address(uniCurveConverter)), 0); assertEq(IERC20(token1).balanceOf(address(uniCurveConverter)), 0); assertEq(IERC20(weth).balanceOf(address(uniCurveConverter)), 0); assertEq(IERC20(dai).balanceOf(address(uniCurveConverter)), 0); assertEq(IERC20(usdc).balanceOf(address(uniCurveConverter)), 0); assertEq(IERC20(usdt).balanceOf(address(uniCurveConverter)), 0); assertEq(IERC20(susd).balanceOf(address(uniCurveConverter)), 0); } function test_uni_curve_convert_dai_weth() public { _test_uni_curve_converter(dai, weth); } function test_uni_curve_convert_usdt_weth() public { _test_uni_curve_converter(usdt, weth); } function test_uni_curve_convert_wbtc_weth() public { _test_uni_curve_converter(wbtc, weth); } } contract StrategyCurveCurveJarSwapTest is DSTestDefiBase { address governance; address strategist; address devfund; address treasury; address timelock; IStrategy[] curveStrategies; PickleJar[] curvePickleJars; ControllerV4 controller; CurveProxyLogic curveProxyLogic; UniswapV2ProxyLogic uniswapV2ProxyLogic; address[] curvePools; address[] curveLps; function setUp() public { governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); // Curve Strategies curveStrategies = new IStrategy[](3); curvePickleJars = new PickleJar[](curveStrategies.length); curveLps = new address[](curveStrategies.length); curvePools = new address[](curveStrategies.length); curveLps[0] = three_crv; curvePools[0] = three_pool; curveStrategies[0] = IStrategy( address( new StrategyCurve3CRVv2( governance, strategist, address(controller), timelock ) ) ); curveLps[1] = scrv; curvePools[1] = susdv2_pool; curveStrategies[1] = IStrategy( address( new StrategyCurveSCRVv3_2( governance, strategist, address(controller), timelock ) ) ); curveLps[2] = ren_crv; curvePools[2] = ren_pool; curveStrategies[2] = IStrategy( address( new StrategyCurveRenCRVv2( governance, strategist, address(controller), timelock ) ) ); // Create PICKLE Jars for (uint256 i = 0; i < curvePickleJars.length; i++) { curvePickleJars[i] = new PickleJar( curveStrategies[i].want(), governance, timelock, address(controller) ); controller.setJar( curveStrategies[i].want(), address(curvePickleJars[i]) ); controller.approveStrategy( curveStrategies[i].want(), address(curveStrategies[i]) ); controller.setStrategy( curveStrategies[i].want(), address(curveStrategies[i]) ); } curveProxyLogic = new CurveProxyLogic(); uniswapV2ProxyLogic = new UniswapV2ProxyLogic(); controller.approveJarConverter(address(curveProxyLogic)); controller.approveJarConverter(address(uniswapV2ProxyLogic)); hevm.warp(startTime); } function _getCurveLP(address curve, uint256 amount) internal { if (curve == ren_pool) { _getERC20(wbtc, amount); uint256 _wbtc = IERC20(wbtc).balanceOf(address(this)); IERC20(wbtc).approve(curve, _wbtc); uint256[2] memory liquidity; liquidity[1] = _wbtc; ICurveFi_2(curve).add_liquidity(liquidity, 0); } else { _getERC20(dai, amount); uint256 _dai = IERC20(dai).balanceOf(address(this)); IERC20(dai).approve(curve, _dai); if (curve == three_pool) { uint256[3] memory liquidity; liquidity[0] = _dai; ICurveFi_3(curve).add_liquidity(liquidity, 0); } else { uint256[4] memory liquidity; liquidity[0] = _dai; ICurveFi_4(curve).add_liquidity(liquidity, 0); } } } // **** Internal functions **** // // Theres so many internal functions due to stack blowing up // Some post swap checks // Checks if there's any leftover funds in the converter contract function _post_swap_check(uint256 fromIndex, uint256 toIndex) internal { IERC20 token0 = curvePickleJars[fromIndex].token(); IERC20 token1 = curvePickleJars[toIndex].token(); uint256 MAX_DUST = 10; // No funds left behind assertEq(curvePickleJars[fromIndex].balanceOf(address(controller)), 0); assertEq(curvePickleJars[toIndex].balanceOf(address(controller)), 0); assertTrue(token0.balanceOf(address(controller)) < MAX_DUST); assertTrue(token1.balanceOf(address(controller)) < MAX_DUST); // Make sure only controller can call 'withdrawForSwap' try curveStrategies[fromIndex].withdrawForSwap(0) { revert("!withdraw-for-swap-only-controller"); } catch {} } function _test_check_treasury_fee(uint256 _amount, uint256 earned) internal { assertEqApprox( _amount.mul(controller.convenienceFee()).div( controller.convenienceFeeMax() ), earned.mul(2) ); } function _test_swap_and_check_balances( address fromPickleJar, address toPickleJar, address fromPickleJarUnderlying, uint256 fromPickleJarUnderlyingAmount, address payable[] memory targets, bytes[] memory data ) internal { uint256 _beforeTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _beforeFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _beforeDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _beforeTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 _ret = controller.swapExactJarForJar( fromPickleJar, toPickleJar, fromPickleJarUnderlyingAmount, 0, // Min receive amount targets, data ); uint256 _afterTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _afterFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _afterDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _afterTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 treasuryEarned = _afterTreasury.sub(_beforeTreasury); assertEq(treasuryEarned, _afterDev.sub(_beforeDev)); assertTrue(treasuryEarned > 0); _test_check_treasury_fee(fromPickleJarUnderlyingAmount, treasuryEarned); assertTrue(_afterFrom < _beforeFrom); assertTrue(_afterTo > _beforeTo); assertTrue(_afterTo.sub(_beforeTo) > 0); assertEq(_afterTo.sub(_beforeTo), _ret); assertEq(_afterFrom, 0); } function _get_uniswap_pl_swap_data(address from, address to) internal pure returns (bytes memory) { return abi.encodeWithSignature("swapUniswap(address,address)", from, to); } function _test_curve_curve( uint256 fromIndex, uint256 toIndex, uint256 amount, address payable[] memory targets, bytes[] memory data ) public { // Get LP _getCurveLP(curvePools[fromIndex], amount); // Deposit into pickle jars address from = address(curvePickleJars[fromIndex].token()); uint256 _from = IERC20(from).balanceOf(address(this)); IERC20(from).approve(address(curvePickleJars[fromIndex]), _from); curvePickleJars[fromIndex].deposit(_from); curvePickleJars[fromIndex].earn(); // Approve controller uint256 _fromPickleJar = IERC20(address(curvePickleJars[fromIndex])) .balanceOf(address(this)); IERC20(address(curvePickleJars[fromIndex])).approve( address(controller), _fromPickleJar ); // Swap try controller.swapExactJarForJar( address(curvePickleJars[fromIndex]), address(curvePickleJars[toIndex]), _fromPickleJar, uint256(-1), // Min receive amount targets, data ) { revert("min-receive-amount"); } catch {} _test_swap_and_check_balances( address(curvePickleJars[fromIndex]), address(curvePickleJars[toIndex]), from, _fromPickleJar, targets, data ); _post_swap_check(fromIndex, toIndex); } // **** Tests **** function test_jar_converter_curve_curve_0() public { uint256 fromIndex = 0; uint256 toIndex = 1; uint256 amount = 400e18; int128 fromCurveUnderlyingIndex = 0; bytes4 toCurveFunctionSig = _getFunctionSig( "add_liquidity(uint256[4],uint256)" ); uint256 toCurvePoolSize = 4; uint256 toCurveUnderlyingIndex = 0; address toCurveUnderlying = dai; // Remove liquidity address fromCurve = curvePools[fromIndex]; address fromCurveLp = curveLps[fromIndex]; address payable target0 = payable(address(curveProxyLogic)); bytes memory data0 = abi.encodeWithSignature( "remove_liquidity_one_coin(address,address,int128)", fromCurve, fromCurveLp, fromCurveUnderlyingIndex ); // Add liquidity address toCurve = curvePools[toIndex]; address payable target1 = payable(address(curveProxyLogic)); bytes memory data1 = abi.encodeWithSignature( "add_liquidity(address,bytes4,uint256,uint256,address)", toCurve, toCurveFunctionSig, toCurvePoolSize, toCurveUnderlyingIndex, toCurveUnderlying ); // Swap _test_curve_curve( fromIndex, toIndex, amount, _getDynamicArray(target0, target1), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_curve_1() public { uint256 fromIndex = 0; uint256 toIndex = 2; uint256 amount = 400e18; int128 fromCurveUnderlyingIndex = 0; bytes4 toCurveFunctionSig = _getFunctionSig( "add_liquidity(uint256[2],uint256)" ); uint256 toCurvePoolSize = 2; uint256 toCurveUnderlyingIndex = 1; address toCurveUnderlying = wbtc; // Remove liquidity address fromCurve = curvePools[fromIndex]; address fromCurveLp = curveLps[fromIndex]; bytes memory data0 = abi.encodeWithSignature( "remove_liquidity_one_coin(address,address,int128)", fromCurve, fromCurveLp, fromCurveUnderlyingIndex ); // Swap bytes memory data1 = _get_uniswap_pl_swap_data(dai, toCurveUnderlying); // Add liquidity address toCurve = curvePools[toIndex]; bytes memory data2 = abi.encodeWithSignature( "add_liquidity(address,bytes4,uint256,uint256,address)", toCurve, toCurveFunctionSig, toCurvePoolSize, toCurveUnderlyingIndex, toCurveUnderlying ); _test_curve_curve( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1, data2) ); } function test_jar_converter_curve_curve_2() public { uint256 fromIndex = 1; uint256 toIndex = 0; uint256 amount = 400e18; int128 fromCurveUnderlyingIndex = 1; bytes4 toCurveFunctionSig = _getFunctionSig( "add_liquidity(uint256[3],uint256)" ); uint256 toCurvePoolSize = 3; uint256 toCurveUnderlyingIndex = 2; address toCurveUnderlying = usdt; // Remove liquidity address fromCurve = susdv2_deposit; // curvePools[fromIndex]; address fromCurveLp = curveLps[fromIndex]; bytes memory data0 = abi.encodeWithSignature( "remove_liquidity_one_coin(address,address,int128)", fromCurve, fromCurveLp, fromCurveUnderlyingIndex ); // Swap bytes memory data1 = _get_uniswap_pl_swap_data(usdc, usdt); // Add liquidity address toCurve = curvePools[toIndex]; bytes memory data2 = abi.encodeWithSignature( "add_liquidity(address,bytes4,uint256,uint256,address)", toCurve, toCurveFunctionSig, toCurvePoolSize, toCurveUnderlyingIndex, toCurveUnderlying ); _test_curve_curve( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1, data2) ); } function test_jar_converter_curve_curve_3() public { uint256 fromIndex = 2; uint256 toIndex = 0; uint256 amount = 4e6; int128 fromCurveUnderlyingIndex = 1; bytes4 toCurveFunctionSig = _getFunctionSig( "add_liquidity(uint256[3],uint256)" ); uint256 toCurvePoolSize = 3; uint256 toCurveUnderlyingIndex = 1; address toCurveUnderlying = usdc; // Remove liquidity address fromCurve = curvePools[fromIndex]; address fromCurveLp = curveLps[fromIndex]; bytes memory data0 = abi.encodeWithSignature( "remove_liquidity_one_coin(address,address,int128)", fromCurve, fromCurveLp, fromCurveUnderlyingIndex ); // Swap bytes memory data1 = _get_uniswap_pl_swap_data(wbtc, usdc); // Add liquidity address toCurve = curvePools[toIndex]; bytes memory data2 = abi.encodeWithSignature( "add_liquidity(address,bytes4,uint256,uint256,address)", toCurve, toCurveFunctionSig, toCurvePoolSize, toCurveUnderlyingIndex, toCurveUnderlying ); _test_curve_curve( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1, data2) ); } function test_jar_converter_curve_curve_4() public { uint256 fromIndex = 1; uint256 toIndex = 0; uint256 amount = 400e18; int128 fromCurveUnderlyingIndex = 2; bytes4 toCurveFunctionSig = _getFunctionSig( "add_liquidity(uint256[3],uint256)" ); uint256 toCurvePoolSize = 3; uint256 toCurveUnderlyingIndex = 1; address toCurveUnderlying = usdc; // Remove liquidity address fromCurve = susdv2_deposit; address fromCurveLp = curveLps[fromIndex]; bytes memory data0 = abi.encodeWithSignature( "remove_liquidity_one_coin(address,address,int128)", fromCurve, fromCurveLp, fromCurveUnderlyingIndex ); // Swap bytes memory data1 = _get_uniswap_pl_swap_data(usdt, usdc); // Add liquidity address toCurve = curvePools[toIndex]; bytes memory data2 = abi.encodeWithSignature( "add_liquidity(address,bytes4,uint256,uint256,address)", toCurve, toCurveFunctionSig, toCurvePoolSize, toCurveUnderlyingIndex, toCurveUnderlying ); _test_curve_curve( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1, data2) ); } } contract StrategyCurveUniJarSwapTest is DSTestDefiBase { address governance; address strategist; address devfund; address treasury; address timelock; IStrategy[] curveStrategies; IStrategy[] uniStrategies; PickleJar[] curvePickleJars; PickleJar[] uniPickleJars; ControllerV4 controller; CurveProxyLogic curveProxyLogic; UniswapV2ProxyLogic uniswapV2ProxyLogic; address[] curvePools; address[] curveLps; address[] uniUnderlying; // Contract wide variable to avoid stack too deep errors uint256 temp; function setUp() public { governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); // Curve Strategies curveStrategies = new IStrategy[](3); curvePickleJars = new PickleJar[](curveStrategies.length); curveLps = new address[](curveStrategies.length); curvePools = new address[](curveStrategies.length); curveLps[0] = three_crv; curvePools[0] = three_pool; curveStrategies[0] = IStrategy( address( new StrategyCurve3CRVv2( governance, strategist, address(controller), timelock ) ) ); curveLps[1] = scrv; curvePools[1] = susdv2_pool; curveStrategies[1] = IStrategy( address( new StrategyCurveSCRVv3_2( governance, strategist, address(controller), timelock ) ) ); curveLps[2] = ren_crv; curvePools[2] = ren_pool; curveStrategies[2] = IStrategy( address( new StrategyCurveRenCRVv2( governance, strategist, address(controller), timelock ) ) ); // Create PICKLE Jars for (uint256 i = 0; i < curvePickleJars.length; i++) { curvePickleJars[i] = new PickleJar( curveStrategies[i].want(), governance, timelock, address(controller) ); controller.setJar( curveStrategies[i].want(), address(curvePickleJars[i]) ); controller.approveStrategy( curveStrategies[i].want(), address(curveStrategies[i]) ); controller.setStrategy( curveStrategies[i].want(), address(curveStrategies[i]) ); } // Uni strategies uniStrategies = new IStrategy[](4); uniUnderlying = new address[](uniStrategies.length); uniPickleJars = new PickleJar[](uniStrategies.length); uniUnderlying[0] = dai; uniStrategies[0] = IStrategy( address( new StrategyUniEthDaiLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[1] = usdc; uniStrategies[1] = IStrategy( address( new StrategyUniEthUsdcLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[2] = usdt; uniStrategies[2] = IStrategy( address( new StrategyUniEthUsdtLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[3] = wbtc; uniStrategies[3] = IStrategy( address( new StrategyUniEthWBtcLpV2( governance, strategist, address(controller), timelock ) ) ); for (uint256 i = 0; i < uniStrategies.length; i++) { uniPickleJars[i] = new PickleJar( uniStrategies[i].want(), governance, timelock, address(controller) ); controller.setJar( uniStrategies[i].want(), address(uniPickleJars[i]) ); controller.approveStrategy( uniStrategies[i].want(), address(uniStrategies[i]) ); controller.setStrategy( uniStrategies[i].want(), address(uniStrategies[i]) ); } curveProxyLogic = new CurveProxyLogic(); uniswapV2ProxyLogic = new UniswapV2ProxyLogic(); controller.approveJarConverter(address(curveProxyLogic)); controller.approveJarConverter(address(uniswapV2ProxyLogic)); hevm.warp(startTime); } function _getCurveLP(address curve, uint256 amount) internal { if (curve == ren_pool) { _getERC20(wbtc, amount); uint256 _wbtc = IERC20(wbtc).balanceOf(address(this)); IERC20(wbtc).approve(curve, _wbtc); uint256[2] memory liquidity; liquidity[1] = _wbtc; ICurveFi_2(curve).add_liquidity(liquidity, 0); } else { _getERC20(dai, amount); uint256 _dai = IERC20(dai).balanceOf(address(this)); IERC20(dai).approve(curve, _dai); if (curve == three_pool) { uint256[3] memory liquidity; liquidity[0] = _dai; ICurveFi_3(curve).add_liquidity(liquidity, 0); } else { uint256[4] memory liquidity; liquidity[0] = _dai; ICurveFi_4(curve).add_liquidity(liquidity, 0); } } } function _get_primitive_to_lp_data( address from, address to, address dustRecipient ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "primitiveToLpTokens(address,address,address)", from, to, dustRecipient ); } function _get_curve_remove_liquidity_data( address curve, address curveLP, int128 index ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "remove_liquidity_one_coin(address,address,int128)", curve, curveLP, index ); } // Some post swap checks // Checks if there's any leftover funds in the converter contract function _post_swap_check(uint256 fromIndex, uint256 toIndex) internal { IERC20 token0 = curvePickleJars[fromIndex].token(); IUniswapV2Pair token1 = IUniswapV2Pair( address(uniPickleJars[toIndex].token()) ); uint256 MAX_DUST = 1000; // No funds left behind assertEq(curvePickleJars[fromIndex].balanceOf(address(controller)), 0); assertEq(uniPickleJars[toIndex].balanceOf(address(controller)), 0); assertTrue(token0.balanceOf(address(controller)) < MAX_DUST); assertTrue(token1.balanceOf(address(controller)) < MAX_DUST); // Curve -> UNI LP should be optimal supply // Note: We refund the access, which is why its checking this balance assertTrue(IERC20(token1.token0()).balanceOf(address(this)) < MAX_DUST); assertTrue(IERC20(token1.token1()).balanceOf(address(this)) < MAX_DUST); // Make sure only controller can call 'withdrawForSwap' try curveStrategies[fromIndex].withdrawForSwap(0) { revert("!withdraw-for-swap-only-controller"); } catch {} } function _test_check_treasury_fee(uint256 _amount, uint256 earned) internal { assertEqApprox( _amount.mul(controller.convenienceFee()).div( controller.convenienceFeeMax() ), earned.mul(2) ); } function _test_swap_and_check_balances( address fromPickleJar, address toPickleJar, address fromPickleJarUnderlying, uint256 fromPickleJarUnderlyingAmount, address payable[] memory targets, bytes[] memory data ) internal { uint256 _beforeTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _beforeFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _beforeDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _beforeTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 _ret = controller.swapExactJarForJar( fromPickleJar, toPickleJar, fromPickleJarUnderlyingAmount, 0, // Min receive amount targets, data ); uint256 _afterTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _afterFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _afterDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _afterTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 treasuryEarned = _afterTreasury.sub(_beforeTreasury); assertEq(treasuryEarned, _afterDev.sub(_beforeDev)); assertTrue(treasuryEarned > 0); _test_check_treasury_fee(fromPickleJarUnderlyingAmount, treasuryEarned); assertTrue(_afterFrom < _beforeFrom); assertTrue(_afterTo > _beforeTo); assertTrue(_afterTo.sub(_beforeTo) > 0); assertEq(_afterTo.sub(_beforeTo), _ret); assertEq(_afterFrom, 0); } function _test_curve_uni_swap( uint256 fromIndex, uint256 toIndex, uint256 amount, address payable[] memory targets, bytes[] memory data ) internal { // Deposit into PickleJars address from = address(curvePickleJars[fromIndex].token()); _getCurveLP(curvePools[fromIndex], amount); uint256 _from = IERC20(from).balanceOf(address(this)); IERC20(from).approve(address(curvePickleJars[fromIndex]), _from); curvePickleJars[fromIndex].deposit(_from); curvePickleJars[fromIndex].earn(); // Swap! uint256 _fromPickleJar = IERC20(address(curvePickleJars[fromIndex])) .balanceOf(address(this)); IERC20(address(curvePickleJars[fromIndex])).approve( address(controller), _fromPickleJar ); // Check minimum amount try controller.swapExactJarForJar( address(curvePickleJars[fromIndex]), address(uniPickleJars[toIndex]), _fromPickleJar, uint256(-1), // Min receive amount targets, data ) { revert("min-amount-should-fail"); } catch {} _test_swap_and_check_balances( address(curvePickleJars[fromIndex]), address(uniPickleJars[toIndex]), from, _fromPickleJar, targets, data ); _post_swap_check(fromIndex, toIndex); } // **** Tests **** // function test_jar_converter_curve_uni_0_0() public { uint256 fromIndex = 0; uint256 toIndex = 0; uint256 amount = 400e18; address fromUnderlying = dai; int128 fromUnderlyingIndex = 0; address curvePool = curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_0_1() public { uint256 fromIndex = 0; uint256 toIndex = 1; uint256 amount = 400e18; address fromUnderlying = usdc; int128 fromUnderlyingIndex = 1; address curvePool = curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_0_2() public { uint256 fromIndex = 0; uint256 toIndex = 2; uint256 amount = 400e18; address fromUnderlying = usdt; int128 fromUnderlyingIndex = 2; address curvePool = curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_0_3() public { uint256 fromIndex = 0; uint256 toIndex = 3; uint256 amount = 400e18; address fromUnderlying = usdt; int128 fromUnderlyingIndex = 2; address curvePool = curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_1_0() public { uint256 fromIndex = 1; uint256 toIndex = 0; uint256 amount = 400e18; address fromUnderlying = usdt; int128 fromUnderlyingIndex = 2; address curvePool = susdv2_deposit; // curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_1_1() public { uint256 fromIndex = 1; uint256 toIndex = 1; uint256 amount = 400e18; address fromUnderlying = dai; int128 fromUnderlyingIndex = 0; address curvePool = susdv2_deposit; // curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_1_2() public { uint256 fromIndex = 1; uint256 toIndex = 2; uint256 amount = 400e18; address fromUnderlying = dai; int128 fromUnderlyingIndex = 0; address curvePool = susdv2_deposit; // curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_1_3() public { uint256 fromIndex = 1; uint256 toIndex = 3; uint256 amount = 400e18; address fromUnderlying = dai; int128 fromUnderlyingIndex = 0; address curvePool = susdv2_deposit; // curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_curve_uni_2_3() public { uint256 fromIndex = 2; uint256 toIndex = 3; uint256 amount = 4e6; address fromUnderlying = wbtc; int128 fromUnderlyingIndex = 1; address curvePool = curvePools[fromIndex]; address toUnderlying = uniUnderlying[toIndex]; address toWant = univ2Factory.getPair(weth, toUnderlying); bytes memory data0 = _get_curve_remove_liquidity_data( curvePool, curveLps[fromIndex], fromUnderlyingIndex ); bytes memory data1 = _get_primitive_to_lp_data( fromUnderlying, toWant, treasury ); _test_curve_uni_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(curveProxyLogic)), payable(address(uniswapV2ProxyLogic)) ), _getDynamicArray(data0, data1) ); } } contract StrategyUniCurveJarSwapTest is DSTestDefiBase { address governance; address strategist; address devfund; address treasury; address timelock; IStrategy[] curveStrategies; IStrategy[] uniStrategies; PickleJar[] curvePickleJars; PickleJar[] uniPickleJars; ControllerV4 controller; CurveProxyLogic curveProxyLogic; UniswapV2ProxyLogic uniswapV2ProxyLogic; address[] curvePools; address[] curveLps; address[] uniUnderlying; // Contract wide variable to avoid stack too deep errors uint256 temp; function setUp() public { governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); // Curve Strategies curveStrategies = new IStrategy[](3); curvePickleJars = new PickleJar[](curveStrategies.length); curveLps = new address[](curveStrategies.length); curvePools = new address[](curveStrategies.length); curveLps[0] = three_crv; curvePools[0] = three_pool; curveStrategies[0] = IStrategy( address( new StrategyCurve3CRVv2( governance, strategist, address(controller), timelock ) ) ); curveLps[1] = scrv; curvePools[1] = susdv2_pool; curveStrategies[1] = IStrategy( address( new StrategyCurveSCRVv3_2( governance, strategist, address(controller), timelock ) ) ); curveLps[2] = ren_crv; curvePools[2] = ren_pool; curveStrategies[2] = IStrategy( address( new StrategyCurveRenCRVv2( governance, strategist, address(controller), timelock ) ) ); // Create PICKLE Jars for (uint256 i = 0; i < curvePickleJars.length; i++) { curvePickleJars[i] = new PickleJar( curveStrategies[i].want(), governance, timelock, address(controller) ); controller.setJar( curveStrategies[i].want(), address(curvePickleJars[i]) ); controller.approveStrategy( curveStrategies[i].want(), address(curveStrategies[i]) ); controller.setStrategy( curveStrategies[i].want(), address(curveStrategies[i]) ); } // Uni strategies uniStrategies = new IStrategy[](4); uniUnderlying = new address[](uniStrategies.length); uniPickleJars = new PickleJar[](uniStrategies.length); uniUnderlying[0] = dai; uniStrategies[0] = IStrategy( address( new StrategyUniEthDaiLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[1] = usdc; uniStrategies[1] = IStrategy( address( new StrategyUniEthUsdcLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[2] = usdt; uniStrategies[2] = IStrategy( address( new StrategyUniEthUsdtLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[3] = wbtc; uniStrategies[3] = IStrategy( address( new StrategyUniEthWBtcLpV2( governance, strategist, address(controller), timelock ) ) ); for (uint256 i = 0; i < uniStrategies.length; i++) { uniPickleJars[i] = new PickleJar( uniStrategies[i].want(), governance, timelock, address(controller) ); controller.setJar( uniStrategies[i].want(), address(uniPickleJars[i]) ); controller.approveStrategy( uniStrategies[i].want(), address(uniStrategies[i]) ); controller.setStrategy( uniStrategies[i].want(), address(uniStrategies[i]) ); } curveProxyLogic = new CurveProxyLogic(); uniswapV2ProxyLogic = new UniswapV2ProxyLogic(); controller.approveJarConverter(address(curveProxyLogic)); controller.approveJarConverter(address(uniswapV2ProxyLogic)); hevm.warp(startTime); } function _getUniLP( address lp, uint256 ethAmount, uint256 otherAmount ) internal { IUniswapV2Pair fromPair = IUniswapV2Pair(lp); address other = fromPair.token0() != weth ? fromPair.token0() : fromPair.token1(); _getERC20(other, otherAmount); uint256 _other = IERC20(other).balanceOf(address(this)); IERC20(other).safeApprove(address(univ2), 0); IERC20(other).safeApprove(address(univ2), _other); univ2.addLiquidityETH{value: ethAmount}( other, _other, 0, 0, address(this), now + 60 ); } function _get_uniswap_remove_liquidity_data(address pair) internal pure returns (bytes memory) { return abi.encodeWithSignature("removeLiquidity(address)", pair); } function _get_uniswap_lp_tokens_to_primitive(address from, address to) internal pure returns (bytes memory) { return abi.encodeWithSignature( "lpTokensToPrimitive(address,address)", from, to ); } function _get_curve_add_liquidity_data( address curve, bytes4 curveFunctionSig, uint256 curvePoolSize, uint256 curveUnderlyingIndex, address underlying ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "add_liquidity(address,bytes4,uint256,uint256,address)", curve, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, underlying ); } // Some post swap checks // Checks if there's any leftover funds in the converter contract function _post_swap_check(uint256 fromIndex, uint256 toIndex) internal { IERC20 token0 = uniPickleJars[fromIndex].token(); IERC20 token1 = curvePickleJars[toIndex].token(); // No funds left behind assertEq(uniPickleJars[fromIndex].balanceOf(address(controller)), 0); assertEq(curvePickleJars[toIndex].balanceOf(address(controller)), 0); assertEq(token0.balanceOf(address(controller)), 0); assertEq(token1.balanceOf(address(controller)), 0); assertEq(IERC20(wbtc).balanceOf(address(controller)), 0); // assertEq(IERC20(usdt).balanceOf(address(controller)), 0); // assertEq(IERC20(usdc).balanceOf(address(controller)), 0); // assertEq(IERC20(susd).balanceOf(address(controller)), 0); // assertEq(IERC20(dai).balanceOf(address(controller)), 0); // No balance left behind! assertEq(token1.balanceOf(address(this)), 0); // Make sure only controller can call 'withdrawForSwap' try uniStrategies[fromIndex].withdrawForSwap(0) { revert("!withdraw-for-swap-only-controller"); } catch {} } function _test_check_treasury_fee(uint256 _amount, uint256 earned) internal { assertEqApprox( _amount.mul(controller.convenienceFee()).div( controller.convenienceFeeMax() ), earned.mul(2) ); } function _test_swap_and_check_balances( address fromPickleJar, address toPickleJar, address fromPickleJarUnderlying, uint256 fromPickleJarUnderlyingAmount, address payable[] memory targets, bytes[] memory data ) internal { uint256 _beforeTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _beforeFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _beforeDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _beforeTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 _ret = controller.swapExactJarForJar( fromPickleJar, toPickleJar, fromPickleJarUnderlyingAmount, 0, // Min receive amount targets, data ); uint256 _afterTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _afterFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _afterDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _afterTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 treasuryEarned = _afterTreasury.sub(_beforeTreasury); assertEq(treasuryEarned, _afterDev.sub(_beforeDev)); assertTrue(treasuryEarned > 0); _test_check_treasury_fee(fromPickleJarUnderlyingAmount, treasuryEarned); assertTrue(_afterFrom < _beforeFrom); assertTrue(_afterTo > _beforeTo); assertTrue(_afterTo.sub(_beforeTo) > 0); assertEq(_afterTo.sub(_beforeTo), _ret); assertEq(_afterFrom, 0); } function _test_uni_curve_swap( uint256 fromIndex, uint256 toIndex, uint256 amount, address payable[] memory targets, bytes[] memory data ) internal { // Deposit into PickleJars address from = address(uniPickleJars[fromIndex].token()); _getUniLP(from, 1e18, amount); uint256 _from = IERC20(from).balanceOf(address(this)); IERC20(from).approve(address(uniPickleJars[fromIndex]), _from); uniPickleJars[fromIndex].deposit(_from); uniPickleJars[fromIndex].earn(); // Swap! uint256 _fromPickleJar = IERC20(address(uniPickleJars[fromIndex])) .balanceOf(address(this)); IERC20(address(uniPickleJars[fromIndex])).approve( address(controller), _fromPickleJar ); // Check minimum amount try controller.swapExactJarForJar( address(uniPickleJars[fromIndex]), address(curvePickleJars[toIndex]), _fromPickleJar, uint256(-1), // Min receive amount targets, data ) { revert("min-amount-should-fail"); } catch {} _test_swap_and_check_balances( address(uniPickleJars[fromIndex]), address(curvePickleJars[toIndex]), from, _fromPickleJar, targets, data ); _post_swap_check(fromIndex, toIndex); } // **** Tests **** // function test_jar_converter_uni_curve_0_0() public { uint256 fromIndex = 0; uint256 toIndex = 0; uint256 amount = 400e18; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 3; address curveUnderlying = dai; uint256 curveUnderlyingIndex = 0; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[3],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_1_0() public { uint256 fromIndex = 1; uint256 toIndex = 0; uint256 amount = 400e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 3; address curveUnderlying = dai; uint256 curveUnderlyingIndex = 0; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[3],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_2_0() public { uint256 fromIndex = 2; uint256 toIndex = 0; uint256 amount = 400e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 3; address curveUnderlying = dai; uint256 curveUnderlyingIndex = 0; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[3],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_3_0() public { uint256 fromIndex = 3; uint256 toIndex = 0; uint256 amount = 4e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 3; address curveUnderlying = dai; uint256 curveUnderlyingIndex = 0; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[3],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_0_1() public { uint256 fromIndex = 0; uint256 toIndex = 1; uint256 amount = 400e18; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 4; address curveUnderlying = usdt; uint256 curveUnderlyingIndex = 2; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[4],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_1_1() public { uint256 fromIndex = 1; uint256 toIndex = 1; uint256 amount = 400e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 4; address curveUnderlying = usdt; uint256 curveUnderlyingIndex = 2; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[4],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_2_1() public { uint256 fromIndex = 2; uint256 toIndex = 1; uint256 amount = 400e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 4; address curveUnderlying = usdt; uint256 curveUnderlyingIndex = 2; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[4],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_3_1() public { uint256 fromIndex = 3; uint256 toIndex = 1; uint256 amount = 4e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 4; address curveUnderlying = usdt; uint256 curveUnderlyingIndex = 2; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[4],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_4_1() public { uint256 fromIndex = 3; uint256 toIndex = 1; uint256 amount = 4e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 4; address curveUnderlying = usdt; uint256 curveUnderlyingIndex = 2; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[4],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_0_2() public { uint256 fromIndex = 0; uint256 toIndex = 2; uint256 amount = 400e18; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 2; address curveUnderlying = wbtc; uint256 curveUnderlyingIndex = 1; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[2],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_1_2() public { uint256 fromIndex = 1; uint256 toIndex = 2; uint256 amount = 400e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 2; address curveUnderlying = wbtc; uint256 curveUnderlyingIndex = 1; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[2],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_2_2() public { uint256 fromIndex = 2; uint256 toIndex = 2; uint256 amount = 400e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 2; address curveUnderlying = wbtc; uint256 curveUnderlyingIndex = 1; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[2],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } function test_jar_converter_uni_curve_3_2() public { uint256 fromIndex = 3; uint256 toIndex = 2; uint256 amount = 4e6; address fromUnderlying = uniUnderlying[fromIndex]; address curvePool = curvePools[toIndex]; uint256 curvePoolSize = 2; address curveUnderlying = wbtc; uint256 curveUnderlyingIndex = 1; bytes4 curveFunctionSig = _getFunctionSig( "add_liquidity(uint256[2],uint256)" ); bytes memory data0 = _get_uniswap_lp_tokens_to_primitive( univ2Factory.getPair(weth, fromUnderlying), curveUnderlying ); bytes memory data1 = _get_curve_add_liquidity_data( curvePool, curveFunctionSig, curvePoolSize, curveUnderlyingIndex, curveUnderlying ); _test_uni_curve_swap( fromIndex, toIndex, amount, _getDynamicArray( payable(address(uniswapV2ProxyLogic)), payable(address(curveProxyLogic)) ), _getDynamicArray(data0, data1) ); } } contract StrategyUniUniJarSwapTest is DSTestDefiBase { address governance; address strategist; address devfund; address treasury; address timelock; IStrategy[] uniStrategies; PickleJar[] uniPickleJars; ControllerV4 controller; CurveProxyLogic curveProxyLogic; UniswapV2ProxyLogic uniswapV2ProxyLogic; address[] uniUnderlying; function setUp() public { governance = address(this); strategist = address(this); devfund = address(new User()); treasury = address(new User()); timelock = address(this); controller = new ControllerV4( governance, strategist, timelock, devfund, treasury ); // Uni strategies uniStrategies = new IStrategy[](4); uniUnderlying = new address[](uniStrategies.length); uniPickleJars = new PickleJar[](uniStrategies.length); uniUnderlying[0] = dai; uniStrategies[0] = IStrategy( address( new StrategyUniEthDaiLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[1] = usdc; uniStrategies[1] = IStrategy( address( new StrategyUniEthUsdcLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[2] = usdt; uniStrategies[2] = IStrategy( address( new StrategyUniEthUsdtLpV4( governance, strategist, address(controller), timelock ) ) ); uniUnderlying[3] = wbtc; uniStrategies[3] = IStrategy( address( new StrategyUniEthWBtcLpV2( governance, strategist, address(controller), timelock ) ) ); for (uint256 i = 0; i < uniStrategies.length; i++) { uniPickleJars[i] = new PickleJar( uniStrategies[i].want(), governance, timelock, address(controller) ); controller.setJar( uniStrategies[i].want(), address(uniPickleJars[i]) ); controller.approveStrategy( uniStrategies[i].want(), address(uniStrategies[i]) ); controller.setStrategy( uniStrategies[i].want(), address(uniStrategies[i]) ); } curveProxyLogic = new CurveProxyLogic(); uniswapV2ProxyLogic = new UniswapV2ProxyLogic(); controller.approveJarConverter(address(curveProxyLogic)); controller.approveJarConverter(address(uniswapV2ProxyLogic)); hevm.warp(startTime); } function _getUniLP( address lp, uint256 ethAmount, uint256 otherAmount ) internal { IUniswapV2Pair fromPair = IUniswapV2Pair(lp); address other = fromPair.token0() != weth ? fromPair.token0() : fromPair.token1(); _getERC20(other, otherAmount); uint256 _other = IERC20(other).balanceOf(address(this)); IERC20(other).safeApprove(address(univ2), 0); IERC20(other).safeApprove(address(univ2), _other); univ2.addLiquidityETH{value: ethAmount}( other, _other, 0, 0, address(this), now + 60 ); } function _get_swap_lp_data( address from, address to, address dustRecipient ) internal pure returns (bytes memory) { return abi.encodeWithSignature( "swapUniLPTokens(address,address,address)", from, to, dustRecipient ); } function _post_swap_check(uint256 fromIndex, uint256 toIndex) internal { IERC20 token0 = uniPickleJars[fromIndex].token(); IERC20 token1 = uniPickleJars[toIndex].token(); uint256 MAX_DUST = 10; // No funds left behind assertEq(uniPickleJars[fromIndex].balanceOf(address(controller)), 0); assertEq(uniPickleJars[toIndex].balanceOf(address(controller)), 0); assertTrue(token0.balanceOf(address(controller)) < MAX_DUST); assertTrue(token1.balanceOf(address(controller)) < MAX_DUST); // Make sure only controller can call 'withdrawForSwap' try uniStrategies[fromIndex].withdrawForSwap(0) { revert("!withdraw-for-swap-only-controller"); } catch {} } function _test_check_treasury_fee(uint256 _amount, uint256 earned) internal { assertEqApprox( _amount.mul(controller.convenienceFee()).div( controller.convenienceFeeMax() ), earned.mul(2) ); } function _test_swap_and_check_balances( address fromPickleJar, address toPickleJar, address fromPickleJarUnderlying, uint256 fromPickleJarUnderlyingAmount, address payable[] memory targets, bytes[] memory data ) internal { uint256 _beforeTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _beforeFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _beforeDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _beforeTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 _ret = controller.swapExactJarForJar( fromPickleJar, toPickleJar, fromPickleJarUnderlyingAmount, 0, // Min receive amount targets, data ); uint256 _afterTo = IERC20(toPickleJar).balanceOf(address(this)); uint256 _afterFrom = IERC20(fromPickleJar).balanceOf(address(this)); uint256 _afterDev = IERC20(fromPickleJarUnderlying).balanceOf(devfund); uint256 _afterTreasury = IERC20(fromPickleJarUnderlying).balanceOf( treasury ); uint256 treasuryEarned = _afterTreasury.sub(_beforeTreasury); assertEq(treasuryEarned, _afterDev.sub(_beforeDev)); assertTrue(treasuryEarned > 0); _test_check_treasury_fee(fromPickleJarUnderlyingAmount, treasuryEarned); assertTrue(_afterFrom < _beforeFrom); assertTrue(_afterTo > _beforeTo); assertTrue(_afterTo.sub(_beforeTo) > 0); assertEq(_afterTo.sub(_beforeTo), _ret); assertEq(_afterFrom, 0); } function _test_uni_uni( uint256 fromIndex, uint256 toIndex, uint256 amount, address payable[] memory targets, bytes[] memory data ) internal { address from = address(uniPickleJars[fromIndex].token()); _getUniLP(from, 1e18, amount); uint256 _from = IERC20(from).balanceOf(address(this)); IERC20(from).approve(address(uniPickleJars[fromIndex]), _from); uniPickleJars[fromIndex].deposit(_from); uniPickleJars[fromIndex].earn(); // Swap! uint256 _fromPickleJar = IERC20(address(uniPickleJars[fromIndex])) .balanceOf(address(this)); IERC20(address(uniPickleJars[fromIndex])).approve( address(controller), _fromPickleJar ); // Check minimum amount try controller.swapExactJarForJar( address(uniPickleJars[fromIndex]), address(uniPickleJars[toIndex]), _fromPickleJar, uint256(-1), // Min receive amount targets, data ) { revert("min-amount-should-fail"); } catch {} _test_swap_and_check_balances( address(uniPickleJars[fromIndex]), address(uniPickleJars[toIndex]), from, _fromPickleJar, targets, data ); _post_swap_check(fromIndex, toIndex); } // **** Tests **** function test_jar_converter_uni_uni_0() public { uint256 fromIndex = 0; uint256 toIndex = 1; uint256 amount = 400e18; address fromUnderlying = uniUnderlying[fromIndex]; address from = univ2Factory.getPair(weth, fromUnderlying); address toUnderlying = uniUnderlying[toIndex]; address to = univ2Factory.getPair(weth, toUnderlying); _test_uni_uni( fromIndex, toIndex, amount, _getDynamicArray(payable(address(uniswapV2ProxyLogic))), _getDynamicArray(_get_swap_lp_data(from, to, treasury)) ); } function test_jar_converter_uni_uni_1() public { uint256 fromIndex = 0; uint256 toIndex = 2; uint256 amount = 400e18; address fromUnderlying = uniUnderlying[fromIndex]; address from = univ2Factory.getPair(weth, fromUnderlying); address toUnderlying = uniUnderlying[toIndex]; address to = univ2Factory.getPair(weth, toUnderlying); _test_uni_uni( fromIndex, toIndex, amount, _getDynamicArray(payable(address(uniswapV2ProxyLogic))), _getDynamicArray(_get_swap_lp_data(from, to, treasury)) ); } function test_jar_converter_uni_uni_2() public { uint256 fromIndex = 2; uint256 toIndex = 3; uint256 amount = 400e6; address fromUnderlying = uniUnderlying[fromIndex]; address from = univ2Factory.getPair(weth, fromUnderlying); address toUnderlying = uniUnderlying[toIndex]; address to = univ2Factory.getPair(weth, toUnderlying); _test_uni_uni( fromIndex, toIndex, amount, _getDynamicArray(payable(address(uniswapV2ProxyLogic))), _getDynamicArray(_get_swap_lp_data(from, to, treasury)) ); } function test_jar_converter_uni_uni_3() public { uint256 fromIndex = 3; uint256 toIndex = 2; uint256 amount = 4e6; address fromUnderlying = uniUnderlying[fromIndex]; address from = univ2Factory.getPair(weth, fromUnderlying); address toUnderlying = uniUnderlying[toIndex]; address to = univ2Factory.getPair(weth, toUnderlying); _test_uni_uni( fromIndex, toIndex, amount, _getDynamicArray(payable(address(uniswapV2ProxyLogic))), _getDynamicArray(_get_swap_lp_data(from, to, treasury)) ); } }
Anyone can harvest it at any given time. I understand the possibility of being frontrun But ETH is a dark forest, and I wanna see how this plays out i.e. will be be heavily frontrunned? if so, a new strategy will be deployed. stablecoin we want to convert to Collects crv tokens Don't bother voting in v1 x% is sent back to the rewards holder to be used to lock up in as veCRV in a future date
function harvest() public onlyBenevolent override { (address to, uint256 toIndex) = getMostPremium(); ICurveMintr(mintr).mint(gauge); uint256 _crv = IERC20(crv).balanceOf(address(this)); if (_crv > 0) { uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax); if (_keepCRV > 0) { IERC20(crv).safeTransfer( IController(controller).treasury(), _keepCRV ); } _crv = _crv.sub(_keepCRV); _swapUniswap(crv, to, _crv); } uint256 _to = IERC20(to).balanceOf(address(this)); if (_to > 0) { IERC20(to).safeApprove(curve, 0); IERC20(to).safeApprove(curve, _to); uint256[3] memory liquidity; liquidity[toIndex] = _to; ICurveFi_3(curve).add_liquidity(liquidity, 0); } _distributePerformanceFeesAndDeposit(); }
7,450,274
// SPDX-License-Identifier: MIT pragma solidity >=0.5.0 <0.9.0; import "./libraries/math/WadRayMath.sol"; import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "hardhat/console.sol"; contract UsdPlusToken is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable, AccessControlUpgradeable, UUPSUpgradeable { using WadRayMath for uint256; using EnumerableSet for EnumerableSet.AddressSet; // --- ERC20 fields mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; // --- fields bytes32 public constant EXCHANGER = keccak256("EXCHANGER"); bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE"); uint256 private _totalMint; uint256 private _totalBurn; uint256 public liquidityIndexChangeTime; uint256 public liquidityIndex; uint256 public liquidityIndexDenominator; EnumerableSet.AddressSet _owners; // --- events event ExchangerUpdated(address exchanger); event LiquidityIndexUpdated(uint256 changeTime, uint256 liquidityIndex); // --- modifiers modifier onlyAdmin() { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Restricted to admins"); _; } modifier onlyExchanger() { require(hasRole(EXCHANGER, msg.sender), "Caller is not the EXCHANGER"); _; } // --- setters function setExchanger(address _exchanger) external onlyAdmin { grantRole(EXCHANGER, _exchanger); emit ExchangerUpdated(_exchanger); } function setLiquidityIndex(uint256 _liquidityIndex) external onlyExchanger { require(_liquidityIndex > 0, "Zero liquidity index not allowed"); liquidityIndex = _liquidityIndex; liquidityIndexChangeTime = block.timestamp; emit LiquidityIndexUpdated(liquidityIndexChangeTime, liquidityIndex); } /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} function initialize() initializer public { __Context_init_unchained(); _name = "USD+"; _symbol = "USD+"; __AccessControl_init(); __UUPSUpgradeable_init(); _grantRole(DEFAULT_ADMIN_ROLE, msg.sender); _grantRole(UPGRADER_ROLE, msg.sender); liquidityIndex = 10 ** 27; // as Ray liquidityIndexDenominator = 10 ** 27; // Ray } function _authorizeUpgrade(address newImplementation) internal onlyRole(UPGRADER_ROLE) override {} // --- logic function mint(address _sender, uint256 _amount) external onlyExchanger { // up to ray uint256 mintAmount = _amount.wadToRay(); mintAmount = mintAmount.rayDiv(liquidityIndex); _mint(_sender, mintAmount); _totalMint += mintAmount; emit Transfer(address(0), _sender, _amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; _afterTokenTransfer(address(0), account, amount); } function burn(address _sender, uint256 _amount) external onlyExchanger { // up to ray uint256 burnAmount = _amount.wadToRay(); burnAmount = burnAmount.rayDiv(liquidityIndex); _burn(_sender, burnAmount); _totalBurn += burnAmount; emit Transfer(_sender, address(0), _amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; _afterTokenTransfer(account, address(0), amount); } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; _afterTokenTransfer(sender, recipient, amount); } /** * @dev See {IERC20-transfer}. */ function transfer(address recipient, uint256 amount) public override returns (bool) { // up to ray uint256 transferAmount = amount.wadToRay(); transferAmount = transferAmount.rayDiv(liquidityIndex); _transfer(_msgSender(), recipient, transferAmount); emit Transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view override returns (uint256) { uint256 allowanceRay = _allowance(owner, spender).rayMul(liquidityIndex); // ray -> wad return allowanceRay.rayToWad(); } /** * @dev See {IERC20-allowance}. */ function _allowance(address owner, address spender) internal view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. */ function approve(address spender, uint256 amount) external override returns (bool){ // up to ray uint256 scaledAmount = amount.wadToRay(); scaledAmount = scaledAmount.rayDiv(liquidityIndex); _approve(_msgSender(), spender, scaledAmount); return true; } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { // up to ray uint256 scaledAmount = amount.wadToRay(); scaledAmount = scaledAmount.rayDiv(liquidityIndex); _transfer(sender, recipient, scaledAmount); uint256 currentAllowance = _allowance(sender, _msgSender()); require(currentAllowance >= scaledAmount, "UsdPlusToken: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - scaledAmount); } emit Transfer(sender, recipient, amount); return true; } /** * @dev Calculates the balance of the user: principal balance + interest generated by the principal * @param user The user whose balance is calculated * @return The balance of the user **/ function balanceOf(address user) public view override returns (uint256) { // stored balance is ray (27) uint256 balanceInMapping = _balanceOf(user); // ray -> ray uint256 balanceRay = balanceInMapping.rayMul(liquidityIndex); // ray -> wad return balanceRay.rayToWad(); } /** * @dev See {IERC20-balanceOf}. */ function _balanceOf(address account) internal view returns (uint256) { return _balances[account]; } /** * @dev Returns the scaled balance of the user. The scaled balance is the sum of all the * updated stored balance divided by the reserve's liquidity index at the moment of the update * @param user The user whose balance is calculated * @return The scaled balance of the user **/ function scaledBalanceOf(address user) external view returns (uint256) { return _balanceOf(user); } /** * @dev calculates the total supply of the specific aToken * since the balance of every single user increases over time, the total supply * does that too. * @return the current total supply **/ function totalSupply() public view override returns (uint256) { // stored totalSupply is ray (27) uint256 currentSupply = _totalSupply; // ray -> ray uint256 currentSupplyRay = currentSupply.rayMul(liquidityIndex); // ray -> wad return currentSupplyRay.rayToWad(); } function totalMint() external view returns (uint256) { uint256 totalMintRay = _totalMint.rayMul(liquidityIndex); return totalMintRay.rayToWad(); } function totalBurn() external view returns (uint256) { uint256 totalBurnRay = _totalBurn.rayMul(liquidityIndex); return totalBurnRay.rayToWad(); } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Returns the scaled total supply of the variable debt token * @return the scaled total supply **/ function scaledTotalSupply() public view returns (uint256) { return _totalSupply; } function ownerLength() external view returns (uint256) { return _owners.length(); } function ownerAt(uint256 index) external view returns (address) { return _owners.at(index); } function ownerBalanceAt(uint256 index) external view returns (uint256) { return balanceOf(_owners.at(index)); } /** * @dev Returns the name of the token. */ function name() public view override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public pure override returns (uint8) { return 6; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal { } function _afterTokenTransfer( address from, address to, uint256 amount ) internal { if (from == address(0)) { // mint _owners.add(to); } else if (to == address(0)) { // burn if (balanceOf(from) == 0) { _owners.remove(from); } } else { // transfer if (balanceOf(from) == 0) { _owners.remove(from); } _owners.add(to); } } uint256[50] private __gap; }
Moves `amount` of tokens from `sender` to `recipient`. This internal function is equivalent to {transfer}, and can be used to e.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `sender` cannot be the zero address. - `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`./
function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; _afterTokenTransfer(sender, recipient, amount); }
15,853,191
// 口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口 // 口口口口口口口口口口口口口       口口口口口口口口口口口口口口口口口口口口口口口口口口口口    口口口口口口口口口 // 口口口口口口口口口口口口         口口口口口口口口口口口口口口口口口口口口口口口口口口口    口口口口口口口口口 // 口口口口口口口口口口口    口口口    口口口口口口口口口口口口口口口口口口口口口口口口口口    口口口口口口口口口 // 口口口口口口口口口口    口口口口口    口口口口口口口口口口口口口口口口口口口口口口口口口    口口口口口口口口口 // 口口口口口口口口口口   口口口口口口口   口口       口口口      口口         口口口口口口口口口 // 口口口口口口口口口    口口口口口口口口口口口         口口      口          口口口口口口口口口 // 口口口口口口口口口    口口口口口口口口口口    口口口   口口    口口口   口口     口口口口口口口口口 // 口口口口口口口口口    口口口口口口口口口口口口口口口口口   口口   口口口    口口口    口口口口口口口口口 // 口口口口口口口口口    口口口口口口口口口口口口         口   口口口   口口口口    口口口口口口口口口 // 口口口口口口口口口    口口口口口口口口口口口          口   口口口   口口口口    口口口口口口口口口 // 口口口口口口口口口口   口口口口口口口       口口口    口   口口口   口口口口    口口口口口口口口口 // 口口口口口口口口口口    口口口口口       口口口口    口   口口口    口口口    口口口口口口口口口 // 口口口口口口口口口口口    口口口    口    口口     口   口口口    口口     口口口口口口口口口 // 口口口口口口口口口口口口          口口          口   口口口口          口口口口口口口口口 // 口口口口口口口口口口口口口       口口口口口         口   口口口口口         口口口口口口口口口 // 口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口 // 口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口 // 口口口    口口口口口口     口口口口口口口口口口口口口   口口口口口口口口口口口口口口口口口口口口口口口口口口口 // 口口口     口口口口口     口口口口口口口口口口口口口   口口口口口口口口口口口口口口口口口口口口口口口口口口口 // 口口口     口口口口口     口口口口口口口口口口口口口   口口口口口口口口口口口口口口口口口口口口口口口口口口口 // 口口口     口口口口      口口口口口口口口口口口口口   口口口口口口口口口口口口口口口口口口口口口口口口口口口 // 口口口      口口口      口口口       口口口   口口    口口口      口口口      口口口 // 口口口      口口口      口口         口口   口    口口         口口      口口口 // 口口口      口口       口    口口口   口口       口口口   口口口    口    口口口口口 // 口口口       口       口口口口口口口口   口口      口口口    口口口口   口   口口口口口口 // 口口口   口   口       口口口         口      口口口           口   口口口口口口 // 口口口   口   口       口口          口      口口口           口   口口口口口口 // 口口口   口      口    口    口口口    口       口口   口口口口口口口口口   口口口口口口 // 口口口   口口     口    口   口口口口    口   口    口    口口口口口口口口   口口口口口口 // 口口口   口口     口    口    口口     口   口口   口口    口口    口   口口口口口口 // 口口口   口口    口口    口口          口   口口    口         口口   口口口口口口 // 口口口   口口口   口口    口口口         口   口口口    口口      口口口   口口口口口口 // 口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口口 //───────────────────────────────────────────────────────────────────────────────────── //         A very insteresting blockchain-game about invent, design, knowledge, ecology, fortune and future //                    The creation team: Wizard, Monk, Assassin //───────────────────────────────────────────────────────────────────────────────────── pragma solidity ^0.4.24; /** * @title Contract that will work with ERC223 tokens. */ contract ERC223ReceivingContract { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data) public; } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer( address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom( address _from, address _to, uint256 _value ) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve( address _spender, uint256 _value ) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval( address _spender, uint _addedValue ) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval( address _spender, uint _subtractedValue ) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } contract Trader { function buy(address _from, uint256 _tokenId, uint256 _count) public; } // 不支持自定义参数,只允许用指定的trader进行购买操作 contract Cake is PausableToken { string public name; string public symbol; uint8 public decimals = 18; mapping(address => bool) public traders; constructor() public { name = "Card Alchemists&#39; Knowledge Energy (CardMaker Cash)"; symbol = "CAKE"; uint256 _totalSupply = 100000000000; // 一千亿 totalSupply_ = _totalSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balances[msg.sender] = totalSupply_; // Give the creator all tokens tokenURI_ = "http://cardmaker.io/cake/token"; } function addTrader(address _trader) public onlyOwner { traders[_trader] = true; } function removeTrader(address _trader) public onlyOwner { delete traders[_trader]; } /** * @dev Transfer the specified amount of tokens to the specified address. * This function doesn&#39;t contain `_data` param. * due to backwards compatibility reasons. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. */ function transfer(address _to, uint _value) public returns (bool) { uint codeLength; bytes memory empty; // solium-disable-next-line security/no-inline-assembly assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } super.transfer(_to, _value); if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, empty); } return true; } function transferAndBuy(address _trader, uint256 _value, uint256 _tokenId, uint256 _count) public { require(traders[_trader], ""); transfer(_trader, _value); Trader(_trader).buy(msg.sender, _tokenId, _count); } function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { uint codeLength; bytes memory empty; // solium-disable-next-line security/no-inline-assembly assembly { // Retrieve the size of the code on target address, this needs assembly . codeLength := extcodesize(_to) } super.transferFrom(_from, _to, _value); if (codeLength > 0) { ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(_from, _value, empty); } return true; } event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public whenNotPaused { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who], "no value to burn"); // no need to require value <= totalSupply, since that would imply the // sender&#39;s balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } // EIP1046/1047 string private tokenURI_ = ""; function tokenURI() external view returns (string) { return tokenURI_; } }
no need to require value <= totalSupply, since that would imply the sender&39;s balance is greater than the totalSupply, which should be an assertion failure
function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who], "no value to burn"); balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); }
15,053,884
// SPDX-License-Identifier: MIT /**************************************************************** ** ** ** ██████╗ █████╗ ██████╗ ███╗ ███╗ █████╗ ███╗ ██╗ ** ** ██╔════╝██╔══██╗██╔══██╗ ████╗ ████║██╔══██╗████╗ ██║ ** ** ██║ ███████║██████╔╝ ██╔████╔██║███████║██╔██╗ ██║ ** ** ██║ ██╔══██║██╔══██╗ ██║╚██╔╝██║██╔══██║██║╚██╗██║ ** ** ╚██████╗██║ ██║██║ ██║ ██║ ╚═╝ ██║██║ ██║██║ ╚████║ ** ** ╚═════╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝ ** ** ** ** © 2022 iParking ** ** ** ****************************************************************/ // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); return _allTokens[index]; } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override { super._beforeTokenTransfer(from, to, tokenId); if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } pragma solidity >=0.7.0 <0.9.0; contract CarMan is ERC721Enumerable, Ownable { using Strings for uint256; string public baseURI; string public baseExtension = ".json"; string public notRevealedUri; uint256 public cost = 0.5 ether; uint256 public maxSupply = 2000; uint256 public maxMintAmount = 10; uint256 public nftPerAddressLimit = 10; uint256 public currentPhaseMintMaxAmount = 110; uint32 public publicSaleStart = 1647136800; uint32 public preSaleStart = 1646964000; uint32 public vipSaleStart = 1646618400; bool public publicSalePaused = true; bool public preSalePaused = true; bool public vipSalePaused = true; bool public revealed = false; bool public onlyWhitelisted = true; address[] whitelistedAddresses; mapping(address => uint256) addressMintedBalance; mapping(address => uint256) vipMintAmount; // addresses to manage this contract mapping(address => bool) controllers; constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedUri ) ERC721(_name, _symbol) { baseURI = _initBaseURI; notRevealedUri = _initNotRevealedUri; } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // public function vipSaleMint(uint256 _mintAmount) public { require(_mintAmount > 0, "Mint Amount should be bigger than 0"); require((!vipSalePaused)&&(vipSaleStart <= block.timestamp), "Not Reach VIP Sale Time"); uint256 supply = totalSupply(); require(_mintAmount > 0, "need to mint at least 1 NFT"); require(_mintAmount <= maxMintAmount, "max mint amount per session exceeded"); require(supply + _mintAmount <= currentPhaseMintMaxAmount, "reach current Phase NFT limit"); require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded"); require(vipMintAmount[msg.sender] != 0, "user is not VIP"); uint256 ownerMintedCount = addressMintedBalance[msg.sender]; uint256 vipMintCount = vipMintAmount[msg.sender]; require(ownerMintedCount + _mintAmount <= vipMintCount, "max VIP Mint Amount exceeded"); require(ownerMintedCount + _mintAmount <= nftPerAddressLimit, "max NFT per address exceeded"); for (uint256 i = 1; i <= _mintAmount; i++) { addressMintedBalance[msg.sender]++; _safeMint(msg.sender, supply + i); } } function preSaleMint(uint256 _mintAmount) public payable { require(_mintAmount > 0, "Mint Amount should be bigger than 0"); require((!preSalePaused)&&(preSaleStart <= block.timestamp), "Not Reach Pre Sale Time"); uint256 supply = totalSupply(); require(_mintAmount > 0, "need to mint at least 1 NFT"); require(_mintAmount <= maxMintAmount, "max mint amount per session exceeded"); require(supply + _mintAmount <= currentPhaseMintMaxAmount, "reach current Phase NFT limit"); require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded"); if (msg.sender != owner()) { if(onlyWhitelisted == true) { require(isWhitelisted(msg.sender), "user is not whitelisted"); uint256 ownerMintedCount = addressMintedBalance[msg.sender]; require(ownerMintedCount + _mintAmount <= nftPerAddressLimit, "max NFT per address exceeded"); } require(msg.value >= cost * _mintAmount, "insufficient funds"); } for (uint256 i = 1; i <= _mintAmount; i++) { addressMintedBalance[msg.sender]++; _safeMint(msg.sender, supply + i); } } function publicSaleMint(uint256 _mintAmount) public payable { require(_mintAmount > 0, "Mint Amount should be bigger than 0"); require((!publicSalePaused)&&(publicSaleStart <= block.timestamp), "Not Reach Public Sale Time"); uint256 supply = totalSupply(); require(_mintAmount > 0, "need to mint at least 1 NFT"); require(_mintAmount <= maxMintAmount, "max mint amount per session exceeded"); require(supply + _mintAmount <= currentPhaseMintMaxAmount, "reach current Phase NFT limit"); require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded"); if (msg.sender != owner()) { if(onlyWhitelisted == true) { require(isWhitelisted(msg.sender), "user is not whitelisted"); uint256 ownerMintedCount = addressMintedBalance[msg.sender]; require(ownerMintedCount + _mintAmount <= nftPerAddressLimit, "max NFT per address exceeded"); } require(msg.value >= cost * _mintAmount, "insufficient funds"); } for (uint256 i = 1; i <= _mintAmount; i++) { addressMintedBalance[msg.sender]++; _safeMint(msg.sender, supply + i); } } function isWhitelisted(address _user) public view returns (bool) { for (uint i = 0; i < whitelistedAddresses.length; i++) { if (whitelistedAddresses[i] == _user) { return true; } } return false; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if(revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } function publicSaleIsActive() public view returns (bool) { return ( (publicSaleStart <= block.timestamp) && (!publicSalePaused) ); } function preSaleIsActive() public view returns (bool) { return ( (preSaleStart <= block.timestamp) && (!preSalePaused) ); } function vipSaleIsActive() public view returns (bool) { return ( (vipSaleStart <= block.timestamp) && (!vipSalePaused) ); } function checkVIPMintAmount(address _account) public view returns (uint256) { return vipMintAmount[_account]; } // for controller function reveal(bool _state) public { require(controllers[msg.sender], "Only controllers can operate this function"); revealed = _state; } function setNftPerAddressLimit(uint256 _limit) public { require(controllers[msg.sender], "Only controllers can operate this function"); nftPerAddressLimit = _limit; } function setCost(uint256 _newCost) public { require(controllers[msg.sender], "Only controllers can operate this function"); cost = _newCost; } function setmaxMintAmount(uint256 _newmaxMintAmount) public { require(controllers[msg.sender], "Only controllers can operate this function"); maxMintAmount = _newmaxMintAmount; } function setcurrentPhaseMintMaxAmount(uint256 _newPhaseAmount) public { require(controllers[msg.sender], "Only controllers can operate this function"); currentPhaseMintMaxAmount = _newPhaseAmount; } function setPublicSaleStart(uint32 timestamp) public { require(controllers[msg.sender], "Only controllers can operate this function"); publicSaleStart = timestamp; } function setPreSaleStart(uint32 timestamp) public { require(controllers[msg.sender], "Only controllers can operate this function"); preSaleStart = timestamp; } function setVIPSaleStart(uint32 timestamp) public { require(controllers[msg.sender], "Only controllers can operate this function"); vipSaleStart = timestamp; } function setBaseURI(string memory _newBaseURI) public { require(controllers[msg.sender], "Only controllers can operate this function"); baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public { require(controllers[msg.sender], "Only controllers can operate this function"); baseExtension = _newBaseExtension; } function setNotRevealedURI(string memory _notRevealedURI) public { require(controllers[msg.sender], "Only controllers can operate this function"); notRevealedUri = _notRevealedURI; } function setPreSalePause(bool _state) public { require(controllers[msg.sender], "Only controllers can operate this function"); preSalePaused = _state; } function setVIPSalePause(bool _state) public { require(controllers[msg.sender], "Only controllers can operate this function"); vipSalePaused = _state; } function setVIPMintAmount(address[] memory _accounts, uint256[] memory _amounts) public { require(controllers[msg.sender], "Only controllers can operate this function"); require(_accounts.length == _amounts.length, "accounts and amounts array length mismatch"); for (uint256 i = 0; i < _accounts.length; ++i) { vipMintAmount[_accounts[i]]=_amounts[i]; } } function setPublicSalePause(bool _state) public { require(controllers[msg.sender], "Only controllers can operate this function"); publicSalePaused = _state; } function setOnlyWhitelisted(bool _state) public { require(controllers[msg.sender], "Only controllers can operate this function"); onlyWhitelisted = _state; } function whitelistUsers(address[] calldata _users) public { require(controllers[msg.sender], "Only controllers can operate this function"); delete whitelistedAddresses; whitelistedAddresses = _users; } //only owner /** * enables an address for management * @param controller the address to enable */ function addController(address controller) external onlyOwner { controllers[controller] = true; } /** * disables an address for management * @param controller the address to disbale */ function removeController(address controller) external onlyOwner { controllers[controller] = false; } function withdraw() public onlyOwner { (bool success, ) = payable(msg.sender).call{value: address(this).balance}(""); require(success); } }
disables an address for management controller the address to disbale/
function removeController(address controller) external onlyOwner { controllers[controller] = false; }
185,911
pragma solidity ^0.4.18; /* ASTRCoin ICO - Airdrop code */ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { //was constant uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract ERC20 { function transfer(address receiver, uint amount) public ; function transferFrom(address sender, address receiver, uint amount) public returns(bool success); // do token.approve on the ICO contract function balanceOf(address _owner) constant public returns (uint256 balance); } /** * Airdrop for ASTRCoin */ contract ASTRDrop is Ownable { ERC20 public token; // using the ASTRCoin token - will set an address address public ownerAddress; // deploy owner uint8 internal decimals = 4; // 4 decimal places should be enough in general uint256 internal decimalsConversion = 10 ** uint256(decimals); uint public AIRDROP_AMOUNT = 10 * decimalsConversion; function multisend(address[] dests) onlyOwner public returns (uint256) { ownerAddress = ERC20(0x3EFAe2e152F62F5cc12cc0794b816d22d416a721); // token = ERC20(0x80E7a4d750aDe616Da896C49049B7EdE9e04C191); // uint256 i = 0; while (i < dests.length) { // probably want to keep this to only 20 or 30 addresses at a time token.transferFrom(ownerAddress, dests[i], AIRDROP_AMOUNT); i += 1; } return(i); } // Change the airdrop rate function setAirdropAmount(uint256 _astrAirdrop) onlyOwner public { if( _astrAirdrop > 0 ) { AIRDROP_AMOUNT = _astrAirdrop * decimalsConversion; } } // reset the rate to the default function resetAirdropAmount() onlyOwner public { AIRDROP_AMOUNT = 10 * decimalsConversion; } }
reset the rate to the default
function resetAirdropAmount() onlyOwner public { AIRDROP_AMOUNT = 10 * decimalsConversion; }
15,827,641
/** *Submitted for verification at Etherscan.io on 2021-05-26 */ // SPDX-License-Identifier: GPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: IBaseStrategy interface IBaseStrategy { function apiVersion() external pure returns (string memory); function name() external pure returns (string memory); function vault() external view returns (address); function keeper() external view returns (address); function tendTrigger(uint256 callCost) external view returns (bool); function tend() external; function harvestTrigger(uint256 callCost) external view returns (bool); function harvest() external; function strategist() external view returns (address); } // Part: IGenericLender interface IGenericLender { function lenderName() external view returns (string memory); function nav() external view returns (uint256); function strategy() external view returns (address); function apr() external view returns (uint256); function weightedApr() external view returns (uint256); function withdraw(uint256 amount) external returns (uint256); function emergencyWithdraw(uint256 amount) external; function deposit() external; function withdrawAll() external returns (bool); function hasAssets() external view returns (bool); function aprAfterDeposit(uint256 amount) external view returns (uint256); function setDust(uint256 _dust) external; function sweep(address _token) external; } // Part: InterestRateModel interface InterestRateModel { /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate( uint256 cash, uint256 borrows, uint256 reserves ) external view returns (uint256, uint256); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa ) external view returns (uint256); } // Part: OpenZeppelin/[email protected]/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Part: OpenZeppelin/[email protected]/SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Part: CTokenI interface CTokenI { /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows); /** * @notice Event emitted when tokens are minted */ event Mint(address minter, uint256 mintAmount, uint256 mintTokens); /** * @notice Event emitted when tokens are redeemed */ event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrow(address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrow(address liquidator, address borrower, uint256 repayAmount, address cTokenCollateral, uint256 seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when the reserve factor is changed */ event NewReserveFactor(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint256 amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint256 amount); /** * @notice Failure event */ event Failure(uint256 error, uint256 info, uint256 detail); function transfer(address dst, uint256 amount) external returns (bool); function transferFrom( address src, address dst, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function getAccountSnapshot(address account) external view returns ( uint256, uint256, uint256, uint256 ); function borrowRatePerBlock() external view returns (uint256); function supplyRatePerBlock() external view returns (uint256); function totalBorrowsCurrent() external returns (uint256); function borrowBalanceCurrent(address account) external returns (uint256); function borrowBalanceStored(address account) external view returns (uint256); function exchangeRateCurrent() external returns (uint256); function accrualBlockNumber() external view returns (uint256); function exchangeRateStored() external view returns (uint256); function getCash() external view returns (uint256); function accrueInterest() external returns (uint256); function interestRateModel() external view returns (InterestRateModel); function totalReserves() external view returns (uint256); function reserveFactorMantissa() external view returns (uint256); function seize( address liquidator, address borrower, uint256 seizeTokens ) external returns (uint256); function totalBorrows() external view returns (uint256); function totalSupply() external view returns (uint256); } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Part: iearn-finance/[email protected]/VaultAPI interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } // Part: CErc20I interface CErc20I is CTokenI { function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function borrow(uint256 borrowAmount) external returns (uint256); function repayBorrow(uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256); function liquidateBorrow( address borrower, uint256 repayAmount, CTokenI cTokenCollateral ) external returns (uint256); function underlying() external view returns (address); } // Part: GenericLenderBase abstract contract GenericLenderBase is IGenericLender { using SafeERC20 for IERC20; VaultAPI public vault; address public override strategy; IERC20 public want; string public override lenderName; uint256 public dust; event Cloned(address indexed clone); constructor(address _strategy, string memory _name) public { _initialize(_strategy, _name); } function _initialize(address _strategy, string memory _name) internal { require(address(strategy) == address(0), "Lender already initialized"); strategy = _strategy; vault = VaultAPI(IBaseStrategy(strategy).vault()); want = IERC20(vault.token()); lenderName = _name; dust = 10000; want.safeApprove(_strategy, uint256(-1)); } function initialize(address _strategy, string memory _name) external virtual { _initialize(_strategy, _name); } function _clone(address _strategy, string memory _name) internal returns (address newLender) { // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore(clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(clone_code, 0x14), addressBytes) mstore(add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) newLender := create(0, clone_code, 0x37) } GenericLenderBase(newLender).initialize(_strategy, _name); emit Cloned(newLender); } function setDust(uint256 _dust) external virtual override management { dust = _dust; } function sweep(address _token) external virtual override management { address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(vault.governance(), IERC20(_token).balanceOf(address(this))); } function protectedTokens() internal view virtual returns (address[] memory); //make sure to use modifier management() { require( msg.sender == address(strategy) || msg.sender == vault.governance() || msg.sender == IBaseStrategy(strategy).strategist(), "!management" ); _; } } // File: GenericCream.sol /******************** * A lender plugin for LenderYieldOptimiser for any erc20 asset on Cream (not eth) * Made by SamPriestley.com * https://github.com/Grandthrax/yearnv2/blob/master/contracts/GenericLender/GenericCream.sol * ********************* */ contract GenericCream is GenericLenderBase { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; uint256 private constant blocksPerYear = 2_300_000; uint256 public dustThreshold = 10_000; CErc20I public cToken; constructor( address _strategy, string memory name, address _cToken ) public GenericLenderBase(_strategy, name) { _initialize(_cToken); } function initialize(address _cToken) external { _initialize(_cToken); } function _initialize(address _cToken) internal { require(address(cToken) == address(0), "GenericCream already initialized"); cToken = CErc20I(_cToken); require(cToken.underlying() == address(want), "WRONG CTOKEN"); want.safeApprove(_cToken, uint256(-1)); dustThreshold = 10_000; } function cloneCreamLender( address _strategy, string memory _name, address _cToken ) external returns (address newLender) { newLender = _clone(_strategy, _name); GenericCream(newLender).initialize(_cToken); } function nav() external view override returns (uint256) { return _nav(); } function _nav() internal view returns (uint256) { uint256 amount = want.balanceOf(address(this)).add(underlyingBalanceStored()); if(amount < dustThreshold){ return 0; }else{ return amount; } } function underlyingBalanceStored() public view returns (uint256 balance) { uint256 currentCr = cToken.balanceOf(address(this)); if (currentCr < dustThreshold) { balance = 0; } else { //The current exchange rate as an unsigned integer, scaled by 1e18. balance = currentCr.mul(cToken.exchangeRateStored()).div(1e18); } } function convertFromUnderlying(uint256 amountOfUnderlying) public view returns (uint256 balance){ if (amountOfUnderlying == 0) { balance = 0; } else { balance = amountOfUnderlying.mul(1e18).div(cToken.exchangeRateStored()); } } function apr() external view override returns (uint256) { return _apr(); } function _apr() internal view returns (uint256) { return cToken.supplyRatePerBlock().mul(blocksPerYear); } function weightedApr() external view override returns (uint256) { uint256 a = _apr(); return a.mul(_nav()); } function withdraw(uint256 amount) external override management returns (uint256) { return _withdraw(amount); } //emergency withdraw. sends balance plus amount to governance function emergencyWithdraw(uint256 amount) external override management { //dont care about error here cToken.redeem(amount); want.safeTransfer(vault.governance(), want.balanceOf(address(this))); } //adjust dust threshol function setDustThreshold(uint256 amount) external management { dustThreshold = amount; } //withdraw an amount including any want balance function _withdraw(uint256 amount) internal returns (uint256) { uint256 balanceUnderlying = cToken.balanceOfUnderlying(address(this)); uint256 looseBalance = want.balanceOf(address(this)); uint256 total = balanceUnderlying.add(looseBalance); if (amount.add(dustThreshold) >= total) { //cant withdraw more than we own. so withdraw all we can if(balanceUnderlying > dustThreshold){ require(cToken.redeem(cToken.balanceOf(address(this))) == 0, "ctoken: redeemAll fail"); } looseBalance = want.balanceOf(address(this)); want.safeTransfer(address(strategy), looseBalance); return looseBalance; } if (looseBalance >= amount) { want.safeTransfer(address(strategy), amount); return amount; } //not state changing but OK because of previous call uint256 liquidity = want.balanceOf(address(cToken)); if (liquidity > 1) { uint256 toWithdraw = amount.sub(looseBalance); //we can take all if (toWithdraw > liquidity) { toWithdraw = liquidity; } require(cToken.redeemUnderlying(toWithdraw) == 0, "ctoken: redeemUnderlying fail"); } looseBalance = want.balanceOf(address(this)); want.safeTransfer(address(strategy), looseBalance); return looseBalance; } function deposit() external override management { uint256 balance = want.balanceOf(address(this)); require(cToken.mint(balance) == 0, "ctoken: mint fail"); } //we use different method to withdraw for safety function withdrawAll() external override management returns (bool all) { uint256 liquidity = want.balanceOf(address(cToken)); uint256 liquidityInCTokens = convertFromUnderlying(liquidity); uint256 amountInCtokens = cToken.balanceOf(address(this)); if (liquidityInCTokens > 2) { liquidityInCTokens = liquidityInCTokens-1; if (amountInCtokens <= liquidityInCTokens) { //we can take all all = true; cToken.redeem(amountInCtokens); } else { //redo or else price changes cToken.mint(0); liquidityInCTokens = convertFromUnderlying(want.balanceOf(address(cToken))); //take all we can all = false; cToken.redeem(liquidityInCTokens); } } return all; } function hasAssets() external view override returns (bool) { return cToken.balanceOf(address(this)) > dustThreshold; } function aprAfterDeposit(uint256 amount) external view override returns (uint256) { uint256 cashPrior = want.balanceOf(address(cToken)); uint256 borrows = cToken.totalBorrows(); uint256 reserves = cToken.totalReserves(); uint256 reserverFactor = cToken.reserveFactorMantissa(); InterestRateModel model = cToken.interestRateModel(); //the supply rate is derived from the borrow rate, reserve factor and the amount of total borrows. uint256 supplyRate = model.getSupplyRate(cashPrior.add(amount), borrows, reserves, reserverFactor); return supplyRate.mul(blocksPerYear); } function protectedTokens() internal view override returns (address[] memory) { address[] memory protected = new address[](2); protected[0] = address(want); protected[1] = address(cToken); return protected; } }
emergency withdraw. sends balance plus amount to governancedont care about error here
function emergencyWithdraw(uint256 amount) external override management { cToken.redeem(amount); want.safeTransfer(vault.governance(), want.balanceOf(address(this))); }
2,154,516
pragma solidity ^0.4.21; library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract ERC827 is ERC20 { function approve( address _spender, uint256 _value, bytes _data ) public returns (bool); function transfer( address _to, uint256 _value, bytes _data ) public returns (bool); function transferFrom( address _from, address _to, uint256 _value, bytes _data ) public returns (bool); } contract ERC827Token is ERC827, StandardToken { /** @dev Addition to ERC20 token methods. It allows to approve the transfer of value and execute a call with the sent data. Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this race condition is to first reduce the spender&#39;s allowance to 0 and set the desired value afterwards: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 @param _spender The address that will spend the funds. @param _value The amount of tokens to be spent. @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function approve(address _spender, uint256 _value, bytes _data) public returns (bool) { require(_spender != address(this)); super.approve(_spender, _value); require(_spender.call(_data)); return true; } /** @dev Addition to ERC20 token methods. Transfer tokens to a specified address and execute a call with the sent data on the same transaction @param _to address The address which you want to transfer to @param _value uint256 the amout of tokens to be transfered @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function transfer(address _to, uint256 _value, bytes _data) public returns (bool) { require(_to != address(this)); super.transfer(_to, _value); require(_to.call(_data)); return true; } /** @dev Addition to ERC20 token methods. Transfer tokens from one address to another and make a contract call on the same transaction @param _from The address which you want to send tokens from @param _to The address which you want to transfer to @param _value The amout of tokens to be transferred @param _data ABI-encoded contract call to call `_to` address. @return true if the call function was executed successfully */ function transferFrom(address _from, address _to, uint256 _value, bytes _data) public returns (bool) { require(_to != address(this)); super.transferFrom(_from, _to, _value); require(_to.call(_data)); return true; } /** * @dev Addition to StandardToken methods. Increase the amount of tokens that * an owner allowed to a spender and execute a call with the sent data. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. * @param _data ABI-encoded contract call to call `_spender` address. */ function increaseApproval(address _spender, uint _addedValue, bytes _data) public returns (bool) { require(_spender != address(this)); super.increaseApproval(_spender, _addedValue); require(_spender.call(_data)); return true; } /** * @dev Addition to StandardToken methods. Decrease the amount of tokens that * an owner allowed to a spender and execute a call with the sent data. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. * @param _data ABI-encoded contract call to call `_spender` address. */ function decreaseApproval(address _spender, uint _subtractedValue, bytes _data) public returns (bool) { require(_spender != address(this)); super.decreaseApproval(_spender, _subtractedValue); require(_spender.call(_data)); return true; } } contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender&#39;s balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply_ = totalSupply_.sub(_value); Burn(burner, _value); Transfer(burner, address(0), _value); } } contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title DAOToken, based on zeppelin contract. * @dev ERC20 compatible token. It is a mintable and burnable token. */ contract TestToken is ERC827Token, MintableToken, BurnableToken { string public name; string public symbol; uint8 public constant decimals = 18; uint public cap; /** * @dev Constructor * @param _name - token name * @param _symbol - token symbol * @param _cap - token cap - 0 value means no cap */ function TestToken(string _name, string _symbol,uint _cap) public { name = _name; symbol = _symbol; cap = _cap; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { if (cap > 0) require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } }
Constructor _name - token name _symbol - token symbol _cap - token cap - 0 value means no cap/
function TestToken(string _name, string _symbol,uint _cap) public { name = _name; symbol = _symbol; cap = _cap; }
6,737,538
./full_match/1/0x1807e79594A19de9a887f0A1448F4AB4c347B763/sources/lib/relic-sdk/packages/contracts/lib/Storage.sol
compute the slot for a struct field given the base slot and offset base the slot of the struct base offset the slot offset in the struct/
function structFieldSlot( bytes32 base, uint256 offset ) internal pure returns (bytes32) { return bytes32(uint256(base) + offset); }
17,042,462
/* * This file was generated by MyWish Platform (https://mywish.io/) * The complete code could be found at https://github.com/MyWishPlatform/ * Copyright (C) 2018 MyWish * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ pragma solidity ^0.4.20; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint256) { return allowed[_owner][_spender]; } /** * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale { using SafeMath for uint256; // The token being sold MintableToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // how many token units a buyer gets per wei uint256 public rate; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != address(0)); token = createTokenContract(); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (MintableToken) { return new MintableToken(); } // fallback function can be used to buy tokens function () external payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.mul(rate); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal view returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { return now > endTime; } } /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); finalization(); Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } /** * @title RefundVault * @dev This contract is used for storing funds while a crowdsale * is in progress. Supports refunding the money if crowdsale fails, * and forwarding it if crowdsale is successful. */ contract RefundVault is Ownable { using SafeMath for uint256; enum State { Active, Refunding, Closed } mapping (address => uint256) public deposited; address public wallet; State public state; event Closed(); event RefundsEnabled(); event Refunded(address indexed beneficiary, uint256 weiAmount); function RefundVault(address _wallet) public { require(_wallet != address(0)); wallet = _wallet; state = State.Active; } function deposit(address investor) onlyOwner public payable { require(state == State.Active); deposited[investor] = deposited[investor].add(msg.value); } function close() onlyOwner public { require(state == State.Active); state = State.Closed; Closed(); wallet.transfer(this.balance); } function enableRefunds() onlyOwner public { require(state == State.Active); state = State.Refunding; RefundsEnabled(); } function refund(address investor) public { require(state == State.Refunding); uint256 depositedValue = deposited[investor]; deposited[investor] = 0; investor.transfer(depositedValue); Refunded(investor, depositedValue); } } contract FreezableToken is StandardToken { // freezing chains mapping (bytes32 => uint64) internal chains; // freezing amounts for each chain mapping (bytes32 => uint) internal freezings; // total freezing balance per address mapping (address => uint) internal freezingBalance; event Freezed(address indexed to, uint64 release, uint amount); event Released(address indexed owner, uint amount); /** * @dev Gets the balance of the specified address include freezing tokens. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner) + freezingBalance[_owner]; } /** * @dev Gets the balance of the specified address without freezing tokens. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function actualBalanceOf(address _owner) public view returns (uint256 balance) { return super.balanceOf(_owner); } function freezingBalanceOf(address _owner) public view returns (uint256 balance) { return freezingBalance[_owner]; } /** * @dev gets freezing count * @param _addr Address of freeze tokens owner. */ function freezingCount(address _addr) public view returns (uint count) { uint64 release = chains[toKey(_addr, 0)]; while (release != 0) { count ++; release = chains[toKey(_addr, release)]; } } /** * @dev gets freezing end date and freezing balance for the freezing portion specified by index. * @param _addr Address of freeze tokens owner. * @param _index Freezing portion index. It ordered by release date descending. */ function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) { for (uint i = 0; i < _index + 1; i ++) { _release = chains[toKey(_addr, _release)]; if (_release == 0) { return; } } _balance = freezings[toKey(_addr, _release)]; } /** * @dev freeze your tokens to the specified address. * Be careful, gas usage is not deterministic, * and depends on how many freezes _to address already has. * @param _to Address to which token will be freeze. * @param _amount Amount of token to freeze. * @param _until Release date, must be in future. */ function freezeTo(address _to, uint _amount, uint64 _until) public { require(_to != address(0)); require(_amount <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBalance[_to].add(_amount); freeze(_to, _until); Transfer(msg.sender, _to, _amount); Freezed(_to, _until, _amount); } /** * @dev release first available freezing tokens. */ function releaseOnce() public { bytes32 headKey = toKey(msg.sender, 0); uint64 head = chains[headKey]; require(head != 0); require(uint64(block.timestamp) > head); bytes32 currentKey = toKey(msg.sender, head); uint64 next = chains[currentKey]; uint amount = freezings[currentKey]; delete freezings[currentKey]; balances[msg.sender] = balances[msg.sender].add(amount); freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount); if (next == 0) { delete chains[headKey]; } else { chains[headKey] = next; delete chains[currentKey]; } Released(msg.sender, amount); } /** * @dev release all available for release freezing tokens. Gas usage is not deterministic! * @return how many tokens was released */ function releaseAll() public returns (uint tokens) { uint release; uint balance; (release, balance) = getFreezing(msg.sender, 0); while (release != 0 && block.timestamp > release) { releaseOnce(); tokens += balance; (release, balance) = getFreezing(msg.sender, 0); } } function toKey(address _addr, uint _release) internal pure returns (bytes32 result) { // WISH masc to increase entropy result = 0x5749534800000000000000000000000000000000000000000000000000000000; assembly { result := or(result, mul(_addr, 0x10000000000000000)) result := or(result, _release) } } function freeze(address _to, uint64 _until) internal { require(_until > block.timestamp); bytes32 key = toKey(_to, _until); bytes32 parentKey = toKey(_to, uint64(0)); uint64 next = chains[parentKey]; if (next == 0) { chains[parentKey] = _until; return; } bytes32 nextKey = toKey(_to, next); uint parent; while (next != 0 && _until > next) { parent = next; parentKey = nextKey; next = chains[nextKey]; nextKey = toKey(_to, next); } if (_until == next) { return; } if (next != 0) { chains[key] = next; } chains[parentKey] = _until; } } /** * @title Contract that will work with ERC223 tokens. */ contract ERC223Receiver { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data) public; } contract ERC223Basic is ERC20Basic { function transfer(address to, uint value, bytes data) public returns (bool); event Transfer(address indexed from, address indexed to, uint value, bytes data); } contract SuccessfulERC223Receiver is ERC223Receiver { event Invoked(address from, uint value, bytes data); function tokenFallback(address _from, uint _value, bytes _data) public { Invoked(_from, _value, _data); } } contract FailingERC223Receiver is ERC223Receiver { function tokenFallback(address, uint, bytes) public { revert(); } } contract ERC223ReceiverWithoutTokenFallback { } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is StandardToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { require(_value > 0); require(_value <= balances[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balances[burner] = balances[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract FreezableMintableToken is FreezableToken, MintableToken { /** * @dev Mint the specified amount of token to the specified address and freeze it until the specified date. * Be careful, gas usage is not deterministic, * and depends on how many freezes _to address already has. * @param _to Address to which token will be freeze. * @param _amount Amount of token to mint and freeze. * @param _until Release date, must be in future. * @return A boolean that indicates if the operation was successful. */ function mintAndFreeze(address _to, uint _amount, uint64 _until) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); bytes32 currentKey = toKey(_to, _until); freezings[currentKey] = freezings[currentKey].add(_amount); freezingBalance[_to] = freezingBalance[_to].add(_amount); freeze(_to, _until); Mint(_to, _amount); Freezed(_to, _until, _amount); Transfer(msg.sender, _to, _amount); return true; } } contract Consts { uint constant TOKEN_DECIMALS = 2; uint8 constant TOKEN_DECIMALS_UINT8 = 2; uint constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS; string constant TOKEN_NAME = "marketLIST"; string constant TOKEN_SYMBOL = "LIST"; bool constant PAUSED = true; address constant TARGET_USER = 0x17238a53f266f058C4A1CbC616f4308E4226FEBF; uint constant START_TIME = 1524481200; bool constant CONTINUE_MINTING = false; } /** * @title Reference implementation of the ERC223 standard token. */ contract ERC223Token is ERC223Basic, BasicToken, FailingERC223Receiver { using SafeMath for uint; /** * @dev Transfer the specified amount of tokens to the specified address. * Invokes the `tokenFallback` function if the recipient is a contract. * The token transfer fails if the recipient is a contract * but does not implement the `tokenFallback` function * or the fallback function to receive funds. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. * @param _data Transaction metadata. */ function transfer(address _to, uint _value, bytes _data) public returns (bool) { // Standard function transfer similar to ERC20 transfer with no _data . // Added due to backwards compatibility reasons . uint codeLength; assembly { // Retrieve the size of the code on target address, this needs assembly. codeLength := extcodesize(_to) } balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); if(codeLength > 0) { ERC223Receiver receiver = ERC223Receiver(_to); receiver.tokenFallback(msg.sender, _value, _data); } Transfer(msg.sender, _to, _value, _data); return true; } /** * @dev Transfer the specified amount of tokens to the specified address. * This function works the same with the previous one * but doesn't contain `_data` param. * Added due to backwards compatibility reasons. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { bytes memory empty; return transfer(_to, _value, empty); } } contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable { function name() pure public returns (string _name) { return TOKEN_NAME; } function symbol() pure public returns (string _symbol) { return TOKEN_SYMBOL; } function decimals() pure public returns (uint8 _decimals) { return TOKEN_DECIMALS_UINT8; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) { require(!paused); return super.transferFrom(_from, _to, _value); } function transfer(address _to, uint256 _value) public returns (bool _success) { require(!paused); return super.transfer(_to, _value); } } /** * @title CappedCrowdsale * @dev Extension of Crowdsale with a max amount of funds raised */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 public cap; function CappedCrowdsale(uint256 _cap) public { require(_cap > 0); cap = _cap; } // overriding Crowdsale#validPurchase to add extra cap logic // @return true if investors can buy at the moment function validPurchase() internal view returns (bool) { bool withinCap = weiRaised.add(msg.value) <= cap; return super.validPurchase() && withinCap; } // overriding Crowdsale#hasEnded to add cap logic // @return true if crowdsale event has ended function hasEnded() public view returns (bool) { bool capReached = weiRaised >= cap; return super.hasEnded() || capReached; } } /** * @title RefundableCrowdsale * @dev Extension of Crowdsale contract that adds a funding goal, and * the possibility of users getting a refund if goal is not met. * Uses a RefundVault as the crowdsale's vault. */ contract RefundableCrowdsale is FinalizableCrowdsale { using SafeMath for uint256; // minimum amount of funds to be raised in weis uint256 public goal; // refund vault used to hold funds while crowdsale is running RefundVault public vault; function RefundableCrowdsale(uint256 _goal) public { require(_goal > 0); vault = new RefundVault(wallet); goal = _goal; } // We're overriding the fund forwarding from Crowdsale. // In addition to sending the funds, we want to call // the RefundVault deposit function function forwardFunds() internal { vault.deposit.value(msg.value)(msg.sender); } // if crowdsale is unsuccessful, investors can claim refunds here function claimRefund() public { require(isFinalized); require(!goalReached()); vault.refund(msg.sender); } // vault finalization task, called when owner calls finalize() function finalization() internal { if (goalReached()) { vault.close(); } else { vault.enableRefunds(); } super.finalization(); } function goalReached() public view returns (bool) { return weiRaised >= goal; } } contract MainCrowdsale is Consts, FinalizableCrowdsale { function hasStarted() public constant returns (bool) { return now >= startTime; } function finalization() internal { super.finalization(); if (PAUSED) { MainToken(token).unpause(); } if (!CONTINUE_MINTING) { token.finishMinting(); } token.transferOwnership(TARGET_USER); } function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 tokens = weiAmount.mul(rate).div(1 ether); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } } contract Checkable { address private serviceAccount; /** * Flag means that contract accident already occurs. */ bool private triggered = false; /** * Occurs when accident happened. */ event Triggered(uint balance); /** * Occurs when check finished. */ event Checked(bool isAccident); function Checkable() public { serviceAccount = msg.sender; } /** * @dev Replace service account with new one. * @param _account Valid service account address. */ function changeServiceAccount(address _account) onlyService public { assert(_account != 0); serviceAccount = _account; } /** * @dev Is caller (sender) service account. */ function isServiceAccount() view public returns (bool) { return msg.sender == serviceAccount; } /** * Public check method. */ function check() onlyService notTriggered payable public { if (internalCheck()) { Triggered(this.balance); triggered = true; internalAction(); } } /** * @dev Do inner check. * @return bool true of accident triggered, false otherwise. */ function internalCheck() internal returns (bool); /** * @dev Do inner action if check was success. */ function internalAction() internal; modifier onlyService { require(msg.sender == serviceAccount); _; } modifier notTriggered() { require(!triggered); _; } } contract BonusableCrowdsale is Consts, Crowdsale { function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); uint256 weiAmount = msg.value; // calculate token amount to be created uint256 bonusRate = getBonusRate(weiAmount); uint256 tokens = weiAmount.mul(bonusRate).div(1 ether); // update state weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); forwardFunds(); } function getBonusRate(uint256 weiAmount) internal view returns (uint256) { uint256 bonusRate = rate; // apply bonus for time & weiRaised uint[3] memory weiRaisedStartsBoundaries = [uint(0),uint(0),uint(0)]; uint[3] memory weiRaisedEndsBoundaries = [uint(67000000000000000000000),uint(67000000000000000000000),uint(67000000000000000000000)]; uint64[3] memory timeStartsBoundaries = [uint64(1524481200),uint64(1525086000),uint64(1525690800)]; uint64[3] memory timeEndsBoundaries = [uint64(1525086000),uint64(1525690800),uint64(1526295600)]; uint[3] memory weiRaisedAndTimeRates = [uint(100),uint(70),uint(50)]; for (uint i = 0; i < 3; i++) { bool weiRaisedInBound = (weiRaisedStartsBoundaries[i] <= weiRaised) && (weiRaised < weiRaisedEndsBoundaries[i]); bool timeInBound = (timeStartsBoundaries[i] <= now) && (now < timeEndsBoundaries[i]); if (weiRaisedInBound && timeInBound) { bonusRate += bonusRate * weiRaisedAndTimeRates[i] / 1000; } } return bonusRate; } } contract TemplateCrowdsale is Consts, MainCrowdsale , BonusableCrowdsale , CappedCrowdsale , Checkable { event Initialized(); bool public initialized = false; function TemplateCrowdsale(MintableToken _token) public Crowdsale(START_TIME > now ? START_TIME : now, 1529751600, 10000 * TOKEN_DECIMAL_MULTIPLIER, 0x048B8E1e604AE9DE680dB49ed2EC0D57f45090d6) CappedCrowdsale(67000000000000000000000) { token = _token; } function init() public onlyOwner { require(!initialized); initialized = true; if (PAUSED) { MainToken(token).pause(); } address[1] memory addresses = [address(0x17238a53f266f058c4a1cbc616f4308e4226febf)]; uint[1] memory amounts = [uint(33000000000)]; uint64[1] memory freezes = [uint64(1529751661)]; for (uint i = 0; i < addresses.length; i++) { if (freezes[i] == 0) { MainToken(token).mint(addresses[i], amounts[i]); } else { MainToken(token).mintAndFreeze(addresses[i], amounts[i], freezes[i]); } } transferOwnership(TARGET_USER); Initialized(); } /** * @dev override token creation to set token address in constructor. */ function createTokenContract() internal returns (MintableToken) { return MintableToken(0); } /** * @dev Do inner check. * @return bool true of accident triggered, false otherwise. */ function internalCheck() internal returns (bool) { bool result = !isFinalized && hasEnded(); Checked(result); return result; } /** * @dev Do inner action if check was success. */ function internalAction() internal { finalization(); Finalized(); isFinalized = true; } /** * @dev override purchase validation to add extra value logic. * @return true if sended more than minimal value */ function validPurchase() internal view returns (bool) { bool minValue = msg.value >= 100000000000000000; bool maxValue = msg.value <= 1000000000000000000000; return minValue && maxValue && super.validPurchase(); } /** * @dev override hasEnded to add minimal value logic * @return true if remained to achieve less than minimal */ function hasEnded() public view returns (bool) { bool remainValue = cap.sub(weiRaised) < 100000000000000000; return super.hasEnded() || remainValue; } }
event for token purchase logging purchaser who paid for the tokens beneficiary who got the tokens value weis paid for purchase amount amount of tokens purchased/
function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public { require(_startTime >= now); require(_endTime >= _startTime); require(_rate > 0); require(_wallet != address(0)); token = createTokenContract(); startTime = _startTime; endTime = _endTime; rate = _rate; wallet = _wallet; }
104,816
/** *Submitted for verification at Etherscan.io on 2021-07-25 */ /* B.PROTOCOL TERMS OF USE ======================= THE TERMS OF USE CONTAINED HEREIN (THESE “TERMS”) GOVERN YOUR USE OF B.PROTOCOL, WHICH IS A DECENTRALIZED PROTOCOL ON THE ETHEREUM BLOCKCHAIN (the “PROTOCOL”) THAT enables a backstop liquidity mechanism FOR DECENTRALIZED LENDING PLATFORMS (“DLPs”). PLEASE READ THESE TERMS CAREFULLY AT https://github.com/backstop-protocol/Terms-and-Conditions, INCLUDING ALL DISCLAIMERS AND RISK FACTORS, BEFORE USING THE PROTOCOL. BY USING THE PROTOCOL, YOU ARE IRREVOCABLY CONSENTING TO BE BOUND BY THESE TERMS. IF YOU DO NOT AGREE TO ALL OF THESE TERMS, DO NOT USE THE PROTOCOL. YOUR RIGHT TO USE THE PROTOCOL IS SUBJECT AND DEPENDENT BY YOUR AGREEMENT TO ALL TERMS AND CONDITIONS SET FORTH HEREIN, WHICH AGREEMENT SHALL BE EVIDENCED BY YOUR USE OF THE PROTOCOL. Minors Prohibited: The Protocol is not directed to individuals under the age of eighteen (18) or the age of majority in your jurisdiction if the age of majority is greater. If you are under the age of eighteen or the age of majority (if greater), you are not authorized to access or use the Protocol. By using the Protocol, you represent and warrant that you are above such age. License; No Warranties; Limitation of Liability; (a) The software underlying the Protocol is licensed for use in accordance with the 3-clause BSD License, which can be accessed here: https://opensource.org/licenses/BSD-3-Clause. (b) THE PROTOCOL IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS", “WITH ALL FAULTS” and “AS AVAILABLE” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. (c) 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. */ // Sources flattened with hardhat v2.5.0 https://hardhat.org // File @openzeppelin/contracts/GSN/[email protected] pragma solidity ^0.5.0; pragma experimental ABIEncoderV2; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/ownership/[email protected] pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File contracts/bprotocol/proxy/GnosisSafeProxy.sol pragma solidity >=0.5.0 <0.7.0; /// @title IProxy - Helper interface to access masterCopy of the Proxy on-chain /// @author Richard Meissner - <[email protected]> interface IProxy { function masterCopy() external view returns (address); } /// @title GnosisSafeProxy - Generic proxy contract allows to execute all transactions applying the code of a master contract. /// @author Stefan George - <[email protected]> /// @author Richard Meissner - <[email protected]> contract GnosisSafeProxy { // masterCopy always needs to be first declared variable, to ensure that it is at the same location in the contracts to which calls are delegated. // To reduce deployment costs this variable is internal and needs to be retrieved via `getStorageAt` address internal masterCopy; /// @dev Constructor function sets address of master copy contract. /// @param _masterCopy Master copy address. constructor(address _masterCopy) public { require(_masterCopy != address(0), "Invalid master copy address provided"); masterCopy = _masterCopy; } /// @dev Fallback function forwards all transactions and returns all received return data. function () external payable { // solium-disable-next-line security/no-inline-assembly assembly { let masterCopy := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff) // 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s if eq(calldataload(0), 0xa619486e00000000000000000000000000000000000000000000000000000000) { mstore(0, masterCopy) return(0, 0x20) } calldatacopy(0, 0, calldatasize()) let success := delegatecall(gas, masterCopy, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) if eq(success, 0) { revert(0, returndatasize()) } return(0, returndatasize()) } } } // File contracts/bprotocol/interfaces/IAvatar.sol pragma solidity 0.5.16; contract IERC20Avatar { function transfer(address cToken, address dst, uint256 amount) external returns (bool); function transferFrom(address cToken, address src, address dst, uint256 amount) external returns (bool); function approve(address cToken, address spender, uint256 amount) public returns (bool); } contract IAvatar is IERC20Avatar { function initialize(address _registry, address comp, address compVoter) external; function quit() external returns (bool); function canUntop() public returns (bool); function toppedUpCToken() external returns (address); function toppedUpAmount() external returns (uint256); function redeem(address cToken, uint256 redeemTokens, address payable userOrDelegatee) external returns (uint256); function redeemUnderlying(address cToken, uint256 redeemAmount, address payable userOrDelegatee) external returns (uint256); function borrow(address cToken, uint256 borrowAmount, address payable userOrDelegatee) external returns (uint256); function borrowBalanceCurrent(address cToken) external returns (uint256); function collectCToken(address cToken, address from, uint256 cTokenAmt) public; function liquidateBorrow(uint repayAmount, address cTokenCollateral) external payable returns (uint256); // Comptroller functions function enterMarket(address cToken) external returns (uint256); function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory); function exitMarket(address cToken) external returns (uint256); function claimComp() external; function claimComp(address[] calldata bTokens) external; function claimComp(address[] calldata bTokens, bool borrowers, bool suppliers) external; function getAccountLiquidity() external view returns (uint err, uint liquidity, uint shortFall); } // Workaround for issue https://github.com/ethereum/solidity/issues/526 // CEther contract IAvatarCEther is IAvatar { function mint() external payable; function repayBorrow() external payable; function repayBorrowBehalf(address borrower) external payable; } // CErc20 contract IAvatarCErc20 is IAvatar { function mint(address cToken, uint256 mintAmount) external returns (uint256); function repayBorrow(address cToken, uint256 repayAmount) external returns (uint256); function repayBorrowBehalf(address cToken, address borrower, uint256 repayAmount) external returns (uint256); } contract ICushion { function liquidateBorrow(uint256 underlyingAmtToLiquidate, uint256 amtToDeductFromTopup, address cTokenCollateral) external payable returns (uint256); function canLiquidate() external returns (bool); function untop(uint amount) external; function toppedUpAmount() external returns (uint); function remainingLiquidationAmount() external returns(uint); function getMaxLiquidationAmount(address debtCToken) public returns (uint256); } contract ICushionCErc20 is ICushion { function topup(address cToken, uint256 topupAmount) external; } contract ICushionCEther is ICushion { function topup() external payable; } // File contracts/bprotocol/Registry.sol pragma solidity 0.5.16; /** * @dev Registry contract to maintain Compound, BProtocol and avatar address. */ contract Registry is Ownable { // Compound Contracts address public comptroller; address public comp; address public cEther; // BProtocol Contracts address public pool; address public score; address public compVoter; // this will not be used address public bComptroller; // Avatar address public avatarImpl; // Owner => Avatar mapping (address => address) public avatarOf; // Avatar => Owner mapping (address => address) public ownerOf; address[] public avatars; // An Avatar can have multiple Delegatee // Avatar => Delegatee => bool mapping (address => mapping(address => bool)) public delegate; // dummy caller, for safer delegate and execute DummyCaller public dummyCaller; // (target, 4 bytes) => boolean. For each target address and function call, can avatar call it? // this is to support upgradable features in compound // calls that allow user to change collateral and debt size, and enter/exit market should not be listed mapping (address => mapping(bytes4 => bool)) public whitelistedAvatarCalls; event NewAvatar(address indexed avatar, address owner); event Delegate(address indexed delegator, address avatar, address delegatee); event RevokeDelegate(address indexed delegator, address avatar, address delegatee); event NewPool(address oldPool, address newPool); event NewScore(address oldScore, address newScore); event AvatarCallWhitelisted(address target, bytes4 functionSig, bool whitelist); constructor( address _comptroller, address _comp, address _cEther, address _pool, address _bComptroller, address _compVoter, address _avatarImpl ) public { comptroller = _comptroller; comp = _comp; cEther = _cEther; pool = _pool; bComptroller = _bComptroller; compVoter = _compVoter; avatarImpl = _avatarImpl; dummyCaller = new DummyCaller(); } function setPool(address newPool) external onlyOwner { require(newPool != address(0), "Registry: pool-address-is-zero"); address oldPool = pool; pool = newPool; emit NewPool(oldPool, newPool); } function setScore(address newScore) external onlyOwner { require(newScore != address(0), "Registry: score-address-is-zero"); address oldScore = score; score = newScore; emit NewScore(oldScore, newScore); } function setWhitelistAvatarCall(address target, bytes4 functionSig, bool list) external onlyOwner { whitelistedAvatarCalls[target][functionSig] = list; emit AvatarCallWhitelisted(target, functionSig, list); } function newAvatar() external returns (address) { return _newAvatar(msg.sender); } function getAvatar(address _owner) public returns (address) { require(_owner != address(0), "Registry: owner-address-is-zero"); address _avatar = avatarOf[_owner]; if(_avatar == address(0)) { _avatar = _newAvatar(_owner); } return _avatar; } function delegateAvatar(address delegatee) public { require(delegatee != address(0), "Registry: delegatee-address-is-zero"); address _avatar = avatarOf[msg.sender]; require(_avatar != address(0), "Registry: avatar-not-found"); delegate[_avatar][delegatee] = true; emit Delegate(msg.sender, _avatar, delegatee); } function revokeDelegateAvatar(address delegatee) public { address _avatar = avatarOf[msg.sender]; require(_avatar != address(0), "Registry: avatar-not-found"); require(delegate[_avatar][delegatee], "Registry: not-delegated"); delegate[_avatar][delegatee] = false; emit RevokeDelegate(msg.sender, _avatar, delegatee); } function delegateAndExecuteOnce(address delegatee, address payable target, bytes calldata data) external payable { // make sure there is an avatar getAvatar(msg.sender); delegateAvatar(delegatee); dummyCaller.execute.value(msg.value)(target, data); revokeDelegateAvatar(delegatee); } function _newAvatar(address _owner) internal returns (address) { require(avatarOf[_owner] == address(0), "Registry: avatar-exits-for-owner"); // _owner should not be an avatar address require(ownerOf[_owner] == address(0), "Registry: cannot-create-an-avatar-of-avatar"); // Deploy GnosisSafeProxy with the Avatar contract as logic contract address _avatar = _deployAvatarProxy(_owner); // Initialize Avatar IAvatar(_avatar).initialize(address(this), comp, compVoter); avatarOf[_owner] = _avatar; ownerOf[_avatar] = _owner; avatars.push(_avatar); emit NewAvatar(_avatar, _owner); return _avatar; } function _deployAvatarProxy(address _owner) internal returns (address proxy) { bytes32 salt = keccak256(abi.encodePacked(_owner)); bytes memory proxyCode = type(GnosisSafeProxy).creationCode; bytes memory deploymentData = abi.encodePacked(proxyCode, uint256(avatarImpl)); assembly { proxy := create2(0, add(deploymentData, 0x20), mload(deploymentData), salt) if iszero(extcodesize(proxy)) { revert(0, 0) } } } function avatarLength() external view returns (uint256) { return avatars.length; } function avatarList() external view returns (address[] memory) { return avatars; } function doesAvatarExist(address _avatar) public view returns (bool) { return ownerOf[_avatar] != address(0); } function doesAvatarExistFor(address _owner) public view returns (bool) { return avatarOf[_owner] != address(0); } } contract DummyCaller { function execute(address target, bytes calldata data) external payable { (bool succ, bytes memory err) = target.call.value(msg.value)(data); require(succ, string(err)); } } // File contracts/bprotocol/interfaces/IRegistry.sol pragma solidity 0.5.16; interface IRegistry { // Ownable function transferOwnership(address newOwner) external; // Compound contracts function comp() external view returns (address); function comptroller() external view returns (address); function cEther() external view returns (address); // B.Protocol contracts function bComptroller() external view returns (address); function score() external view returns (address); function pool() external view returns (address); // Avatar functions function delegate(address avatar, address delegatee) external view returns (bool); function doesAvatarExist(address avatar) external view returns (bool); function doesAvatarExistFor(address owner) external view returns (bool); function ownerOf(address avatar) external view returns (address); function avatarOf(address owner) external view returns (address); function newAvatar() external returns (address); function getAvatar(address owner) external returns (address); // avatar whitelisted calls function whitelistedAvatarCalls(address target, bytes4 functionSig) external view returns(bool); function setPool(address newPool) external; function setScore(address newScore) external; function setWhitelistAvatarCall(address target, bytes4 functionSig, bool list) external; } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File contracts/bprotocol/interfaces/CTokenInterfaces.sol pragma solidity 0.5.16; contract CTokenInterface { /* ERC20 */ function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function totalSupply() external view returns (uint256); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); /* User Interface */ function isCToken() external view returns (bool); function underlying() external view returns (IERC20); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) public view returns (uint); function exchangeRateCurrent() public returns (uint); function exchangeRateStored() public view returns (uint); function getCash() external view returns (uint); function accrueInterest() public returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); } contract ICToken is CTokenInterface { /* User Interface */ function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); } // Workaround for issue https://github.com/ethereum/solidity/issues/526 // Defined separate contract as `mint()` override with `.value()` has issues contract ICErc20 is ICToken { function mint(uint mintAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, address cTokenCollateral) external returns (uint); } contract ICEther is ICToken { function mint() external payable; function repayBorrow() external payable; function repayBorrowBehalf(address borrower) external payable; function liquidateBorrow(address borrower, address cTokenCollateral) external payable; } contract IPriceOracle { /** * @notice Get the underlying price of a cToken asset * @param cToken The cToken to get the underlying price of * @return The underlying asset price mantissa (scaled by 1e18). * Zero means the price is unavailable. */ function getUnderlyingPrice(CTokenInterface cToken) external view returns (uint); } // File contracts/bprotocol/lib/CarefulMath.sol pragma solidity 0.5.16; /** * @title Careful Math * @author Compound * @notice COPY TAKEN FROM COMPOUND FINANCE * @notice Derived from OpenZeppelin's SafeMath library * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol */ contract CarefulMath { /** * @dev Possible error codes that we can return */ enum MathError { NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW } /** * @dev Multiplies two numbers, returns an error on overflow. */ function mulUInt(uint a, uint b) internal pure returns (MathError, uint) { if (a == 0) { return (MathError.NO_ERROR, 0); } uint c = a * b; if (c / a != b) { return (MathError.INTEGER_OVERFLOW, 0); } else { return (MathError.NO_ERROR, c); } } /** * @dev Integer division of two numbers, truncating the quotient. */ function divUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b == 0) { return (MathError.DIVISION_BY_ZERO, 0); } return (MathError.NO_ERROR, a / b); } /** * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend). */ function subUInt(uint a, uint b) internal pure returns (MathError, uint) { if (b <= a) { return (MathError.NO_ERROR, a - b); } else { return (MathError.INTEGER_UNDERFLOW, 0); } } /** * @dev Adds two numbers, returns an error on overflow. */ function addUInt(uint a, uint b) internal pure returns (MathError, uint) { uint c = a + b; if (c >= a) { return (MathError.NO_ERROR, c); } else { return (MathError.INTEGER_OVERFLOW, 0); } } /** * @dev add a and b and then subtract c */ function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) { (MathError err0, uint sum) = addUInt(a, b); if (err0 != MathError.NO_ERROR) { return (err0, 0); } return subUInt(sum, c); } } // File contracts/bprotocol/lib/Exponential.sol pragma solidity 0.5.16; /** * @title Exponential module for storing fixed-precision decimals * @author Compound * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places. * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is: * `Exp({mantissa: 5100000000000000000})`. */ contract Exponential is CarefulMath { uint constant expScale = 1e18; uint constant doubleScale = 1e36; uint constant halfExpScale = expScale/2; uint constant mantissaOne = expScale; struct Exp { uint mantissa; } struct Double { uint mantissa; } /** * @dev Creates an exponential from numerator and denominator values. * Note: Returns an error if (`num` * 10e18) > MAX_INT, * or if `denom` is zero. */ function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledNumerator) = mulUInt(num, expScale); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } (MathError err1, uint rational) = divUInt(scaledNumerator, denom); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: rational})); } /** * @dev Multiply an Exp by a scalar, returning a new Exp. */ function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) { (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa})); } /** * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer. */ function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) { (MathError err, Exp memory product) = mulScalar(a, scalar); if (err != MathError.NO_ERROR) { return (err, 0); } return (MathError.NO_ERROR, truncate(product)); } /** * @dev Divide a scalar by an Exp, returning a new Exp. */ function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) { /* We are doing this as: getExp(mulUInt(expScale, scalar), divisor.mantissa) How it works: Exp = a / b; Scalar = s; `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale` */ (MathError err0, uint numerator) = mulUInt(expScale, scalar); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } return getExp(numerator, divisor.mantissa); } /** * @dev Multiplies two exponentials, returning a new exponential. */ function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa); if (err0 != MathError.NO_ERROR) { return (err0, Exp({mantissa: 0})); } // We add half the scale before dividing so that we get rounding instead of truncation. // See "Listing 6" and text above it at https://accu.org/index.php/journals/1717 // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18. (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct); if (err1 != MathError.NO_ERROR) { return (err1, Exp({mantissa: 0})); } (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale); // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero. assert(err2 == MathError.NO_ERROR); return (MathError.NO_ERROR, Exp({mantissa: product})); } /** * @dev Multiplies two exponentials given their mantissas, returning a new exponential. */ function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) { return mulExp(Exp({mantissa: a}), Exp({mantissa: b})); } /** * @dev Divides two exponentials, returning a new exponential. * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b, * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa) */ function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) { return getExp(a.mantissa, b.mantissa); } /** * @dev Truncates the given exp to a whole number value. * For example, truncate(Exp{mantissa: 15 * expScale}) = 15 */ function truncate(Exp memory exp) pure internal returns (uint) { // Note: We are not using careful math here as we're performing a division that cannot fail return exp.mantissa / expScale; } function safe224(uint n, string memory errorMessage) pure internal returns (uint224) { require(n < 2**224, errorMessage); return uint224(n); } function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: add_(a.mantissa, b.mantissa)}); } function add_(uint a, uint b) pure internal returns (uint) { return add_(a, b, "addition overflow"); } function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: sub_(a.mantissa, b.mantissa)}); } function sub_(uint a, uint b) pure internal returns (uint) { return sub_(a, b, "subtraction underflow"); } function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b <= a, errorMessage); return a - b; } function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale}); } function mul_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Exp memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / expScale; } function mul_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale}); } function mul_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: mul_(a.mantissa, b)}); } function mul_(uint a, Double memory b) pure internal returns (uint) { return mul_(a, b.mantissa) / doubleScale; } function mul_(uint a, uint b) pure internal returns (uint) { return mul_(a, b, "multiplication overflow"); } function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { if (a == 0 || b == 0) { return 0; } uint c = a * b; require(c / a == b, errorMessage); return c; } function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) { return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)}); } function div_(Exp memory a, uint b) pure internal returns (Exp memory) { return Exp({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Exp memory b) pure internal returns (uint) { return div_(mul_(a, expScale), b.mantissa); } function div_(Double memory a, Double memory b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)}); } function div_(Double memory a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(a.mantissa, b)}); } function div_(uint a, Double memory b) pure internal returns (uint) { return div_(mul_(a, doubleScale), b.mantissa); } function div_(uint a, uint b) pure internal returns (uint) { return div_(a, b, "divide by zero"); } function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) { require(b > 0, errorMessage); return a / b; } function fraction(uint a, uint b) pure internal returns (Double memory) { return Double({mantissa: div_(mul_(a, doubleScale), b)}); } // New functions added by BProtocol // ================================= function mulTrucate(uint a, uint b) internal pure returns (uint) { return mul_(a, b) / expScale; } } // File @openzeppelin/contracts/math/[email protected] pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/bprotocol/btoken/AbsBToken.sol pragma solidity 0.5.16; // Interface // Libs /** * @title AbsBToken is BProtocol token contract which represents the Compound's CToken */ contract AbsBToken is Exponential { using SafeERC20 for IERC20; // BProtocol Registry contract IRegistry public registry; // Compound's CToken this BToken contract is tied to address public cToken; modifier onlyDelegatee(address _avatar) { // `msg.sender` is delegatee require(registry.delegate(_avatar, msg.sender), "BToken: delegatee-not-authorized"); _; } constructor(address _registry, address _cToken) internal { registry = IRegistry(_registry); cToken = _cToken; } function _myAvatar() internal returns (address) { return registry.getAvatar(msg.sender); } // CEther / CErc20 // =============== function borrowBalanceCurrent(address account) external returns (uint256) { address _avatar = registry.getAvatar(account); return IAvatar(_avatar).borrowBalanceCurrent(cToken); } // redeem() function redeem(uint256 redeemTokens) external returns (uint256) { return _redeem(_myAvatar(), redeemTokens); } function redeemOnAvatar(address _avatar, uint256 redeemTokens) external onlyDelegatee(_avatar) returns (uint256) { return _redeem(_avatar, redeemTokens); } function _redeem(address _avatar, uint256 redeemTokens) internal returns (uint256) { uint256 result = IAvatar(_avatar).redeem(cToken, redeemTokens, msg.sender); require(result == 0, "BToken: redeem-failed"); return result; } // redeemUnderlying() function redeemUnderlying(uint256 redeemAmount) external returns (uint256) { return _redeemUnderlying(_myAvatar(), redeemAmount); } function redeemUnderlyingOnAvatar(address _avatar, uint256 redeemAmount) external onlyDelegatee(_avatar) returns (uint256) { return _redeemUnderlying(_avatar, redeemAmount); } function _redeemUnderlying(address _avatar, uint256 redeemAmount) internal returns (uint256) { uint256 result = IAvatar(_avatar).redeemUnderlying(cToken, redeemAmount, msg.sender); require(result == 0, "BToken: redeemUnderlying-failed"); return result; } // borrow() function borrow(uint256 borrowAmount) external returns (uint256) { return _borrow(_myAvatar(), borrowAmount); } function borrowOnAvatar(address _avatar, uint256 borrowAmount) external onlyDelegatee(_avatar) returns (uint256) { return _borrow(_avatar, borrowAmount); } function _borrow(address _avatar, uint256 borrowAmount) internal returns (uint256) { uint256 result = IAvatar(_avatar).borrow(cToken, borrowAmount, msg.sender); require(result == 0, "BToken: borrow-failed"); return result; } // other functions function exchangeRateCurrent() public returns (uint256) { return ICToken(cToken).exchangeRateCurrent(); } function exchangeRateStored() public view returns (uint) { return ICToken(cToken).exchangeRateStored(); } // IERC20 // ======= // transfer() function transfer(address dst, uint256 amount) external returns (bool) { return _transfer(_myAvatar(), dst, amount); } function transferOnAvatar(address _avatar, address dst, uint256 amount) external onlyDelegatee(_avatar) returns (bool) { return _transfer(_avatar, dst, amount); } function _transfer(address _avatar, address dst, uint256 amount) internal returns (bool) { bool result = IAvatar(_avatar).transfer(cToken, dst, amount); require(result, "BToken: transfer-failed"); return result; } // transferFrom() function transferFrom(address src, address dst, uint256 amount) external returns (bool) { return _transferFrom(_myAvatar(), src, dst, amount); } function transferFromOnAvatar(address _avatar, address src, address dst, uint256 amount) external onlyDelegatee(_avatar) returns (bool) { return _transferFrom(_avatar, src, dst, amount); } function _transferFrom(address _avatar, address src, address dst, uint256 amount) internal returns (bool) { bool result = IAvatar(_avatar).transferFrom(cToken, src, dst, amount); require(result, "BToken: transferFrom-failed"); return result; } // approve() function approve(address spender, uint256 amount) public returns (bool) { return IAvatar(_myAvatar()).approve(cToken, spender, amount); } function approveOnAvatar(address _avatar, address spender, uint256 amount) public onlyDelegatee(_avatar) returns (bool) { return IAvatar(_avatar).approve(cToken, spender, amount); } function allowance(address owner, address spender) public view returns (uint256) { address spenderAvatar = registry.avatarOf(spender); if(spenderAvatar == address(0)) return 0; return ICToken(cToken).allowance(registry.avatarOf(owner), spenderAvatar); } function balanceOf(address owner) public view returns (uint256) { address avatar = registry.avatarOf(owner); if(avatar == address(0)) return 0; return ICToken(cToken).balanceOf(avatar); } function balanceOfUnderlying(address owner) external returns (uint) { address avatar = registry.avatarOf(owner); if(avatar == address(0)) return 0; return ICToken(cToken).balanceOfUnderlying(avatar); } function name() public view returns (string memory) { return ICToken(cToken).name(); } function symbol() public view returns (string memory) { return ICToken(cToken).symbol(); } function decimals() public view returns (uint8) { return ICToken(cToken).decimals(); } function totalSupply() public view returns (uint256) { return ICToken(cToken).totalSupply(); } } // File contracts/bprotocol/btoken/BErc20.sol pragma solidity 0.5.16; contract BErc20 is AbsBToken { IERC20 public underlying; constructor( address _registry, address _cToken ) public AbsBToken(_registry, _cToken) { underlying = ICToken(cToken).underlying(); } // mint() function mint(uint256 mintAmount) external returns (uint256) { return _mint(_myAvatar(), mintAmount); } function mintOnAvatar(address _avatar, uint256 mintAmount) external onlyDelegatee(_avatar) returns (uint256) { return _mint(_avatar, mintAmount); } function _mint(address _avatar, uint256 mintAmount) internal returns (uint256) { underlying.safeTransferFrom(msg.sender, _avatar, mintAmount); uint256 result = IAvatarCErc20(_avatar).mint(cToken, mintAmount); require(result == 0, "BErc20: mint-failed"); return result; } // repayBorrow() function repayBorrow(uint256 repayAmount) external returns (uint256) { return _repayBorrow(_myAvatar(), repayAmount); } function repayBorrowOnAvatar(address _avatar, uint256 repayAmount) external onlyDelegatee(_avatar) returns (uint256) { return _repayBorrow(_avatar, repayAmount); } function _repayBorrow(address _avatar, uint256 repayAmount) internal returns (uint256) { uint256 actualRepayAmount = repayAmount; if(repayAmount == uint256(-1)) { actualRepayAmount = IAvatarCErc20(_avatar).borrowBalanceCurrent(cToken); } underlying.safeTransferFrom(msg.sender, _avatar, actualRepayAmount); uint256 result = IAvatarCErc20(_avatar).repayBorrow(cToken, actualRepayAmount); require(result == 0, "BErc20: repayBorrow-failed"); return result; } } // File contracts/bprotocol/btoken/BEther.sol pragma solidity 0.5.16; contract BEther is AbsBToken { constructor( address _registry, address _cToken ) public AbsBToken(_registry, _cToken) {} function _myAvatarCEther() internal returns (IAvatarCEther) { return IAvatarCEther(address(_myAvatar())); } // mint() function mint() external payable { // CEther calls requireNoError() to ensure no failures _myAvatarCEther().mint.value(msg.value)(); } function mintOnAvatar(address _avatar) external onlyDelegatee(_avatar) payable { // CEther calls requireNoError() to ensure no failures IAvatarCEther(_avatar).mint.value(msg.value)(); } // repayBorrow() function repayBorrow() external payable { // CEther calls requireNoError() to ensure no failures _myAvatarCEther().repayBorrow.value(msg.value)(); } function repayBorrowOnAvatar(address _avatar) external onlyDelegatee(_avatar) payable { // CEther calls requireNoError() to ensure no failures IAvatarCEther(_avatar).repayBorrow.value(msg.value)(); } } // File contracts/bprotocol/interfaces/IComptroller.sol pragma solidity 0.5.16; interface IComptroller { // ComptrollerLensInterface.sol // ============================= function markets(address) external view returns (bool, uint); function oracle() external view returns (address); function getAccountLiquidity(address) external view returns (uint, uint, uint); function getAssetsIn(address) external view returns (address[] memory); function compAccrued(address) external view returns (uint); // Claim all the COMP accrued by holder in all markets function claimComp(address holder) external; // Claim all the COMP accrued by holder in specific markets function claimComp(address holder, address[] calldata cTokens) external; function claimComp(address[] calldata holders, address[] calldata cTokens, bool borrowers, bool suppliers) external; // Public storage defined in Comptroller contract // =============================================== function checkMembership(address account, address cToken) external view returns (bool); function closeFactorMantissa() external returns (uint256); function liquidationIncentiveMantissa() external returns (uint256); // Public/external functions defined in Comptroller contract // ========================================================== function enterMarkets(address[] calldata cTokens) external returns (uint[] memory); function exitMarket(address cToken) external returns (uint); function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint); function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint); function getAllMarkets() external view returns (address[] memory); function liquidateCalculateSeizeTokens( address cTokenBorrowed, address cTokenCollateral, uint actualRepayAmount) external view returns (uint, uint); function compBorrowState(address cToken) external returns (uint224, uint32); function compSupplyState(address cToken) external returns (uint224, uint32); } // File contracts/bprotocol/BComptroller.sol pragma solidity 0.5.16; contract BComptroller { IComptroller public comptroller; IRegistry public registry; // CToken => BToken mapping(address => address) public c2b; // BToken => CToken mapping(address => address) public b2c; event NewBToken(address indexed cToken, address bToken); modifier onlyDelegatee(IAvatar _avatar) { // `msg.sender` is delegatee require(registry.delegate(address(_avatar), msg.sender), "BComptroller: delegatee-not-authorized"); _; } constructor(address _comptroller) public { comptroller = IComptroller(_comptroller); } function setRegistry(address _registry) public { require(address(registry) == address(0), "BComptroller: registry-already-set"); registry = IRegistry(_registry); } function newBToken(address cToken) external returns (address) { require(c2b[cToken] == address(0), "BComptroller: BToken-already-exists"); (bool isListed,) = comptroller.markets(cToken); require(isListed, "BComptroller: cToken-not-listed-on-compound"); bool is_cETH = cToken == registry.cEther(); address bToken; if(is_cETH) { bToken = address(new BEther(address(registry), cToken)); } else { bToken = address(new BErc20(address(registry), cToken)); } c2b[cToken] = bToken; b2c[bToken] = cToken; emit NewBToken(cToken, bToken); return bToken; } function isBToken(address bToken) public view returns (bool) { return b2c[bToken] != address(0); } function enterMarket(address bToken) external returns (uint256) { IAvatar avatar = IAvatar(registry.getAvatar(msg.sender)); return _enterMarket(avatar, bToken); } function enterMarketOnAvatar(IAvatar avatar, address bToken) external onlyDelegatee(avatar) returns (uint256) { return _enterMarket(avatar, bToken); } function _enterMarket(IAvatar avatar, address bToken) internal returns (uint256) { require(b2c[bToken] != address(0), "BComptroller: CToken-not-exist-for-bToken"); return avatar.enterMarket(bToken); } function enterMarkets(address[] calldata bTokens) external returns (uint256[] memory) { IAvatar avatar = IAvatar(registry.getAvatar(msg.sender)); return _enterMarkets(avatar, bTokens); } function enterMarketsOnAvatar(IAvatar avatar, address[] calldata bTokens) external onlyDelegatee(avatar) returns (uint256[] memory) { return _enterMarkets(avatar, bTokens); } function _enterMarkets(IAvatar avatar, address[] memory bTokens) internal returns (uint256[] memory) { for(uint i = 0; i < bTokens.length; i++) { require(b2c[bTokens[i]] != address(0), "BComptroller: CToken-not-exist-for-bToken"); } return avatar.enterMarkets(bTokens); } function exitMarket(address bToken) external returns (uint256) { IAvatar avatar = IAvatar(registry.getAvatar(msg.sender)); return avatar.exitMarket(bToken); } function exitMarketOnAvatar(IAvatar avatar, address bToken) external onlyDelegatee(avatar) returns (uint256) { return avatar.exitMarket(bToken); } function getAccountLiquidity(address account) external view returns (uint err, uint liquidity, uint shortFall) { IAvatar avatar = IAvatar(registry.avatarOf(account)); if(avatar == IAvatar(0)) return (0, 0, 0); return avatar.getAccountLiquidity(); } function claimComp(address holder) external { IAvatar avatar = IAvatar(registry.getAvatar(holder)); avatar.claimComp(); } function claimComp(address holder, address[] calldata bTokens) external { IAvatar avatar = IAvatar(registry.getAvatar(holder)); avatar.claimComp(bTokens); } function claimComp( address[] calldata holders, address[] calldata bTokens, bool borrowers, bool suppliers ) external { for(uint256 i = 0; i < holders.length; i++) { IAvatar avatar = IAvatar(registry.getAvatar(holders[i])); avatar.claimComp(bTokens, borrowers, suppliers); } } function oracle() external view returns (address) { return comptroller.oracle(); } function getAllMarkets() external view returns (address[] memory) { return comptroller.getAllMarkets(); } } // File contracts/bprotocol/interfaces/IBToken.sol pragma solidity 0.5.16; interface IBToken { function cToken() external view returns (address); function borrowBalanceCurrent(address account) external returns (uint); function balanceOfUnderlying(address owner) external returns (uint); } // File contracts/bprotocol/interfaces/IUniswapAnchoredView.sol pragma solidity 0.5.16; interface IUniswapAnchoredView { function postPrices(bytes[] calldata messages, bytes[] calldata signatures, string[] calldata symbols) external; function price(string calldata symbol) external view returns (uint); function getUnderlyingPrice(address cToken) external view returns (uint); } // File contracts/bprotocol/interfaces/IBComptroller.sol pragma solidity 0.5.16; interface IBComptroller { function isCToken(address cToken) external view returns (bool); function isBToken(address bToken) external view returns (bool); function c2b(address cToken) external view returns (address); function b2c(address bToken) external view returns (address); } // File contracts/bprotocol/Pool.sol pragma solidity 0.5.16; /** * @title Pool contract to manage the pool of member's fund */ contract Pool is Exponential, Ownable { using SafeERC20 for IERC20; address internal constant ETH_ADDR = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; IComptroller public comptroller; IBComptroller public bComptroller; IRegistry public registry; address public jar; address public cEther; address[] public members; // member share profit params uint public shareNumerator; uint public shareDenominator; // member => underlying => amount mapping(address => mapping(address => uint)) public balance; // member => underlying => amount mapping(address => mapping(address => uint)) public topupBalance; // avatar => TopupInfo mapping(address => TopupInfo) public topped; // bToken => threshold mapping(address => uint) public minSharingThreshold; // debt above this size will be shared uint public minTopupBps = 250; // 2.5% uint public holdingTime = 5 hours; // after 5 hours, someone else can topup instead uint public selectionDuration = 60 minutes; // member selection duration for round robin, default 60 mins struct MemberTopupInfo { uint expire; // after expire time, other member can topup. relevant only if small uint amountTopped; // amount of underlying tokens toppedUp uint amountLiquidated; // how much was already liquidated } struct TopupInfo { mapping(address => MemberTopupInfo) memberInfo; // info per member uint debtToLiquidatePerMember; // total debt avail to liquidate address cToken; // underlying debt cToken address } function getMemberTopupInfo( address user, address member ) public view returns ( uint expire, uint amountTopped, uint amountLiquidated ) { address avatar = registry.avatarOf(user); MemberTopupInfo memory memberInfo = topped[avatar].memberInfo[member]; expire = memberInfo.expire; amountTopped = memberInfo.amountTopped; amountLiquidated = memberInfo.amountLiquidated; } function getDebtTopupInfo(address user, address bTokenDebt) public /* view */ returns(uint minTopup, uint maxTopup, bool isSmall) { uint debt = IBToken(bTokenDebt).borrowBalanceCurrent(user); minTopup = mul_(debt, minTopupBps) / 10000; maxTopup = debt / members.length; isSmall = debt < minSharingThreshold[bTokenDebt]; } function untop(address user, uint underlyingAmount) public onlyMember { _untop(msg.sender, user, underlyingAmount); } function _untopOnBehalf(address member, address user, uint underlyingAmount) internal { _untop(member, user, underlyingAmount); } function _untop(address member, address user, uint underlyingAmount) internal { require(underlyingAmount > 0, "Pool: amount-is-zero"); address avatar = registry.avatarOf(user); TopupInfo storage info = topped[avatar]; address bToken = bComptroller.c2b(info.cToken); MemberTopupInfo storage memberInfo = info.memberInfo[member]; // cannot untop more than topped up amount require(memberInfo.amountTopped >= underlyingAmount, "Pool: amount-too-big"); require(ICushion(avatar).remainingLiquidationAmount() == 0, "Pool: cannot-untop-in-liquidation"); (uint minTopup,,) = getDebtTopupInfo(user, bToken); require( memberInfo.amountTopped == underlyingAmount || sub_(memberInfo.amountTopped, underlyingAmount) >= minTopup, "Pool: invalid-amount" ); if(ICushion(avatar).toppedUpAmount() > 0) ICushion(avatar).untop(underlyingAmount); address underlying = _getUnderlying(info.cToken); balance[member][underlying] = add_(balance[member][underlying], underlyingAmount); topupBalance[member][underlying] = sub_(topupBalance[member][underlying], underlyingAmount); memberInfo.amountTopped = 0; memberInfo.expire = 0; } function smallTopupWinner(address avatar) public view returns(address) { uint chosen = uint(keccak256(abi.encodePacked(avatar, now / selectionDuration))) % members.length; return members[chosen]; } function topup(address user, address bToken, uint amount, bool resetApprove) external onlyMember { address avatar = registry.avatarOf(user); address cToken = bComptroller.b2c(bToken); (uint minTopup, uint maxTopup, bool small) = getDebtTopupInfo(user, bToken); address underlying = _getUnderlying(cToken); uint memberBalance = balance[msg.sender][underlying]; require(memberBalance >= amount, "Pool: topup-insufficient-balance"); require(ICushion(avatar).remainingLiquidationAmount() == 0, "Pool: cannot-topup-in-liquidation"); TopupInfo storage info = topped[avatar]; _untopOnMembers(user, avatar, cToken, small); MemberTopupInfo storage memberInfo = info.memberInfo[msg.sender]; require(add_(amount, memberInfo.amountTopped) >= minTopup, "Pool: topup-amount-small"); require(add_(amount, memberInfo.amountTopped) <= maxTopup, "Pool: topup-amount-big"); // For first topup skip this check as `expire = 0` // From next topup, check for turn of msg.sender (new member) if(small && memberInfo.expire != 0 && memberInfo.expire <= now) { require(smallTopupWinner(avatar) == msg.sender, "Pool: topup-not-your-turn"); } // topup is valid balance[msg.sender][underlying] = sub_(memberBalance, amount); topupBalance[msg.sender][underlying] = add_(topupBalance[msg.sender][underlying], amount); if(small && memberInfo.expire <= now) { memberInfo.expire = add_(now, holdingTime); } memberInfo.amountTopped = add_(memberInfo.amountTopped, amount); // in all the below, as sload will soon cost 2k gas, we use sstore without // checking if the value really changed memberInfo.amountLiquidated = 0; info.debtToLiquidatePerMember = 0; info.cToken = cToken; if(_isCEther(cToken)) { ICushionCEther(avatar).topup.value(amount)(); } else { if(resetApprove) IERC20(underlying).safeApprove(avatar, 0); IERC20(underlying).safeApprove(avatar, amount); ICushionCErc20(avatar).topup(cToken, amount); } } // created this function to avoid stack too deep error function _untopOnMembers(address user, address avatar, address cToken, bool small) internal { uint realCushion = ICushion(avatar).toppedUpAmount(); TopupInfo memory info = topped[avatar]; for(uint i = 0 ; i < members.length ; i++) { address member = members[i]; MemberTopupInfo memory memberInfo = topped[avatar].memberInfo[member]; uint amount = memberInfo.amountTopped; if(amount > 0) { if(realCushion == 0) { _untopOnBehalf(member, user, amount); // now it is 0 topup continue; } require(info.cToken == cToken, "Pool: cToken-miss-match"); if(member == msg.sender) continue; // skil below check for me(member) if(! small) continue; // if big loan, share with it with other members // me(member) checking for other member's expire require(memberInfo.expire < now, "Pool: other-member-topped"); _untopOnBehalf(member, user, amount); } } } event MemberDeposit(address indexed member, address underlying, uint amount); event MemberWithdraw(address indexed member, address underlying, uint amount); event MemberToppedUp(address indexed member, address avatar, address cToken, uint amount); event MemberUntopped(address indexed member, address avatar); event MemberBite(address indexed member, address avatar, address cTokenDebt, address cTokenCollateral, uint underlyingAmtToLiquidate); event ProfitParamsChanged(uint numerator, uint denominator); event MembersSet(address[] members); event SelectionDurationChanged(uint oldDuration, uint newDuration); event MinTopupBpsChanged(uint oldMinTopupBps, uint newMinTopupBps); event HoldingTimeChanged(uint oldHoldingTime, uint newHoldingTime); event MinSharingThresholdChanged(address indexed bToken, uint oldThreshold, uint newThreshold); modifier onlyMember() { require(_isMember(msg.sender), "Pool: not-member"); _; } constructor(address _jar) public { jar = _jar; } // Added to avoid stack-too-deep-error // This also reduce the code size as modifier code is copied to function function _isMember(address member) internal view returns (bool isMember) { for(uint i = 0 ; i < members.length ; i++) { if(members[i] == member) { isMember = true; break; } } } function setRegistry(address _registry) external onlyOwner { require(address(registry) == address(0), "Pool: registry-already-set"); registry = IRegistry(_registry); comptroller = IComptroller(registry.comptroller()); bComptroller = IBComptroller(registry.bComptroller()); cEther = registry.cEther(); } function emergencyExecute(address target, bytes calldata data) external payable onlyOwner { (bool succ, bytes memory ret) = target.call.value(msg.value)(data); require(succ, string(ret)); } /** * @dev Fallback function to receive ETH from Avatar */ function() external payable {} function setMinTopupBps(uint newMinTopupBps) external onlyOwner { require(newMinTopupBps >= 0 && newMinTopupBps <= 10000, "Pool: incorrect-minTopupBps"); uint oldMinTopupBps = minTopupBps; minTopupBps = newMinTopupBps; emit MinTopupBpsChanged(oldMinTopupBps, newMinTopupBps); } function setHoldingTime(uint newHoldingTime) external onlyOwner { require(newHoldingTime > 0, "Pool: incorrect-holdingTime"); uint oldHoldingTime = holdingTime; holdingTime = newHoldingTime; emit HoldingTimeChanged(oldHoldingTime, newHoldingTime); } function setMinSharingThreshold(address bToken, uint newMinThreshold) external onlyOwner { require(newMinThreshold > 0, "Pool: incorrect-minThreshold"); require(bComptroller.isBToken(bToken), "Pool: not-a-BToken"); uint oldMinThreshold = minSharingThreshold[bToken]; minSharingThreshold[bToken] = newMinThreshold; emit MinSharingThresholdChanged(bToken, oldMinThreshold, newMinThreshold); } function setProfitParams(uint numerator, uint denominator) external onlyOwner { require(numerator < denominator, "Pool: invalid-profit-params"); shareNumerator = numerator; shareDenominator = denominator; emit ProfitParamsChanged(numerator, denominator); } function setSelectionDuration(uint newDuration) external onlyOwner { require(newDuration > 0, "Pool: selection-duration-is-zero"); uint oldDuration = selectionDuration; selectionDuration = newDuration; emit SelectionDurationChanged(oldDuration, newDuration); } function setMembers(address[] calldata newMembersList) external onlyOwner { members = newMembersList; emit MembersSet(newMembersList); } function deposit() external payable onlyMember { balance[msg.sender][ETH_ADDR] = add_(balance[msg.sender][ETH_ADDR], msg.value); emit MemberDeposit(msg.sender, ETH_ADDR, msg.value); } function deposit(address underlying, uint amount) external onlyMember { IERC20(underlying).safeTransferFrom(msg.sender, address(this), amount); balance[msg.sender][underlying] = add_(balance[msg.sender][underlying], amount); emit MemberDeposit(msg.sender, underlying, amount); } function withdraw(address underlying, uint amount) external { if(_isETH(underlying)) { balance[msg.sender][ETH_ADDR] = sub_(balance[msg.sender][ETH_ADDR], amount); msg.sender.transfer(amount); } else { balance[msg.sender][underlying] = sub_(balance[msg.sender][underlying], amount); IERC20(underlying).safeTransfer(msg.sender, amount); } emit MemberWithdraw(msg.sender, underlying, amount); } function liquidateBorrow( address borrower, address bTokenCollateral, address bTokenDebt, uint underlyingAmtToLiquidate ) public onlyMember { address cTokenCollateral = bComptroller.b2c(bTokenCollateral); address cTokenDebt = bComptroller.b2c(bTokenDebt); address avatar = registry.avatarOf(borrower); TopupInfo storage info = topped[avatar]; require(info.memberInfo[msg.sender].amountTopped > 0, "Pool: member-didnt-topup"); uint debtToLiquidatePerMember = info.debtToLiquidatePerMember; if(debtToLiquidatePerMember == 0) { uint numMembers = 0; for(uint i = 0 ; i < members.length ; i++) { if(info.memberInfo[members[i]].amountTopped > 0) { numMembers++; } } debtToLiquidatePerMember = ICushion(avatar).getMaxLiquidationAmount(cTokenDebt) / numMembers; info.debtToLiquidatePerMember = debtToLiquidatePerMember; } MemberTopupInfo memory memberInfo = info.memberInfo[msg.sender]; require(memberInfo.amountTopped > 0, "Pool: member-didnt-topup"); require( add_(memberInfo.amountLiquidated, underlyingAmtToLiquidate) <= debtToLiquidatePerMember, "Pool: amount-too-big" ); uint amtToDeductFromTopup = mul_(underlyingAmtToLiquidate, memberInfo.amountTopped) / ( sub_(debtToLiquidatePerMember, memberInfo.amountLiquidated) ); uint amtToRepayOnCompound = sub_(underlyingAmtToLiquidate, amtToDeductFromTopup); address debtUnderlying = _getUnderlying(cTokenDebt); require(balance[msg.sender][debtUnderlying] >= amtToRepayOnCompound, "Pool: low-member-balance"); if(! _isCEther(cTokenDebt)) { IERC20(debtUnderlying).safeApprove(avatar, amtToRepayOnCompound); } require( ICushion(avatar).liquidateBorrow.value(debtUnderlying == ETH_ADDR ? amtToRepayOnCompound : 0)(underlyingAmtToLiquidate, amtToDeductFromTopup, cTokenCollateral) == 0, "Pool: liquidateBorrow-failed" ); // substract payment from member balance balance[msg.sender][debtUnderlying] = sub_(balance[msg.sender][debtUnderlying], amtToRepayOnCompound); // share siezed cTokens with `member` and `jar` _shareLiquidationProceeds(cTokenCollateral, msg.sender); info.memberInfo[msg.sender].amountLiquidated = add_(memberInfo.amountLiquidated, underlyingAmtToLiquidate); info.memberInfo[msg.sender].amountTopped = sub_(memberInfo.amountTopped, amtToDeductFromTopup); topupBalance[msg.sender][debtUnderlying] = sub_(topupBalance[msg.sender][debtUnderlying], amtToDeductFromTopup); if(IAvatar(avatar).toppedUpAmount() == 0) { //info.debtToLiquidatePerMember = 0; // this indicates the liquidation ended delete topped[avatar]; // this will reset debtToLiquidatePerMember } emit MemberBite(msg.sender, avatar, cTokenDebt, cTokenCollateral, underlyingAmtToLiquidate); } function feedPricesAndLiquidate( IUniswapAnchoredView priceOracle, bytes[] calldata messages, bytes[] calldata signatures, string[] calldata symbols, address borrower, address bTokenCollateral, address bTokenDebt, uint underlyingAmtToLiquidate ) external { priceOracle.postPrices(messages, signatures, symbols); liquidateBorrow(borrower, bTokenCollateral, bTokenDebt, underlyingAmtToLiquidate); } function _shareLiquidationProceeds(address cTokenCollateral, address member) internal { uint seizedTokens = IERC20(cTokenCollateral).balanceOf(address(this)); uint memberShare = div_(mul_(seizedTokens, shareNumerator), shareDenominator); uint jarShare = sub_(seizedTokens, memberShare); IERC20(cTokenCollateral).safeTransfer(member, memberShare); IERC20(cTokenCollateral).safeTransfer(jar, jarShare); } function membersLength() external view returns (uint) { return members.length; } function getMembers() external view returns (address[] memory) { return members; } function _isETH(address addr) internal pure returns (bool) { return addr == ETH_ADDR; } function _isCEther(address addr) internal view returns (bool) { return addr == cEther; } function _getUnderlying(address cToken) internal view returns (address underlying) { if(_isCEther(cToken)) { underlying = ETH_ADDR; } else { underlying = address(ICErc20(cToken).underlying()); } } } // File contracts/bprotocol/info/LiquidatorInfo.sol pragma solidity ^0.5.16; contract LiquidatorInfo { address constant ETH = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); struct AvatarInfo { address user; uint totalDebt; // total debt according to price feed uint totalCollateral; // total collateral according to price feed uint weightedCollateral; // collateral x collateral factor. liquidation when weightedCollateral < totalDebt address[] debtTokens; uint[] debtAmounts; address[] collateralTokens; uint[] collateralAmounts; uint[] weightedCollateralAmounts; } struct CushionInfo { bool hasCushion; bool shouldTopup; bool shouldUntop; address cushionCurrentToken; uint cushionCurrentSize; uint cushionTokenTotalDebt; address[] cushionPossibleTokens; // which tokens could be used for cushion uint[] cushionMaxSizes; } struct LiquidationInfo { // only relevant if there is a cushion. we assume only one liquidator uint remainingLiquidationSize; uint memberLiquidationIncentive; } struct AccountInfo { AvatarInfo avatarInfo; CushionInfo cushionInfo; LiquidationInfo liquidationInfo; uint blockNumber; } struct CToken2BToken { address[] cTokens; address[] bTokens; } struct CurrentPrices { uint[] currPrices; address[] ctokens; } struct Info { AccountInfo[] accountInfo; CToken2BToken c2bMapping; CurrentPrices currPrices; uint numAvatars; } function getCTokenToBTokenList(BComptroller bComptroller) public view returns (CToken2BToken memory info) { info.cTokens = bComptroller.getAllMarkets(); info.bTokens = new address[](info.cTokens.length); for(uint i = 0; i < info.cTokens.length; i++) { info.bTokens[i] = bComptroller.c2b(info.cTokens[i]); } } function getCurrentPrices(IUniswapAnchoredView oracle, address[] memory ctokens) public view returns (CurrentPrices memory info) { info.currPrices = new uint[](ctokens.length); info.ctokens = ctokens; for(uint i = 0 ; i < ctokens.length ; i++) { info.currPrices[i] = oracle.getUnderlyingPrice(ctokens[i]); } } function isIn(address[] memory array, address elm) internal pure returns(bool) { for(uint i = 0 ; i < array.length ; i++) { if(elm == array[i]) return true; } return false; } function getAvatarInfo( Registry registry, BComptroller bComptroller, address[] memory cTokens, uint[] memory priceFeed, address avatar ) public returns(AvatarInfo memory info) { require(cTokens.length == priceFeed.length, "cTokens-priceFeed-missmatch"); uint numTokens = cTokens.length; address user = registry.ownerOf(avatar); info.user = user; info.debtTokens = new address[](numTokens); info.debtAmounts = new uint[](numTokens); info.collateralTokens = new address[](numTokens); info.collateralAmounts = new uint[](numTokens); info.weightedCollateralAmounts = new uint[](numTokens); IComptroller comptroller = bComptroller.comptroller(); address[] memory assetsIn = comptroller.getAssetsIn(avatar); for(uint i = 0 ; i < numTokens ; i++) { if(registry.cEther() == cTokens[i]) info.debtTokens[i] = ETH; else info.debtTokens[i] = address(CTokenInterface(cTokens[i]).underlying()); address bToken = bComptroller.c2b(cTokens[i]); info.debtAmounts[i] = IBToken(bToken).borrowBalanceCurrent(user); info.collateralTokens[i] = cTokens[i]; info.collateralAmounts[i] = IBToken(bToken).balanceOfUnderlying(user); if(! isIn(assetsIn, cTokens[i])) info.collateralAmounts[i] = 0; // set as 0 if not in market // CR = collateralRatio = collateralFactorMantissa (,uint CR) = comptroller.markets(cTokens[i]); info.weightedCollateralAmounts[i] = info.collateralAmounts[i] * CR / 1e18; info.totalDebt += info.debtAmounts[i] * priceFeed[i] / 1e18; info.totalCollateral += info.collateralAmounts[i] * priceFeed[i] / 1e18; info.weightedCollateral += info.weightedCollateralAmounts[i] * priceFeed[i] / 1e18; } } function cTokenToUnderlying(Registry registry, address cToken) internal view returns(address) { if(registry.cEther() == cToken) return ETH; else return address(CTokenInterface(cToken).underlying()); } function getCushionInfo( Registry registry, BComptroller bComptroller, Pool pool, address[] memory cTokens, uint[] memory priceFeed, uint debtAmount, uint weightedCollateral, address avatar, address me ) public returns(CushionInfo memory info) { address user = registry.ownerOf(avatar); info.hasCushion = ICushion(avatar).toppedUpAmount() > 0; (, uint amountTopped,) = pool.getMemberTopupInfo(user, me); if(debtAmount > weightedCollateral) { // assume there is only one member info.shouldTopup = true; } info.shouldUntop = (!info.hasCushion && amountTopped > 0); if(amountTopped > 0) { (,address toppedCToken) = pool.topped(avatar); info.cushionCurrentToken = cTokenToUnderlying(registry, toppedCToken); info.cushionCurrentSize = amountTopped; } info.cushionPossibleTokens = new address[](cTokens.length); info.cushionMaxSizes = new uint[](cTokens.length); for(uint i = 0 ; i < cTokens.length ; i++) { uint debt = IBToken(bComptroller.c2b(cTokens[i])).borrowBalanceCurrent(user); uint debtUsd = debt * priceFeed[i] / 1e18; if(amountTopped > 0 && info.hasCushion) { if(info.cushionCurrentToken != cTokenToUnderlying(registry, cTokens[i])) continue; info.cushionTokenTotalDebt = debt; debt -= amountTopped; } info.cushionPossibleTokens[i] = cTokenToUnderlying(registry, cTokens[i]); info.cushionMaxSizes[i] = debt; if(debtAmount > weightedCollateral) { // not enough debt to topup if(debtUsd < (debtAmount - weightedCollateral)) info.cushionMaxSizes[i] = 0; } } } function getLiquidationInfo(Pool pool, address avatar) public returns(LiquidationInfo memory info) { info.remainingLiquidationSize = ICushion(avatar).remainingLiquidationAmount(); Registry registry = Registry(address(pool.registry())); IComptroller comptroller = IComptroller(registry.comptroller()); info.memberLiquidationIncentive = comptroller.liquidationIncentiveMantissa() * pool.shareNumerator() / pool.shareDenominator(); } function getSingleAccountInfo( Pool pool, Registry registry, BComptroller bComptroller, address me, address avatar, address[] memory cTokens, uint[] memory priceFeed, IUniswapAnchoredView oracle ) public returns(AccountInfo memory info) { info.avatarInfo = getAvatarInfo(registry, bComptroller, cTokens, priceFeed, avatar); info.cushionInfo = getCushionInfo( registry, bComptroller, pool, cTokens, priceFeed, info.avatarInfo.totalDebt, info.avatarInfo.weightedCollateral, avatar, me ); info.liquidationInfo = getLiquidationInfo(pool, avatar); info.blockNumber = block.number; CurrentPrices memory realPrices = getCurrentPrices(oracle, cTokens); AvatarInfo memory realAvatarInfo = getAvatarInfo(registry, bComptroller, cTokens, realPrices.currPrices, avatar); if(realAvatarInfo.totalDebt > realAvatarInfo.weightedCollateral) { if(info.liquidationInfo.remainingLiquidationSize == 0) { info.liquidationInfo.remainingLiquidationSize = info.cushionInfo.cushionTokenTotalDebt / 2; } } } function getInfo( uint startAccount, uint endAccount, address me, Pool pool, address[] memory cTokens, uint[] memory priceFeed, string[] memory /* symbols */ // this is obselete now ) public returns(Info memory info) { info.accountInfo = new AccountInfo[](endAccount + 1 - startAccount); Registry registry = Registry(address(pool.registry())); BComptroller bComptroller = BComptroller(address(pool.bComptroller())); IUniswapAnchoredView oracle = IUniswapAnchoredView(IComptroller(BComptroller(bComptroller).comptroller()).oracle()); for(uint i = 0 ; i + startAccount <= endAccount ; i++) { uint accountNumber = i + startAccount; address avatar = registry.avatars(accountNumber); info.accountInfo[i] = getSingleAccountInfo(pool, registry, bComptroller, me, avatar, cTokens, priceFeed, oracle); } info.c2bMapping = getCTokenToBTokenList(bComptroller); info.currPrices = getCurrentPrices(oracle, cTokens); info.numAvatars = registry.avatarLength(); } function getNumAvatars(Pool pool) public view returns(uint) { Registry registry = Registry(address(pool.registry())); return registry.avatarLength(); } }
set as 0 if not in market CR = collateralRatio = collateralFactorMantissa
function getAvatarInfo( Registry registry, BComptroller bComptroller, address[] memory cTokens, uint[] memory priceFeed, address avatar ) public returns(AvatarInfo memory info) { require(cTokens.length == priceFeed.length, "cTokens-priceFeed-missmatch"); uint numTokens = cTokens.length; address user = registry.ownerOf(avatar); info.user = user; info.debtTokens = new address[](numTokens); info.debtAmounts = new uint[](numTokens); info.collateralTokens = new address[](numTokens); info.collateralAmounts = new uint[](numTokens); info.weightedCollateralAmounts = new uint[](numTokens); IComptroller comptroller = bComptroller.comptroller(); address[] memory assetsIn = comptroller.getAssetsIn(avatar); for(uint i = 0 ; i < numTokens ; i++) { if(registry.cEther() == cTokens[i]) info.debtTokens[i] = ETH; else info.debtTokens[i] = address(CTokenInterface(cTokens[i]).underlying()); address bToken = bComptroller.c2b(cTokens[i]); info.debtAmounts[i] = IBToken(bToken).borrowBalanceCurrent(user); info.collateralTokens[i] = cTokens[i]; info.collateralAmounts[i] = IBToken(bToken).balanceOfUnderlying(user); if(! isIn(assetsIn, cTokens[i])) info.collateralAmounts[i] = 0; (,uint CR) = comptroller.markets(cTokens[i]); info.weightedCollateralAmounts[i] = info.collateralAmounts[i] * CR / 1e18; info.totalDebt += info.debtAmounts[i] * priceFeed[i] / 1e18; info.totalCollateral += info.collateralAmounts[i] * priceFeed[i] / 1e18; info.weightedCollateral += info.weightedCollateralAmounts[i] * priceFeed[i] / 1e18; } }
7,827,232
// SPDX-License-Identifier: MIT pragma solidity ^0.8.2; pragma abicoder v2; import {CallForFundsStorage} from "./CallForFundsStorage.sol"; import {ISuperfluid} from "@superfluid-finance/ethereum-contracts/contracts/interfaces/superfluid/ISuperfluid.sol"; import {IConstantFlowAgreementV1} from "@superfluid-finance/ethereum-contracts/contracts/interfaces/agreements/IConstantFlowAgreementV1.sol"; import {ISETH} from "@superfluid-finance/ethereum-contracts/contracts/interfaces/tokens/ISETH.sol"; import {ERC20WithTokenInfo} from "@superfluid-finance/ethereum-contracts/contracts/interfaces/tokens/ERC20WithTokenInfo.sol"; import {ISuperToken} from "@superfluid-finance/ethereum-contracts/contracts/interfaces/superfluid/ISuperToken.sol"; interface ICallForFundsFactory { function proxies(address) external returns (bool); } interface ISuperfluidOverride { function realtimeBalanceOfNow(address account) external view returns ( int256 availableBalance, uint256 deposit, uint256 owedDeposit, uint256 timestamp ); } interface ICallForFundsLogic { function mintCrowdCommission( address[] calldata funders, uint256 id, bytes memory data ) external; function mintSmartArt( address to, address royaltyRecipient, uint256 royaltyValue, string memory uri ) external; } interface ICrowdCommission { function mintCrowdCommissions( address[] memory funders, uint256 id, bytes memory data ) external; } interface ISmartArt { function mint( address to, address royaltyRecipient, uint256 royaltyValue, string memory uri ) external; } contract CallForFundsLogic is CallForFundsStorage { address public immutable crowdCommission; address public immutable smartArt; address public factory; //======== EVENTS ========= event FundingStateChanged(FundingState indexed newFundingState); event ContributionReceivedETH(address indexed donator, uint256 amount); event CallMatched(uint256 indexed amountMatched); event WorkDelivered(string deliverableURI); event RefundCompleted( address[] indexed addresses, uint256[] indexed amounts ); //======== MODIFIERS ========= modifier onlyCreator() { require(msg.sender == creator); _; } modifier onlyLoudverse() { require(msg.sender == loudverseAdmin); _; } modifier onlyProxies() { bool isProxy = ICallForFundsFactory(factory).proxies(msg.sender); require(isProxy); _; } modifier requireState(FundingState fundingState_) { require(fundingState == fundingState_); _; } // Plain ETH transfers. receive() external payable { emit ContributionReceivedETH(msg.sender, msg.value); } // Can find ISuperToken, host and cfa addresses at https://docs.superfluid.finance/superfluid/protocol-developers/networks constructor(address crowdCommission_, address smartArt_) { crowdCommission = crowdCommission_; smartArt = smartArt_; } //======== CREATOR METHODS ========= function startStream() external payable onlyCreator requireState(FundingState.MATCHED) { address proxyAddress = address(this); uint256 proxyBalance = ERC20WithTokenInfo(_dai).balanceOf(proxyAddress); (bool success, ) = address(_daix).call{gas: gasleft()}( abi.encodeWithSignature("upgrade(uint256)", proxyBalance) ); require(success); uint256 daixBalance = ISuperToken(_daix).balanceOf(proxyAddress); int256 _daixBalance = int256(uint256(daixBalance)); int96 timelineInSeconds = int96(timelineInDays) * 86400; int96 daixBalanceInt96 = int96(_daixBalance); int96 flowRate = daixBalanceInt96 / timelineInSeconds; // Safe in 0.8.0 // Start stream ISuperfluid(_host).callAgreement( _cfa, abi.encodeWithSelector( IConstantFlowAgreementV1(_cfa).createFlow.selector, _daix, // daix or whatever token being streamed, if this doesn't work use ISuperToken type msg.sender, // plain address flowRate, // wei/sec int96 new bytes(0) // placeholder - always pass in bytes(0) ), "0x" //userData ); setFundingState(FundingState.STREAMING); } function deliver(string memory deliverableURI_, address slicerAddress) external onlyCreator requireState(FundingState.STREAMING) { deliverableURI = deliverableURI_; emit WorkDelivered(deliverableURI); ICallForFundsLogic(logicAddress).mintSmartArt( msg.sender, slicerAddress, 1000, deliverableURI_ ); setFundingState(FundingState.DELIVERED); } //======== PLATFORM METHODS ========= function setFactory(address factoryAddress) external onlyLoudverse { factory = factoryAddress; } function matchCallForFunds( address[] calldata funders, uint256 id, bytes memory data ) external payable onlyLoudverse requireState(FundingState.OPEN) { // method is payable, msg.value should be the match emit CallMatched(msg.value); // mint crowd-commissioned NFT ICallForFundsLogic(logicAddress).mintCrowdCommission(funders, id, data); setFundingState(FundingState.MATCHED); } function refund(address[] memory addresses, uint256[] memory amounts) external onlyLoudverse requireState(FundingState.OPEN) { // insecure // for now assumes Loudverse will supply correct amounts for refund for (uint256 i = 1; i < addresses.length; i++) { bool success = ERC20WithTokenInfo(_dai).transfer( addresses[i], amounts[i] ); require(success); } address proxyAddress = address(this); uint256 proxyBalance = ERC20WithTokenInfo(_dai).balanceOf(proxyAddress); require(proxyBalance == 0); emit RefundCompleted(addresses, amounts); setFundingState(FundingState.FAILED); } //======== PROXY METHODS ========= function mintCrowdCommission( address[] calldata funders, uint256 id, bytes memory data ) public onlyProxies { ICrowdCommission(crowdCommission).mintCrowdCommissions( funders, id, data ); } function mintSmartArt( address to, // this will be the Creator address address royaltyRecipient, // this will be the Slicer address uint256 royaltyValue, // this will be 10% so 1000 string memory uri ) public onlyProxies { ISmartArt(smartArt).mint(to, royaltyRecipient, royaltyValue, uri); } //======== PRIVATE ========= function setFundingState(FundingState fundingState_) private { fundingState = fundingState_; emit FundingStateChanged(fundingState_); } function _attemptETHTransfer(address to, uint256 value) private returns (bool) { // Here increase the gas limit a reasonable amount above the default, and try // to send ETH to the recipient. // NOTE: This might allow the recipient to attempt a limited reentrancy attack. // solhint-disable-next-line avoid-low-level-calls (bool success, ) = to.call{value: value, gas: 30000}(""); return success; } }
======== PRIVATE =========
function setFundingState(FundingState fundingState_) private { fundingState = fundingState_; emit FundingStateChanged(fundingState_); }
1,843,232
pragma solidity ^0.5.4; import "./AuctionityTreasurer_V1.sol"; import "../CommonContract/AuctionityLibrary_V1.sol"; import "../CommonContract/AuctionityChainId_V1.sol"; import "../CommonContract/SafeMath.sol"; contract AuctionityTreasurer_V2 is AuctionityTreasurer_V1 { event LogLockDepot_V2( address user, address tokenContractAddress, uint256 tokenId, uint256 amount, uint256 lockedFor ); event LogUnlockDepot_V2( address user, address tokenContractAddress, uint256 tokenId, uint256 amount, uint256 lockedFor ); event LogTransferDepot_V2( address from, address to, address tokenContractAddress, uint256 tokenId, uint256 amount, bytes data ); event LogTransferDepotLocked_V2( uint256 lockedFor, address from, address to, address tokenContractAddress, uint256 tokenId, uint256 amount, bool keepLock, bytes data ); event LogSetWithdrawalVoucher_V2( address withdrawalUser, bytes voucher ); /// @notice transfer ERC1155 /// @param _to address of receiver /// @param _tokenContractAddress address : ERC1155 smart contract /// @param _tokenId uint256 : tokenId of ERC1155 /// @param _amount uint256 function transferERC1155_V2( address _to, address _tokenContractAddress, uint256 _tokenId, uint256 _amount ) public { _transferDepot_V2( msg.sender, _to, _tokenContractAddress, _tokenId, _amount, "" ); emit LogTransferDepot_V2( msg.sender, _to, _tokenContractAddress, _tokenId, _amount, "" ); } /// @notice withdrawal ERC1155 /// @param _tokenContractAddress address : ERC1155 smart contract /// @param _tokenId uint256 : tokenId of ERC1155 /// @param _amount uint256 function withdrawalERC1155_V2( address _tokenContractAddress, uint256 _tokenId, uint256 _amount ) public { _withdrawal_V1(msg.sender, _tokenContractAddress, _tokenId, _amount); emit LogWithdrawal_V1(msg.sender, _tokenContractAddress, _tokenId, _amount); } function setWithdrawalVoucher_V2( address _withdrawalUser, bytes memory _withdrawalVoucher ) public delegatedSendIsOracle_V1 { require( withdrawals[_withdrawalUser].withdrawalVoucher[keccak256( _withdrawalVoucher )] == 0, "Withdrawal voucher already exist" ); uint16 _withdrawalVoucherIndex = uint16( withdrawals[_withdrawalUser].withdrawalVoucherList.push("0x0") - 1 ); withdrawals[_withdrawalUser].withdrawalVoucherList[_withdrawalVoucherIndex] = _withdrawalVoucher; withdrawals[_withdrawalUser].withdrawalVoucher[keccak256( _withdrawalVoucher )] = _withdrawalVoucherIndex; emit LogSetWithdrawalVoucher_V2( _withdrawalUser, _withdrawalVoucher ); } /// @notice internal Lock part of deposit to a called smart contract /// @param user address /// @param tokenContractAddress address : ERC1155 smart contract /// @param tokenId uint256 : tokenId of ERC1155 /// @param amount uint256 amount to lock /// @param lockedFor uint256 lockedId function _lockDeposit_V2( address user, address tokenContractAddress, uint256 tokenId, uint256 amount, uint256 lockedFor ) internal { if(amount <= 0){ bytes memory _revertData = abi.encodeWithSelector( bytes4(keccak256("ErrorLockDeposit_V2(string,address,address,uint256,uint256,uint256)")), "Amount must be greater than zero", user, tokenContractAddress, tokenId, amount, lockedFor ); assembly { let size := mload(_revertData) revert(add(_revertData,0x20), size) } } uint256 balanceOfUser = _getBalance_V1( user, tokenContractAddress, tokenId ); if(balanceOfUser < amount){ bytes memory _revertData = abi.encodeWithSelector( bytes4(keccak256("ErrorLockDeposit_V2(string,address,address,uint256,uint256,uint256,uint256)")), "Not enough amount to locked", user, tokenContractAddress, tokenId, amount, balanceOfUser, lockedFor ); assembly { let size := mload(_revertData) revert(add(_revertData,0x20), size) } } _addDepotLocked_V1( user, tokenContractAddress, tokenId, amount, lockedFor ); _subDepot_V1(user, tokenContractAddress, tokenId, amount); emit LogLockDepot_V2( user, tokenContractAddress, tokenId, amount, lockedFor ); } /// @notice internal Unlock part of deposit to a called smart contract /// @param user address /// @param tokenContractAddress address : ERC1155 smart contract /// @param tokenId uint256 : tokenId of ERC1155 /// @param amount uint256 amount to lock /// @param lockedFor uint256 lockedId function _unlockDeposit_V2( address user, address tokenContractAddress, uint256 tokenId, uint256 amount, uint256 lockedFor ) internal{ if(amount <= 0){ // Generate custom revert data bytes memory _revertData = abi.encodeWithSelector( bytes4(keccak256("ErrorUnLockDeposit_V2(string,address,address,uint256,uint256,uint256)")), "Amount must be greater than zero", user, tokenContractAddress, tokenId, amount, lockedFor ); assembly { let size := mload(_revertData) revert(add(_revertData,0x20), size) } } uint256 balanceOfUser = _getBalanceLocked_V1( user, tokenContractAddress, tokenId, lockedFor ); if(balanceOfUser < amount){ // Generate custom revert data bytes memory _revertData = abi.encodeWithSelector( bytes4(keccak256("ErrorUnLockDeposit_V2(string,address,address,uint256,uint256,uint256,uint256)")), "Not enouth amount locked", user, tokenContractAddress, tokenId, amount, balanceOfUser, lockedFor ); assembly { let size := mload(_revertData) revert(add(_revertData,0x20), size) } } // remove from locked storage and add to available storage _subDepotLocked_V1( user, tokenContractAddress, tokenId, amount, lockedFor ); _addDepot_V1(user, tokenContractAddress, tokenId, amount); emit LogUnlockDepot_V2( user, tokenContractAddress, tokenId, amount, lockedFor ); } /// @notice internal transfer depot locked /// @param lockedFor uin256 identity of locked requested /// @param from address of owner /// @param to address of receiver /// @param tokenContractAddress address of token contract /// @param tokenId uint256 id of token /// @param amount uint256 number of token /// @param keepLock bool , true if the transfer want to keep tocken locked /// @param data bytes additional data for transfer function _transferDepotLocked_V2( uint256 lockedFor, address from, address to, address tokenContractAddress, uint256 tokenId, uint256 amount, bool keepLock, bytes memory data ) internal { if(amount <= 0){ // Generate custom revert data bytes memory _revertData = abi.encodeWithSelector( bytes4(keccak256("ErrorTransferDepotLocked_V2(string,uint256,address,address,address,uint256,uint256,bool,bytes)")), "Amount must be greater than zero", lockedFor, from, to, tokenContractAddress, tokenId, amount, keepLock, data ); assembly { let size := mload(_revertData) revert(add(_revertData,0x20), size) } } uint256 balanceOfUser = _getBalanceLocked_V1( from, tokenContractAddress, tokenId, lockedFor ); if(balanceOfUser < amount) { // Generate custom revert data bytes memory _revertData = abi.encodeWithSelector( bytes4(keccak256("ErrorTransferDepotLocked_V2(string,uint256,address,address,address,uint256,uint256,uint256,bool,bytes)")), "Amount too low", lockedFor, from, to, tokenContractAddress, tokenId, amount, balanceOfUser, keepLock, data ); assembly { let size := mload(_revertData) revert(add(_revertData,0x20), size) } } // remove from locked storage and add to available storage _subDepotLocked_V1( from, tokenContractAddress, tokenId, amount, lockedFor ); _addDepot_V1(to, tokenContractAddress, tokenId, amount); if(keepLock) { _lockDeposit_V2(to, tokenContractAddress, tokenId, amount, lockedFor); } } /// @notice internal transfer depot /// @param from address of owner /// @param to address of receiver /// @param tokenContractAddress address of token contract /// @param tokenId uint256 id of token /// @param amount uint256 number of token /// @param data bytes additional data for transfer function _transferDepot_V2( address from, address to, address tokenContractAddress, uint256 tokenId, uint256 amount, bytes memory data ) internal { if(amount <= 0){ // Generate custom revert data bytes memory _revertData = abi.encodeWithSelector( bytes4(keccak256("ErrorTransferDepot_V2(string,address,address,address,uint256,uint256,bytes)")), "Amount must be greater than zero", from, to, tokenContractAddress, tokenId, amount, data ); assembly { let size := mload(_revertData) revert(add(_revertData,0x20), size) } } uint256 balanceOfUser = _getBalance_V1( from, tokenContractAddress, tokenId ); if( balanceOfUser < amount ) { // Generate custom revert data bytes memory _revertData = abi.encodeWithSelector( bytes4(keccak256("ErrorTransferDepot_V2(string,address,address,address,uint256,uint256,uint256,bytes)")), "Amount too low", from, to, tokenContractAddress, tokenId, amount, balanceOfUser, data ); assembly { let size := mload(_revertData) revert(add(_revertData,0x20), size) } } // remove from locked storage and add to available storage _subDepot_V1( from, tokenContractAddress, tokenId, amount ); _addDepot_V1(to, tokenContractAddress, tokenId, amount); } /// @notice public Lock part of deposit to a called smart contract, for internal use in same proxy /// @param user address /// @param tokenContractAddress address : ERC1155 smart contract /// @param tokenId uint256 : tokenId of ERC1155 /// @param amount uint256 amount to lock /// @param lockedFor uint256 lockedId function internalLockDeposit_V2( address user, address tokenContractAddress, uint256 tokenId, uint256 amount, uint256 lockedFor ) public { _lockDeposit_V2(user, tokenContractAddress, tokenId, amount, lockedFor); } /// @notice public Unlock part of deposit to a called smart contract, for internal use in same proxy /// @param user address /// @param tokenContractAddress address : ERC1155 smart contract /// @param tokenId uint256 : tokenId of ERC1155 /// @param amount uint256 amount to lock /// @param lockedFor uint256 lockedId function internalUnLockDeposit_V2( address user, address tokenContractAddress, uint256 tokenId, uint256 amount, uint256 lockedFor ) public { _unlockDeposit_V2(user, tokenContractAddress, tokenId, amount, lockedFor); } /// @notice public transfer depot locked, for internal use in same proxy /// @param lockedFor uin256 identity of locked requested /// @param from address of owner /// @param to address of receiver /// @param tokenContractAddress address of token contract /// @param tokenId uint256 id of token /// @param amount uint256 number of token /// @param keepLock bool , true if the transfer want to keep tocken locked /// @param data bytes additional data for transfer function internalTransferDepotLocked_V2( uint256 lockedFor, address from, address to, address tokenContractAddress, uint256 tokenId, uint256 amount, bool keepLock, bytes memory data ) public { _transferDepotLocked_V2( lockedFor, from, to, tokenContractAddress, tokenId, amount, keepLock, data ); emit LogTransferDepotLocked_V2( lockedFor, from, to, tokenContractAddress, tokenId, amount, keepLock, data ); } /// @notice public transfer depot, for internal use in same proxy /// @param from address of owner /// @param to address of receiver /// @param tokenContractAddress address of token contract /// @param tokenId uint256 id of token /// @param amount uint256 number of token /// @param data bytes additional data for transfer function internalTransferDepot_V2( address from, address to, address tokenContractAddress, uint256 tokenId, uint256 amount, bytes memory data ) public { _transferDepot_V2( from, to, tokenContractAddress, tokenId, amount, data ); emit LogTransferDepot_V2( from, to, tokenContractAddress, tokenId, amount, data ); } /// @notice oracle can manually force token unlock /// @param user address /// @param tokenContractAddress address : ERC1155 smart contract /// @param tokenId uint256 : tokenId of ERC1155 /// @param amount uint256 amount to lock /// @param lockedFor uint256 lockedId function oracleUnlock_V2( address user, address tokenContractAddress, uint256 tokenId, uint256 amount, uint256 lockedFor ) public delegatedSendIsOracle_V1 { _unlockDeposit_V2(user, tokenContractAddress, tokenId, amount, lockedFor); } }
public Unlock part of deposit to a called smart contract, for internal use in same proxy user address tokenContractAddress address : ERC1155 smart contract tokenId uint256 : tokenId of ERC1155 amount uint256 amount to lock lockedFor uint256 lockedId
function internalUnLockDeposit_V2( address user, address tokenContractAddress, uint256 tokenId, uint256 amount, uint256 lockedFor ) public { _unlockDeposit_V2(user, tokenContractAddress, tokenId, amount, lockedFor); }
12,762,803
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; import "./IERC20.sol"; import "../access/Ownable.sol"; import "../interfaces/IUniswapV2Pair.sol"; import "../interfaces/IUniswapV2Factory.sol"; import "../interfaces/IUniswapV2Router02.sol"; contract Safe is IERC20, Ownable { mapping(address => uint256) private _rOwned; mapping(address => uint256) private _tOwned; mapping(address => mapping(address => uint256)) private _allowances; mapping(address => bool) private _isExcluded; mapping(address => bool) private _isExcludedFromFee; address[] private _excluded; address private _burnPool = 0x0000000000000000000000000000000000000000; uint256 private constant MAX = ~uint256(0); uint256 private _tTotal = 100_000_000_000; uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; uint256 private _tBurnTotal; string private _name; string private _symbol; uint8 private _decimals; //2% uint8 public _taxFee = 2; uint8 private _previousTaxFee = _taxFee; //2% uint8 public _burnFee = 2; uint8 private _previousBurnFee = _burnFee; uint8 public _liquidityFee = 6; uint8 private _previousLiquidityFee = _liquidityFee; uint256 public _lpRewardFromLiquidity = 1; uint256 public _maxTxAmount = 50000 * 10**18; uint256 public totalLiquidityProviderRewards; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool public BurnLpTokensEnabled = false; uint256 public TotalBurnedLpTokens; bool inSwapAndLiquify; bool public swapAndLiquifyEnabled = false; uint256 private minTokensBeforeSwap = 8000; modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } event RewardLiquidityProviders(uint256 tokenAmount); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity ); /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All three of these values are immutable: they can only be set once during * construction. */ constructor( string memory name_, string memory symbol_, uint8 decimals_ ) { _name = name_; _symbol = symbol_; _decimals = decimals_; _rOwned[_msgSender()] = _rTotal; IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Create a uniswap pair for this new token uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); // set the rest of the contract variables uniswapV2Router = _uniswapV2Router; //exclude owner and this contract from fee _isExcludedFromFee[owner()] = true; _isExcludedFromFee[address(this)] = true; emit Transfer(address(0), _msgSender(), _tTotal); } //to recieve ETH from uniswapV2Router when swaping receive() external payable {} function setTaxFeePercent(uint8 taxFee) external onlyOwner() { _taxFee = taxFee; } function setBurnFeePercent(uint8 burnFee) external onlyOwner() { _burnFee = burnFee; } function setLiquidityFeePercent(uint8 liquidityFee) external onlyOwner() { _liquidityFee = liquidityFee; } function setLpRewardFromLiquidityPercent(uint256 percent) external onlyOwner() { _lpRewardFromLiquidity = percent; } function setMaxTxPercent(uint256 maxTxPercent, uint256 maxTxDecimals) external onlyOwner() { _maxTxAmount = (_tTotal * (maxTxPercent)) / (10**(uint256(maxTxDecimals) + 2)); } function setBurnLpTokenEnabled(bool value) external onlyOwner() { BurnLpTokensEnabled = value; } function includeInReward(address account) external onlyOwner() { require(_isExcluded[account], "Account is already excluded"); for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcluded[account] = false; _excluded.pop(); break; } } } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require( currentAllowance >= amount, "ERC20: transfer amount exceeds allowance" ); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender] + addedValue ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require( currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero" ); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function deliver(uint256 tAmount) public { address sender = _msgSender(); require( !_isExcluded[sender], "Excluded addresses cannot call this function" ); (uint256 rAmount, , , , , , ) = _getValues(tAmount); _rOwned[sender] = _rOwned[sender] - (rAmount); _rTotal = _rTotal - (rAmount); _tFeeTotal = _tFeeTotal + (tAmount); } function withDrawLpTokens() public onlyOwner { IUniswapV2Pair token = IUniswapV2Pair(uniswapV2Pair); uint256 amount = token.balanceOf(address(this)); require(amount > 0, "Not enough LP tokens available to withdraw"); token.transfer(owner(), amount); } function includeInFee(address account) public onlyOwner { _isExcludedFromFee[account] = false; } function excludeFromFee(address account) public onlyOwner { _isExcludedFromFee[account] = true; } function excludeFromReward(address account) public onlyOwner() { require(!_isExcluded[account], "Account is already excluded"); if (_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); } _isExcluded[account] = true; _excluded.push(account); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overloaded; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _tTotal; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { if (_isExcluded[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); } function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns (uint256) { require(tAmount <= _tTotal, "Amount must be less than supply"); if (!deductTransferFee) { (uint256 rAmount, , , , , , ) = _getValues(tAmount); return rAmount; } else { (, uint256 rTransferAmount, , , , , ) = _getValues(tAmount); return rTransferAmount; } } function tokenFromReflection(uint256 rAmount) public view returns (uint256) { require( rAmount <= _rTotal, "Amount must be less than total reflections" ); uint256 currentRate = _getRate(); return rAmount / (currentRate); } function totalFees() public view returns (uint256) { return _tFeeTotal; } function totalBurn() public view returns (uint256) { return _tBurnTotal; } function LpTokenBalance() public view returns (uint256) { IUniswapV2Pair token = IUniswapV2Pair(uniswapV2Pair); uint256 amount = token.balanceOf(address(this)); return amount; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcluded[account]; } function isExcludedFromFee(address account) public view returns (bool) { return _isExcludedFromFee[account]; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) private { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if (from != owner() && to != owner()) require( amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount" ); // is the token balance of this contract address over the min number of // tokens that we need to initiate a swap + liquidity lock? // also, don't get caught in a circular liquidity event. // also, don't swap & liquify if sender is uniswap pair. uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= minTokensBeforeSwap; if ( overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled ) { //calculate lp rewards uint256 lpRewardAmount = (contractTokenBalance * (_lpRewardFromLiquidity)) / (10**2); //distribute rewards _rewardLiquidityProviders(lpRewardAmount); //add liquidity swapAndLiquify(contractTokenBalance - (lpRewardAmount)); //burn lp tokens, hence locking the liquidity forever if (BurnLpTokensEnabled) burnLpTokens(); } //indicates if fee should be deducted from transfer bool takeFee = true; //if any account belongs to _isExcludedFromFee account then remove the fee if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) { takeFee = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from, to, amount, takeFee); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) private { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } //this method is responsible for taking all fee, if takeFee is true function _tokenTransfer( address sender, address recipient, uint256 amount, bool takeFee ) private { if (!takeFee) removeAllFee(); if (_isExcluded[sender] && !_isExcluded[recipient]) { _transferFromExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && _isExcluded[recipient]) { _transferToExcluded(sender, recipient, amount); } else if (!_isExcluded[sender] && !_isExcluded[recipient]) { _transferStandard(sender, recipient, amount); } else if (_isExcluded[sender] && _isExcluded[recipient]) { _transferBothExcluded(sender, recipient, amount); } else { _transferStandard(sender, recipient, amount); } if (!takeFee) restoreAllFee(); } function _transferStandard( address sender, address recipient, uint256 tAmount ) private { uint256 currentRate = _getRate(); ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tLiquidity ) = _getValues(tAmount); uint256 rBurn = tBurn * (currentRate); _rOwned[sender] = _rOwned[sender] - (rAmount); _rOwned[recipient] = _rOwned[recipient] + (rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, rBurn, tFee, tBurn); emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded( address sender, address recipient, uint256 tAmount ) private { uint256 currentRate = _getRate(); ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tLiquidity ) = _getValues(tAmount); uint256 rBurn = tBurn * (currentRate); _rOwned[sender] = _rOwned[sender] - (rAmount); _tOwned[recipient] = _tOwned[recipient] + (tTransferAmount); _rOwned[recipient] = _rOwned[recipient] + (rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, rBurn, tFee, tBurn); emit Transfer(sender, recipient, tTransferAmount); } function _transferFromExcluded( address sender, address recipient, uint256 tAmount ) private { uint256 currentRate = _getRate(); ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tLiquidity ) = _getValues(tAmount); uint256 rBurn = tBurn * (currentRate); _tOwned[sender] = _tOwned[sender] - (tAmount); _rOwned[sender] = _rOwned[sender] - (rAmount); _rOwned[recipient] = _rOwned[recipient] + (rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, rBurn, tFee, tBurn); emit Transfer(sender, recipient, tTransferAmount); } function _transferBothExcluded( address sender, address recipient, uint256 tAmount ) private { uint256 currentRate = _getRate(); ( uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tLiquidity ) = _getValues(tAmount); uint256 rBurn = tBurn * (currentRate); _tOwned[sender] = _tOwned[sender] - (tAmount); _rOwned[sender] = _rOwned[sender] - (rAmount); _tOwned[recipient] = _tOwned[recipient] + (tTransferAmount); _rOwned[recipient] = _rOwned[recipient] + (rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, rBurn, tFee, tBurn); emit Transfer(sender, recipient, tTransferAmount); } function _reflectFee( uint256 rFee, uint256 rBurn, uint256 tFee, uint256 tBurn ) private { _rTotal = _rTotal - (rFee) - (rBurn); _tFeeTotal = _tFeeTotal + (tFee); _tBurnTotal = _tBurnTotal + (tBurn); _tTotal = _tTotal - (tBurn); } function restoreAllFee() private { _taxFee = _previousTaxFee; _burnFee = _previousBurnFee; _liquidityFee = _previousLiquidityFee; } function removeAllFee() private { if (_taxFee == 0 && _burnFee == 0 && _liquidityFee == 0) return; _previousTaxFee = _taxFee; _previousBurnFee = _burnFee; _previousLiquidityFee = _liquidityFee; _taxFee = 0; _burnFee = 0; _liquidityFee = 0; } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { // split the contract balance into halves uint256 half = contractTokenBalance / (2); uint256 otherHalf = contractTokenBalance - (half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance - (initialBalance); // add liquidity to uniswap addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable address(this), block.timestamp ); } function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity * (currentRate); _rOwned[address(this)] = _rOwned[address(this)] + (rLiquidity); if (_isExcluded[address(this)]) _tOwned[address(this)] = _tOwned[address(this)] + (tLiquidity); } function _rewardLiquidityProviders(uint256 liquidityRewards) private { // avoid fee calling _tokenTransfer with false _tokenTransfer(address(this), uniswapV2Pair, liquidityRewards, false); IUniswapV2Pair(uniswapV2Pair).sync(); totalLiquidityProviderRewards = totalLiquidityProviderRewards + (liquidityRewards); emit RewardLiquidityProviders(liquidityRewards); } function burnLpTokens() private { IUniswapV2Pair _token = IUniswapV2Pair(uniswapV2Pair); uint256 amount = _token.balanceOf(address(this)); TotalBurnedLpTokens = TotalBurnedLpTokens + (amount); _token.transfer(_burnPool, amount); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return (_amount * (_taxFee)) / (10**2); } function calculateBurnFee(uint256 _amount) private view returns (uint256) { return (_amount * (_burnFee)) / (10**2); } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return (_amount * (_liquidityFee)) / (10**2); } function _getRate() private view returns (uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply / (tSupply); } function _getCurrentSupply() private view returns (uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if ( _rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply ) return (_rTotal, _tTotal); rSupply = rSupply - (_rOwned[_excluded[i]]); tSupply = tSupply - (_tOwned[_excluded[i]]); } if (rSupply < _rTotal / (_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } function _getValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256, uint256, uint256, uint256 ) { ( uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tLiquidity ) = _getTValues(tAmount); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tBurn, tLiquidity, _getRate()); return ( rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tBurn, tLiquidity ); } function _getTValues(uint256 tAmount) private view returns ( uint256, uint256, uint256, uint256 ) { uint256 tFee = calculateTaxFee(tAmount); uint256 tBurn = calculateBurnFee(tAmount); uint256 tLiquidity = calculateLiquidityFee(tAmount); uint256 tTransferAmount = tAmount - (tFee) - (tBurn) - (tLiquidity); return (tTransferAmount, tFee, tBurn, tLiquidity); } function _getRValues( uint256 tAmount, uint256 tFee, uint256 tBurn, uint256 tLiquidity, uint256 currentRate ) private pure returns ( uint256, uint256, uint256 ) { uint256 rAmount = tAmount * (currentRate); uint256 rFee = tFee * (currentRate); uint256 rBurn = tBurn * (currentRate); uint256 rLiquidity = tLiquidity * (currentRate); uint256 rTransferAmount = rAmount - (rFee) - (rBurn) - (rLiquidity); return (rAmount, rTransferAmount, rFee); } }
avoid fee calling _tokenTransfer with false
function _rewardLiquidityProviders(uint256 liquidityRewards) private { _tokenTransfer(address(this), uniswapV2Pair, liquidityRewards, false); IUniswapV2Pair(uniswapV2Pair).sync(); totalLiquidityProviderRewards = totalLiquidityProviderRewards + (liquidityRewards); emit RewardLiquidityProviders(liquidityRewards); }
5,432,457
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.0; import { SignatureDrop } from "contracts/signature-drop/SignatureDrop.sol"; // Test imports import "./utils/BaseTest.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; contract SignatureDropBenchmarkTest is BaseTest { using StringsUpgradeable for uint256; SignatureDrop public sigdrop; address internal deployerSigner; bytes32 internal typehashMintRequest; bytes32 internal nameHash; bytes32 internal versionHash; bytes32 internal typehashEip712; bytes32 internal domainSeparator; SignatureDrop.AllowlistProof alp; SignatureDrop.MintRequest _mintrequest; bytes _signature; using stdStorage for StdStorage; function setUp() public override { super.setUp(); deployerSigner = signer; sigdrop = SignatureDrop(getContract("SignatureDrop")); erc20.mint(deployerSigner, 1_000_000); vm.deal(deployerSigner, 1_000); typehashMintRequest = keccak256( "MintRequest(address to,address royaltyRecipient,uint256 royaltyBps,address primarySaleRecipient,string uri,uint256 quantity,uint256 pricePerToken,address currency,uint128 validityStartTimestamp,uint128 validityEndTimestamp,bytes32 uid)" ); nameHash = keccak256(bytes("SignatureMintERC721")); versionHash = keccak256(bytes("1")); typehashEip712 = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); domainSeparator = keccak256(abi.encode(typehashEip712, nameHash, versionHash, block.chainid, address(sigdrop))); // ========================== bytes32[] memory proofs = new bytes32[](0); alp.proof = proofs; SignatureDrop.ClaimCondition[] memory conditions = new SignatureDrop.ClaimCondition[](1); conditions[0].maxClaimableSupply = 100; conditions[0].quantityLimitPerTransaction = 100; conditions[0].waitTimeInSecondsBetweenClaims = type(uint256).max; vm.prank(deployerSigner); sigdrop.lazyMint(100, "ipfs://", ""); vm.prank(deployerSigner); sigdrop.setClaimConditions(conditions[0], false); uint256 id = 0; _mintrequest.to = address(0); _mintrequest.royaltyRecipient = address(2); _mintrequest.royaltyBps = 0; _mintrequest.primarySaleRecipient = address(deployer); _mintrequest.uri = "ipfs://"; _mintrequest.quantity = 1; _mintrequest.pricePerToken = 1; _mintrequest.currency = address(erc20); _mintrequest.validityStartTimestamp = 1000; _mintrequest.validityEndTimestamp = 2000; _mintrequest.uid = bytes32(id); _signature = signMintRequest(_mintrequest, privateKey); vm.startPrank(deployerSigner); vm.warp(1000); erc20.approve(address(sigdrop), 1); } function signMintRequest(SignatureDrop.MintRequest memory mintrequest, uint256 privateKey) internal returns (bytes memory) { bytes memory encodedRequest = abi.encode( typehashMintRequest, mintrequest.to, mintrequest.royaltyRecipient, mintrequest.royaltyBps, mintrequest.primarySaleRecipient, keccak256(bytes(mintrequest.uri)), mintrequest.quantity, mintrequest.pricePerToken, mintrequest.currency, mintrequest.validityStartTimestamp, mintrequest.validityEndTimestamp, mintrequest.uid ); bytes32 structHash = keccak256(encodedRequest); bytes32 typedDataHash = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); (uint8 v, bytes32 r, bytes32 s) = vm.sign(privateKey, typedDataHash); bytes memory signature = abi.encodePacked(r, s, v); return signature; } function test_benchmark_mintWithSignature() public { sigdrop.mintWithSignature(_mintrequest, _signature); } function test_benchmark_claim() public { sigdrop.claim(address(25), 1, address(0), 0, alp, ""); } } contract SignatureDropTest is BaseTest { using StringsUpgradeable for uint256; event TokensLazyMinted(uint256 startTokenId, uint256 endTokenId, string baseURI, bytes encryptedBaseURI); event TokenURIRevealed(uint256 index, string revealedURI); event TokensMintedWithSignature( address indexed signer, address indexed mintedTo, uint256 indexed tokenIdMinted, SignatureDrop.MintRequest mintRequest ); SignatureDrop public sigdrop; address internal deployerSigner; bytes32 internal typehashMintRequest; bytes32 internal nameHash; bytes32 internal versionHash; bytes32 internal typehashEip712; bytes32 internal domainSeparator; using stdStorage for StdStorage; function setUp() public override { super.setUp(); deployerSigner = signer; sigdrop = SignatureDrop(getContract("SignatureDrop")); erc20.mint(deployerSigner, 1_000_000); vm.deal(deployerSigner, 1_000); typehashMintRequest = keccak256( "MintRequest(address to,address royaltyRecipient,uint256 royaltyBps,address primarySaleRecipient,string uri,uint256 quantity,uint256 pricePerToken,address currency,uint128 validityStartTimestamp,uint128 validityEndTimestamp,bytes32 uid)" ); nameHash = keccak256(bytes("SignatureMintERC721")); versionHash = keccak256(bytes("1")); typehashEip712 = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); domainSeparator = keccak256(abi.encode(typehashEip712, nameHash, versionHash, block.chainid, address(sigdrop))); } /*/////////////////////////////////////////////////////////////// Lazy Mint Tests //////////////////////////////////////////////////////////////*/ /* * note: Testing state changes; lazy mint a batch of tokens with no encrypted base URI. */ function test_state_lazyMint_noEncryptedURI() public { uint256 amountToLazyMint = 100; string memory baseURI = "ipfs://"; bytes memory encryptedBaseURI = ""; uint256 nextTokenIdToMintBefore = sigdrop.nextTokenIdToMint(); vm.startPrank(deployerSigner); uint256 batchId = sigdrop.lazyMint(amountToLazyMint, baseURI, encryptedBaseURI); assertEq(nextTokenIdToMintBefore + amountToLazyMint, sigdrop.nextTokenIdToMint()); assertEq(nextTokenIdToMintBefore + amountToLazyMint, batchId); for (uint256 i = 0; i < amountToLazyMint; i += 1) { string memory uri = sigdrop.tokenURI(i); console.log(uri); assertEq(uri, string(abi.encodePacked(baseURI, i.toString()))); } vm.stopPrank(); } /* * note: Testing state changes; lazy mint a batch of tokens with encrypted base URI. */ function test_state_lazyMint_withEncryptedURI() public { uint256 amountToLazyMint = 100; string memory baseURI = "ipfs://"; bytes memory encryptedBaseURI = "encryptedBaseURI://"; uint256 nextTokenIdToMintBefore = sigdrop.nextTokenIdToMint(); vm.startPrank(deployerSigner); uint256 batchId = sigdrop.lazyMint(amountToLazyMint, baseURI, encryptedBaseURI); assertEq(nextTokenIdToMintBefore + amountToLazyMint, sigdrop.nextTokenIdToMint()); assertEq(nextTokenIdToMintBefore + amountToLazyMint, batchId); for (uint256 i = 0; i < amountToLazyMint; i += 1) { string memory uri = sigdrop.tokenURI(1); assertEq(uri, string(abi.encodePacked(baseURI, "0"))); } vm.stopPrank(); } /** * note: Testing revert condition; an address without MINTER_ROLE calls lazyMint function. */ function test_revert_lazyMint_MINTER_ROLE() public { bytes memory errorMessage = abi.encodePacked( "Permissions: account ", Strings.toHexString(uint160(address(this)), 20), " is missing role ", Strings.toHexString(uint256(keccak256("MINTER_ROLE")), 32) ); vm.expectRevert(errorMessage); sigdrop.lazyMint(100, "ipfs://", ""); } /* * note: Testing revert condition; calling tokenURI for invalid batch id. */ function test_revert_lazyMint_URIForNonLazyMintedToken() public { vm.startPrank(deployerSigner); sigdrop.lazyMint(100, "ipfs://", ""); vm.expectRevert("No batch id for token."); sigdrop.tokenURI(100); vm.stopPrank(); } /** * note: Testing event emission; tokens lazy minted. */ function test_event_lazyMint_TokensLazyMinted() public { vm.startPrank(deployerSigner); vm.expectEmit(false, false, false, true); emit TokensLazyMinted(0, 100, "ipfs://", ""); sigdrop.lazyMint(100, "ipfs://", ""); vm.stopPrank(); } /* * note: Fuzz testing state changes; lazy mint a batch of tokens with no encrypted base URI. */ function test_fuzz_lazyMint_noEncryptedURI(uint256 x) public { vm.assume(x > 0); uint256 amountToLazyMint = x; string memory baseURI = "ipfs://"; bytes memory encryptedBaseURI = ""; uint256 nextTokenIdToMintBefore = sigdrop.nextTokenIdToMint(); vm.startPrank(deployerSigner); uint256 batchId = sigdrop.lazyMint(amountToLazyMint, baseURI, encryptedBaseURI); assertEq(nextTokenIdToMintBefore + amountToLazyMint, sigdrop.nextTokenIdToMint()); assertEq(nextTokenIdToMintBefore + amountToLazyMint, batchId); string memory uri = sigdrop.tokenURI(0); assertEq(uri, string(abi.encodePacked(baseURI, uint256(0).toString()))); uri = sigdrop.tokenURI(x - 1); assertEq(uri, string(abi.encodePacked(baseURI, uint256(x - 1).toString()))); /** * note: this loop takes too long to run with fuzz tests. */ // for(uint256 i = 0; i < amountToLazyMint; i += 1) { // string memory uri = sigdrop.tokenURI(i); // console.log(uri); // assertEq(uri, string(abi.encodePacked(baseURI, i.toString()))); // } vm.stopPrank(); } /* * note: Fuzz testing state changes; lazy mint a batch of tokens with encrypted base URI. */ function test_fuzz_lazyMint_withEncryptedURI(uint256 x) public { vm.assume(x > 0); uint256 amountToLazyMint = x; string memory baseURI = "ipfs://"; bytes memory encryptedBaseURI = "encryptedBaseURI://"; uint256 nextTokenIdToMintBefore = sigdrop.nextTokenIdToMint(); vm.startPrank(deployerSigner); uint256 batchId = sigdrop.lazyMint(amountToLazyMint, baseURI, encryptedBaseURI); assertEq(nextTokenIdToMintBefore + amountToLazyMint, sigdrop.nextTokenIdToMint()); assertEq(nextTokenIdToMintBefore + amountToLazyMint, batchId); string memory uri = sigdrop.tokenURI(0); assertEq(uri, string(abi.encodePacked(baseURI, "0"))); uri = sigdrop.tokenURI(x - 1); assertEq(uri, string(abi.encodePacked(baseURI, "0"))); /** * note: this loop takes too long to run with fuzz tests. */ // for(uint256 i = 0; i < amountToLazyMint; i += 1) { // string memory uri = sigdrop.tokenURI(1); // assertEq(uri, string(abi.encodePacked(baseURI, "0"))); // } vm.stopPrank(); } /* * note: Fuzz testing; a batch of tokens, and nextTokenIdToMint */ function test_fuzz_lazyMint_batchMintAndNextTokenIdToMint(uint256 x) public { vm.startPrank(deployerSigner); sigdrop.lazyMint(x, "ipfs://", ""); uint256 slot = stdstore.target(address(sigdrop)).sig("nextTokenIdToMint()").find(); bytes32 loc = bytes32(slot); uint256 nextTokenIdToMint = uint256(vm.load(address(sigdrop), loc)); assertEq(nextTokenIdToMint, x); vm.stopPrank(); } /*/////////////////////////////////////////////////////////////// Delayed Reveal Tests //////////////////////////////////////////////////////////////*/ /* * note: Testing state changes; URI revealed for a batch of tokens. */ function test_state_reveal() public { vm.startPrank(deployerSigner); bytes memory key = "key"; uint256 amountToLazyMint = 100; bytes memory secretURI = "ipfs://"; string memory placeholderURI = "ipfs://"; bytes memory encryptedURI = sigdrop.encryptDecrypt(secretURI, key); sigdrop.lazyMint(amountToLazyMint, placeholderURI, encryptedURI); for (uint256 i = 0; i < amountToLazyMint; i += 1) { string memory uri = sigdrop.tokenURI(i); assertEq(uri, string(abi.encodePacked(placeholderURI, "0"))); } string memory revealedURI = sigdrop.reveal(0, key); assertEq(revealedURI, string(secretURI)); for (uint256 i = 0; i < amountToLazyMint; i += 1) { string memory uri = sigdrop.tokenURI(i); assertEq(uri, string(abi.encodePacked(secretURI, i.toString()))); } vm.stopPrank(); } /** * note: Testing revert condition; an address without MINTER_ROLE calls reveal function. */ function test_revert_reveal_MINTER_ROLE() public { bytes memory encryptedURI = sigdrop.encryptDecrypt("ipfs://", "key"); vm.prank(deployerSigner); sigdrop.lazyMint(100, "", encryptedURI); vm.prank(deployerSigner); sigdrop.reveal(0, "key"); bytes memory errorMessage = abi.encodePacked( "Permissions: account ", Strings.toHexString(uint160(address(this)), 20), " is missing role ", Strings.toHexString(uint256(keccak256("MINTER_ROLE")), 32) ); vm.expectRevert(errorMessage); sigdrop.reveal(0, "key"); } /* * note: Testing revert condition; trying to reveal URI for non-existent batch. */ function test_revert_reveal_revealingNonExistentBatch() public { vm.startPrank(deployerSigner); bytes memory encryptedURI = sigdrop.encryptDecrypt("ipfs://", "key"); sigdrop.lazyMint(100, "", encryptedURI); sigdrop.reveal(0, "key"); console.log(sigdrop.getBaseURICount()); sigdrop.lazyMint(100, "", encryptedURI); vm.expectRevert("invalid index."); sigdrop.reveal(2, "key"); vm.stopPrank(); } /* * note: Testing revert condition; already revealed URI. */ function test_revert_delayedReveal_alreadyRevealed() public { vm.startPrank(deployerSigner); bytes memory encryptedURI = sigdrop.encryptDecrypt("ipfs://", "key"); sigdrop.lazyMint(100, "", encryptedURI); sigdrop.reveal(0, "key"); vm.expectRevert("nothing to reveal."); sigdrop.reveal(0, "key"); vm.stopPrank(); } /* * note: Testing state changes; revealing URI with an incorrect key. */ function testFail_reveal_incorrectKey() public { vm.startPrank(deployerSigner); bytes memory encryptedURI = sigdrop.encryptDecrypt("ipfs://", "key"); sigdrop.lazyMint(100, "", encryptedURI); string memory revealedURI = sigdrop.reveal(0, "keyy"); assertEq(revealedURI, "ipfs://"); vm.stopPrank(); } /** * note: Testing event emission; TokenURIRevealed. */ function test_event_reveal_TokenURIRevealed() public { vm.startPrank(deployerSigner); bytes memory encryptedURI = sigdrop.encryptDecrypt("ipfs://", "key"); sigdrop.lazyMint(100, "", encryptedURI); vm.expectEmit(false, false, false, true); emit TokenURIRevealed(0, "ipfs://"); sigdrop.reveal(0, "key"); vm.stopPrank(); } /*/////////////////////////////////////////////////////////////// Signature Mint Tests //////////////////////////////////////////////////////////////*/ function signMintRequest(SignatureDrop.MintRequest memory mintrequest, uint256 privateKey) internal returns (bytes memory) { bytes memory encodedRequest = abi.encode( typehashMintRequest, mintrequest.to, mintrequest.royaltyRecipient, mintrequest.royaltyBps, mintrequest.primarySaleRecipient, keccak256(bytes(mintrequest.uri)), mintrequest.quantity, mintrequest.pricePerToken, mintrequest.currency, mintrequest.validityStartTimestamp, mintrequest.validityEndTimestamp, mintrequest.uid ); bytes32 structHash = keccak256(encodedRequest); bytes32 typedDataHash = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); (uint8 v, bytes32 r, bytes32 s) = vm.sign(privateKey, typedDataHash); bytes memory signature = abi.encodePacked(r, s, v); return signature; } /* * note: Testing state changes; minting with signature, for a given price and currency. */ function test_state_mintWithSignature() public { vm.prank(deployerSigner); sigdrop.lazyMint(100, "ipfs://", ""); uint256 id = 0; SignatureDrop.MintRequest memory mintrequest; mintrequest.to = address(0); mintrequest.royaltyRecipient = address(2); mintrequest.royaltyBps = 0; mintrequest.primarySaleRecipient = address(deployer); mintrequest.uri = "ipfs://"; mintrequest.quantity = 1; mintrequest.pricePerToken = 1; mintrequest.currency = address(erc20); mintrequest.validityStartTimestamp = 1000; mintrequest.validityEndTimestamp = 2000; mintrequest.uid = bytes32(id); // Test with ERC20 currency { uint256 totalSupplyBefore = sigdrop.totalSupply(); bytes memory signature = signMintRequest(mintrequest, privateKey); vm.startPrank(deployerSigner); vm.warp(1000); erc20.approve(address(sigdrop), 1); vm.expectEmit(true, true, true, false); emit TokensMintedWithSignature(deployerSigner, deployerSigner, 0, mintrequest); sigdrop.mintWithSignature(mintrequest, signature); vm.stopPrank(); assertEq(totalSupplyBefore + mintrequest.quantity, sigdrop.totalSupply()); } // Test with native token currency { uint256 totalSupplyBefore = sigdrop.totalSupply(); mintrequest.currency = address(NATIVE_TOKEN); id = 1; mintrequest.uid = bytes32(id); bytes memory signature = signMintRequest(mintrequest, privateKey); vm.startPrank(address(deployerSigner)); vm.warp(1000); sigdrop.mintWithSignature{ value: mintrequest.pricePerToken }(mintrequest, signature); vm.stopPrank(); assertEq(totalSupplyBefore + mintrequest.quantity, sigdrop.totalSupply()); } } /** * note: Testing revert condition; invalid signature. */ function test_revert_mintWithSignature_unapprovedSigner() public { vm.prank(deployerSigner); sigdrop.lazyMint(100, "ipfs://", ""); uint256 id = 0; SignatureDrop.MintRequest memory mintrequest; mintrequest.to = address(0); mintrequest.royaltyRecipient = address(2); mintrequest.royaltyBps = 0; mintrequest.primarySaleRecipient = address(deployer); mintrequest.uri = "ipfs://"; mintrequest.quantity = 1; mintrequest.pricePerToken = 0; mintrequest.currency = address(3); mintrequest.validityStartTimestamp = 1000; mintrequest.validityEndTimestamp = 2000; mintrequest.uid = bytes32(id); bytes memory signature = signMintRequest(mintrequest, privateKey); vm.warp(1000); vm.prank(deployerSigner); sigdrop.mintWithSignature(mintrequest, signature); signature = signMintRequest(mintrequest, 4321); vm.expectRevert("Invalid request"); sigdrop.mintWithSignature(mintrequest, signature); } /** * note: Testing revert condition; not enough minted tokens. */ function test_revert_mintWithSignature_notEnoughMintedTokens() public { vm.prank(deployerSigner); sigdrop.lazyMint(100, "ipfs://", ""); uint256 id = 0; SignatureDrop.MintRequest memory mintrequest; mintrequest.to = address(0); mintrequest.royaltyRecipient = address(2); mintrequest.royaltyBps = 0; mintrequest.primarySaleRecipient = address(deployer); mintrequest.uri = "ipfs://"; mintrequest.quantity = 101; mintrequest.pricePerToken = 0; mintrequest.currency = address(3); mintrequest.validityStartTimestamp = 1000; mintrequest.validityEndTimestamp = 2000; mintrequest.uid = bytes32(id); bytes memory signature = signMintRequest(mintrequest, privateKey); vm.warp(1000); vm.expectRevert("not enough minted tokens."); sigdrop.mintWithSignature(mintrequest, signature); } /** * note: Testing revert condition; sent value is not equal to price. */ function test_revert_mintWithSignature_notSentAmountRequired() public { vm.prank(deployerSigner); sigdrop.lazyMint(100, "ipfs://", ""); uint256 id = 0; SignatureDrop.MintRequest memory mintrequest; mintrequest.to = address(0); mintrequest.royaltyRecipient = address(2); mintrequest.royaltyBps = 0; mintrequest.primarySaleRecipient = address(deployer); mintrequest.uri = "ipfs://"; mintrequest.quantity = 1; mintrequest.pricePerToken = 1; mintrequest.currency = address(3); mintrequest.validityStartTimestamp = 1000; mintrequest.validityEndTimestamp = 2000; mintrequest.uid = bytes32(id); { mintrequest.currency = address(NATIVE_TOKEN); bytes memory signature = signMintRequest(mintrequest, privateKey); vm.startPrank(address(deployerSigner)); vm.warp(mintrequest.validityStartTimestamp); vm.expectRevert("must send total price."); sigdrop.mintWithSignature{ value: 2 }(mintrequest, signature); vm.stopPrank(); } } /** * note: Testing token balances; checking balance and owner of tokens after minting with signature. */ function test_balances_mintWithSignature() public { vm.prank(deployerSigner); sigdrop.lazyMint(100, "ipfs://", ""); uint256 id = 0; SignatureDrop.MintRequest memory mintrequest; mintrequest.to = address(0); mintrequest.royaltyRecipient = address(2); mintrequest.royaltyBps = 0; mintrequest.primarySaleRecipient = address(deployer); mintrequest.uri = "ipfs://"; mintrequest.quantity = 1; mintrequest.pricePerToken = 1; mintrequest.currency = address(erc20); mintrequest.validityStartTimestamp = 1000; mintrequest.validityEndTimestamp = 2000; mintrequest.uid = bytes32(id); { uint256 currencyBalBefore = erc20.balanceOf(deployerSigner); bytes memory signature = signMintRequest(mintrequest, privateKey); vm.startPrank(deployerSigner); vm.warp(1000); erc20.approve(address(sigdrop), 1); sigdrop.mintWithSignature(mintrequest, signature); vm.stopPrank(); uint256 balance = sigdrop.balanceOf(address(deployerSigner)); assertEq(balance, 1); address owner = sigdrop.ownerOf(0); assertEq(deployerSigner, owner); assertEq( currencyBalBefore - mintrequest.pricePerToken * mintrequest.quantity, erc20.balanceOf(deployerSigner) ); vm.expectRevert(abi.encodeWithSignature("OwnerQueryForNonexistentToken()")); owner = sigdrop.ownerOf(1); } } /* * note: Testing state changes; minting with signature, for a given price and currency. */ function mintWithSignature(SignatureDrop.MintRequest memory mintrequest) internal { vm.prank(deployerSigner); sigdrop.lazyMint(100, "ipfs://", ""); uint256 id = 0; { bytes memory signature = signMintRequest(mintrequest, privateKey); vm.startPrank(deployerSigner); vm.warp(mintrequest.validityStartTimestamp); erc20.approve(address(sigdrop), 1); sigdrop.mintWithSignature(mintrequest, signature); vm.stopPrank(); } { mintrequest.currency = address(NATIVE_TOKEN); id = 1; mintrequest.uid = bytes32(id); bytes memory signature = signMintRequest(mintrequest, privateKey); vm.startPrank(address(deployerSigner)); vm.warp(mintrequest.validityStartTimestamp); sigdrop.mintWithSignature{ value: mintrequest.pricePerToken }(mintrequest, signature); vm.stopPrank(); } } function test_fuzz_mintWithSignature(uint128 x, uint128 y) public { if (x < y) { uint256 id = 0; SignatureDrop.MintRequest memory mintrequest; mintrequest.to = address(0); mintrequest.royaltyRecipient = address(2); mintrequest.royaltyBps = 0; mintrequest.primarySaleRecipient = address(deployer); mintrequest.uri = "ipfs://"; mintrequest.quantity = 1; mintrequest.pricePerToken = 1; mintrequest.currency = address(erc20); mintrequest.validityStartTimestamp = x; mintrequest.validityEndTimestamp = y; mintrequest.uid = bytes32(id); mintWithSignature(mintrequest); } } /*/////////////////////////////////////////////////////////////// Claim Tests //////////////////////////////////////////////////////////////*/ /** * note: Testing revert condition; not allowed to claim again before wait time is over. */ function test_revert_claimCondition_waitTimeInSecondsBetweenClaims() public { vm.warp(1); address receiver = getActor(0); bytes32[] memory proofs = new bytes32[](0); SignatureDrop.AllowlistProof memory alp; alp.proof = proofs; SignatureDrop.ClaimCondition[] memory conditions = new SignatureDrop.ClaimCondition[](1); conditions[0].maxClaimableSupply = 100; conditions[0].quantityLimitPerTransaction = 100; conditions[0].waitTimeInSecondsBetweenClaims = type(uint256).max; vm.prank(deployerSigner); sigdrop.lazyMint(100, "ipfs://", ""); vm.prank(deployerSigner); sigdrop.setClaimConditions(conditions[0], false); vm.prank(getActor(5), getActor(5)); sigdrop.claim(receiver, 1, address(0), 0, alp, ""); vm.expectRevert("cannot claim."); vm.prank(getActor(5), getActor(5)); sigdrop.claim(receiver, 1, address(0), 0, alp, ""); } /** * note: Testing revert condition; not enough minted tokens. */ function test_revert_claimCondition_notEnoughMintedTokens() public { vm.warp(1); address receiver = getActor(0); bytes32[] memory proofs = new bytes32[](0); SignatureDrop.AllowlistProof memory alp; alp.proof = proofs; SignatureDrop.ClaimCondition[] memory conditions = new SignatureDrop.ClaimCondition[](1); conditions[0].maxClaimableSupply = 100; conditions[0].quantityLimitPerTransaction = 100; conditions[0].waitTimeInSecondsBetweenClaims = type(uint256).max; vm.prank(deployerSigner); sigdrop.lazyMint(100, "ipfs://", ""); vm.prank(deployerSigner); sigdrop.setClaimConditions(conditions[0], false); vm.expectRevert("not enough minted tokens."); vm.prank(getActor(6), getActor(6)); sigdrop.claim(receiver, 101, address(0), 0, alp, ""); } /** * note: Testing revert condition; exceed max claimable supply. */ function test_revert_claimCondition_exceedMaxClaimableSupply() public { vm.warp(1); address receiver = getActor(0); bytes32[] memory proofs = new bytes32[](0); SignatureDrop.AllowlistProof memory alp; alp.proof = proofs; SignatureDrop.ClaimCondition[] memory conditions = new SignatureDrop.ClaimCondition[](1); conditions[0].maxClaimableSupply = 100; conditions[0].quantityLimitPerTransaction = 100; conditions[0].waitTimeInSecondsBetweenClaims = type(uint256).max; vm.prank(deployerSigner); sigdrop.lazyMint(200, "ipfs://", ""); vm.prank(deployerSigner); sigdrop.setClaimConditions(conditions[0], false); vm.prank(getActor(5), getActor(5)); sigdrop.claim(receiver, 100, address(0), 0, alp, ""); vm.expectRevert("exceed max claimable supply."); vm.prank(getActor(6), getActor(6)); sigdrop.claim(receiver, 1, address(0), 0, alp, ""); } /** * note: Testing revert condition; can't claim if not in whitelist. */ function test_revert_claimCondition_merkleProof() public { string[] memory inputs = new string[](2); inputs[0] = "node"; inputs[1] = "src/test/scripts/generateRoot.ts"; bytes memory result = vm.ffi(inputs); bytes32 root = abi.decode(result, (bytes32)); inputs[1] = "src/test/scripts/getProof.ts"; result = vm.ffi(inputs); bytes32[] memory proofs = abi.decode(result, (bytes32[])); vm.warp(1); address receiver = address(0x92Bb439374a091c7507bE100183d8D1Ed2c9dAD3); SignatureDrop.AllowlistProof memory alp; alp.proof = proofs; SignatureDrop.ClaimCondition[] memory conditions = new SignatureDrop.ClaimCondition[](1); conditions[0].maxClaimableSupply = 100; conditions[0].quantityLimitPerTransaction = 100; conditions[0].waitTimeInSecondsBetweenClaims = type(uint256).max; conditions[0].merkleRoot = root; vm.prank(deployerSigner); sigdrop.lazyMint(200, "ipfs://", ""); vm.prank(deployerSigner); sigdrop.setClaimConditions(conditions[0], false); // vm.prank(getActor(5), getActor(5)); vm.prank(receiver); sigdrop.claim(receiver, 100, address(0), 0, alp, ""); vm.prank(address(4)); vm.expectRevert("not in whitelist."); sigdrop.claim(receiver, 100, address(0), 0, alp, ""); } /** * note: Testing state changes; reset eligibility of claim conditions and claiming again for same condition id. */ function test_state_claimCondition_resetEligibility_waitTimeInSecondsBetweenClaims() public { vm.warp(1); address receiver = getActor(0); bytes32[] memory proofs = new bytes32[](0); SignatureDrop.AllowlistProof memory alp; alp.proof = proofs; SignatureDrop.ClaimCondition[] memory conditions = new SignatureDrop.ClaimCondition[](1); conditions[0].maxClaimableSupply = 100; conditions[0].quantityLimitPerTransaction = 100; conditions[0].waitTimeInSecondsBetweenClaims = type(uint256).max; vm.prank(deployerSigner); sigdrop.lazyMint(100, "ipfs://", ""); vm.prank(deployerSigner); sigdrop.setClaimConditions(conditions[0], false); vm.prank(getActor(5), getActor(5)); sigdrop.claim(receiver, 1, address(0), 0, alp, ""); vm.prank(deployerSigner); sigdrop.setClaimConditions(conditions[0], true); vm.prank(getActor(5), getActor(5)); sigdrop.claim(receiver, 1, address(0), 0, alp, ""); } /*/////////////////////////////////////////////////////////////// Reentrancy related Tests //////////////////////////////////////////////////////////////*/ function testFail_reentrancy_mintWithSignature() public { vm.prank(deployerSigner); sigdrop.lazyMint(100, "ipfs://", ""); uint256 id = 0; SignatureDrop.MintRequest memory mintrequest; mintrequest.to = address(0); mintrequest.royaltyRecipient = address(2); mintrequest.royaltyBps = 0; mintrequest.primarySaleRecipient = address(deployer); mintrequest.uri = "ipfs://"; mintrequest.quantity = 1; mintrequest.pricePerToken = 1; mintrequest.currency = address(NATIVE_TOKEN); mintrequest.validityStartTimestamp = 1000; mintrequest.validityEndTimestamp = 2000; mintrequest.uid = bytes32(id); // Test with native token currency { uint256 totalSupplyBefore = sigdrop.totalSupply(); mintrequest.uid = bytes32(id); bytes memory signature = signMintRequest(mintrequest, privateKey); MaliciousReceiver mal = new MaliciousReceiver(address(sigdrop)); vm.deal(address(mal), 100 ether); vm.warp(1000); mal.attackMintWithSignature(mintrequest, signature, false); assertEq(totalSupplyBefore + mintrequest.quantity, sigdrop.totalSupply()); } } function testFail_reentrancy_claim() public { vm.warp(1); bytes32[] memory proofs = new bytes32[](0); SignatureDrop.AllowlistProof memory alp; alp.proof = proofs; SignatureDrop.ClaimCondition[] memory conditions = new SignatureDrop.ClaimCondition[](1); conditions[0].maxClaimableSupply = 100; conditions[0].quantityLimitPerTransaction = 100; conditions[0].waitTimeInSecondsBetweenClaims = type(uint256).max; vm.prank(deployerSigner); sigdrop.lazyMint(100, "ipfs://", ""); vm.prank(deployerSigner); sigdrop.setClaimConditions(conditions[0], false); MaliciousReceiver mal = new MaliciousReceiver(address(sigdrop)); vm.deal(address(mal), 100 ether); mal.attackClaim(alp, false); } function testFail_combination_signatureAndClaim() public { vm.warp(1); bytes32[] memory proofs = new bytes32[](0); SignatureDrop.AllowlistProof memory alp; alp.proof = proofs; SignatureDrop.ClaimCondition[] memory conditions = new SignatureDrop.ClaimCondition[](1); conditions[0].maxClaimableSupply = 100; conditions[0].quantityLimitPerTransaction = 100; conditions[0].waitTimeInSecondsBetweenClaims = type(uint256).max; vm.prank(deployerSigner); sigdrop.lazyMint(100, "ipfs://", ""); vm.prank(deployerSigner); sigdrop.setClaimConditions(conditions[0], false); uint256 id = 0; SignatureDrop.MintRequest memory mintrequest; mintrequest.to = address(0); mintrequest.royaltyRecipient = address(2); mintrequest.royaltyBps = 0; mintrequest.primarySaleRecipient = address(deployer); mintrequest.uri = "ipfs://"; mintrequest.quantity = 1; mintrequest.pricePerToken = 1; mintrequest.currency = address(NATIVE_TOKEN); mintrequest.validityStartTimestamp = 1000; mintrequest.validityEndTimestamp = 2000; mintrequest.uid = bytes32(id); // Test with native token currency { uint256 totalSupplyBefore = sigdrop.totalSupply(); mintrequest.uid = bytes32(id); bytes memory signature = signMintRequest(mintrequest, privateKey); MaliciousReceiver mal = new MaliciousReceiver(address(sigdrop)); vm.deal(address(mal), 100 ether); vm.warp(1000); mal.saveCombination(mintrequest, signature, alp); mal.attackMintWithSignature(mintrequest, signature, true); // mal.attackClaim(alp, true); assertEq(totalSupplyBefore + mintrequest.quantity, sigdrop.totalSupply()); } } } contract MaliciousReceiver { SignatureDrop public sigdrop; SignatureDrop.MintRequest public mintrequest; SignatureDrop.AllowlistProof public alp; bytes public signature; bool public claim; bool public loop = true; constructor(address _sigdrop) { sigdrop = SignatureDrop(_sigdrop); } function attackMintWithSignature( SignatureDrop.MintRequest calldata _mintrequest, bytes calldata _signature, bool swap ) external { claim = swap; mintrequest = _mintrequest; signature = _signature; sigdrop.mintWithSignature{ value: _mintrequest.pricePerToken }(_mintrequest, _signature); } function attackClaim(SignatureDrop.AllowlistProof calldata _alp, bool swap) external { claim = !swap; alp = _alp; sigdrop.claim(address(this), 1, address(0), 0, _alp, ""); } function saveCombination( SignatureDrop.MintRequest calldata _mintrequest, bytes calldata _signature, SignatureDrop.AllowlistProof calldata _alp ) external { mintrequest = _mintrequest; signature = _signature; alp = _alp; } function onERC721Received( address, address, uint256, bytes calldata ) external returns (bytes4) { if (claim && loop) { loop = false; claim = false; sigdrop.claim(address(this), 1, address(0), 0, alp, ""); } else if (!claim && loop) { loop = false; sigdrop.mintWithSignature{ value: mintrequest.pricePerToken }(mintrequest, signature); } return this.onERC721Received.selector; } }
note: Testing state changes; reset eligibility of claim conditions and claiming again for same condition id./
function test_state_claimCondition_resetEligibility_waitTimeInSecondsBetweenClaims() public { vm.warp(1); address receiver = getActor(0); bytes32[] memory proofs = new bytes32[](0); SignatureDrop.AllowlistProof memory alp; alp.proof = proofs; SignatureDrop.ClaimCondition[] memory conditions = new SignatureDrop.ClaimCondition[](1); conditions[0].maxClaimableSupply = 100; conditions[0].quantityLimitPerTransaction = 100; conditions[0].waitTimeInSecondsBetweenClaims = type(uint256).max; vm.prank(deployerSigner); vm.prank(deployerSigner); sigdrop.setClaimConditions(conditions[0], false); vm.prank(getActor(5), getActor(5)); sigdrop.claim(receiver, 1, address(0), 0, alp, ""); vm.prank(deployerSigner); sigdrop.setClaimConditions(conditions[0], true); vm.prank(getActor(5), getActor(5)); sigdrop.claim(receiver, 1, address(0), 0, alp, ""); } Reentrancy related Tests
1,798,331
// SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; pragma experimental ABIEncoderV2; import '../interfaces/IElasticToken.sol'; import '../libraries/ElasticMath.sol'; import '../core/ElasticDAO.sol'; import '../models/DAO.sol'; import '../models/Ecosystem.sol'; import '../models/Token.sol'; import '../models/TokenHolder.sol'; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; /** * @dev ElasticGovernanceToken contract outlines and defines all the functionality * of an ElasticGovernanceToken and also serves as it's storage */ contract ElasticGovernanceToken is IElasticToken, ReentrancyGuard { address public burner; address public daoAddress; address public ecosystemModelAddress; address public minter; bool public initialized; mapping(address => mapping(address => uint256)) private _allowances; modifier onlyDAO() { require(msg.sender == daoAddress, 'ElasticDAO: Not authorized'); _; } modifier onlyDAOorBurner() { require(msg.sender == daoAddress || msg.sender == burner, 'ElasticDAO: Not authorized'); _; } modifier onlyDAOorMinter() { require(msg.sender == daoAddress || msg.sender == minter, 'ElasticDAO: Not authorized'); _; } /** * @notice initializes the ElasticGovernanceToken * * @param _burner - the address which can burn tokens * @param _minter - the address which can mint tokens * @param _ecosystem - Ecosystem Instance * @param _token - Token Instance * * @dev Requirements: * - The token should not already be initialized * - The address of the burner cannot be zero * - The address of the deployed ElasticDAO cannot be zero * - The address of the ecosystemModelAddress cannot be zero * - The address of the minter cannot be zero * * @return bool */ function initialize( address _burner, address _minter, Ecosystem.Instance memory _ecosystem, Token.Instance memory _token ) external nonReentrant returns (Token.Instance memory) { require(initialized == false, 'ElasticDAO: Already initialized'); require(_burner != address(0), 'ElasticDAO: Address Zero'); require(_ecosystem.daoAddress != address(0), 'ElasticDAO: Address Zero'); require(_ecosystem.ecosystemModelAddress != address(0), 'ElasticDAO: Address Zero'); require(_minter != address(0), 'ElasticDAO: Address Zero'); initialized = true; burner = _burner; daoAddress = _ecosystem.daoAddress; ecosystemModelAddress = _ecosystem.ecosystemModelAddress; minter = _minter; Token tokenStorage = Token(_ecosystem.tokenModelAddress); tokenStorage.serialize(_token); return _token; } /** * @notice Returns the remaining number of tokens that @param _spender will be * allowed to spend on behalf of @param _owner through {transferFrom}. This is * zero by default * * @param _spender - the address of the spender * @param _owner - the address of the owner * * @dev This value changes when {approve} or {transferFrom} are called * * @return uint256 */ function allowance(address _owner, address _spender) external view override returns (uint256) { return _allowances[_owner][_spender]; } /** * @notice Sets @param _amount as the allowance of @param _spender over the caller's tokens * * @param _spender - the address of the spender * * @dev * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * @dev Emits an {Approval} event * * @return bool */ function approve(address _spender, uint256 _amount) external override nonReentrant returns (bool) { _approve(msg.sender, _spender, _amount); return true; } /** * @notice Returns the amount of tokens owned by @param _account using ElasticMath * * @param _account - address of the account * * @dev the number of tokens is given by: * t = lambda * m * k * * t - number of tokens * m - lambda modifier - it's value increases every time someone joins the DAO * k - constant token multiplier - it increases the number of tokens * that each member of the DAO has with respect to their lambda * * Further math and documentaion of 't' can be found at ../libraries/ElasticMath.sol * * @return uint256 */ function balanceOf(address _account) external view override returns (uint256) { Token.Instance memory token = _getToken(); TokenHolder.Instance memory tokenHolder = _getTokenHolder(_account); uint256 t = ElasticMath.t(tokenHolder.lambda, token.k, token.m); return t; } /** * @notice Returns the amount of shares ( lambda ) owned by _account. * * @param _account - address of the account * * @return lambda uint256 - lambda is the number of shares */ function balanceOfInShares(address _account) external view override returns (uint256) { TokenHolder.Instance memory tokenHolder = _getTokenHolder(_account); return tokenHolder.lambda; } /** * @notice Returns the amount of tokens @param _account can vote with, using ElasticMath * * @param _account - the address of the account * * @dev checks if @param _account has more or less lambda than maxVotingLambda, * based on which number of tokens (t) @param _account can vote with is calculated. * Further math and documentaion of 't' can be found at ../libraries/ElasticMath.sol * * @return balance uint256 numberOfTokens (t) */ function balanceOfVoting(address _account) external view returns (uint256 balance) { Token.Instance memory token = _getToken(); TokenHolder.Instance memory tokenHolder = _getTokenHolder(_account); uint256 maxVotingLambda = _getDAO().maxVotingLambda; if (tokenHolder.lambda > maxVotingLambda) { return ElasticMath.t(maxVotingLambda, token.k, token.m); } else { return ElasticMath.t(tokenHolder.lambda, token.k, token.m); } } /** * @notice Reduces the balance(tokens) of @param _account by _amount * * @param _account address of the account * * @param _amount - the amount by which the number of tokens is to be reduced * * @return bool */ function burn(address _account, uint256 _amount) external override onlyDAOorBurner nonReentrant returns (bool) { _burn(_account, _amount); return true; } /** * @notice Reduces the balance(lambda) of @param _account by _amount * * @param _account - address of the account * * @param _amount - the amount by which the number of shares has to be reduced * * @return bool */ function burnShares(address _account, uint256 _amount) external override onlyDAOorBurner nonReentrant returns (bool) { _burnShares(_account, _amount); return true; } /** * @notice returns the number of decimals * * @return 18 */ function decimals() external pure returns (uint256) { return 18; } /** * @notice decreases the allowance of @param _spender by _subtractedValue * * @param _spender - address of the spender * @param _subtractedValue - the value the allowance has to be decreased by * * @dev Requirement: * Allowance cannot be lower than 0 * * @return bool */ function decreaseAllowance(address _spender, uint256 _subtractedValue) external nonReentrant returns (bool) { uint256 newAllowance = SafeMath.sub(_allowances[msg.sender][_spender], _subtractedValue); _approve(msg.sender, _spender, newAllowance); return true; } /** * @notice increases the allowance of @param _spender by _addedValue * * @param _spender - address of the spender * @param _addedValue - the value the allowance has to be increased by * * @return bool */ function increaseAllowance(address _spender, uint256 _addedValue) external nonReentrant returns (bool) { _approve(msg.sender, _spender, SafeMath.add(_allowances[msg.sender][_spender], _addedValue)); return true; } /** * @dev mints @param _amount tokens for @param _account * @param _account - the address of the account for whom the token have to be minted to * @param _amount - the amount of tokens to be minted * @return bool */ function mint(address _account, uint256 _amount) external override onlyDAOorMinter nonReentrant returns (bool) { _mint(_account, _amount); return true; } /** * @dev mints @param _amount of shares for @param _account * @param _account address of the account * @param _amount - the amount of shares to be minted * @return bool */ function mintShares(address _account, uint256 _amount) external override onlyDAOorMinter nonReentrant returns (bool) { _mintShares(_account, _amount); return true; } /** * @dev Returns the name of the token. * @return string - name of the token */ function name() external view returns (string memory) { return _getToken().name; } /** * @notice Returns the number of token holders of ElasticGovernanceToken * * @return uint256 numberOfTokenHolders */ function numberOfTokenHolders() external view override returns (uint256) { return _getToken().numberOfTokenHolders; } /** * @notice sets the burner of the ElasticGovernanceToken * a Burner is an address that can burn tokens(reduce the amount of tokens in circulation) * * @param _burner - the address of the burner * * @dev Requirement: * - Address of the burner cannot be zero address * * @return bool */ function setBurner(address _burner) external onlyDAO nonReentrant returns (bool) { require(_burner != address(0), 'ElasticDAO: Address Zero'); burner = _burner; return true; } /** * @notice sets the minter of the ElasticGovernanceToken * a Minter is an address that can mint tokens(increase the amount of tokens in circulation) * * @param _minter - address of the minter * * @dev Requirement: * - Address of the minter cannot be zero address * * @return bool */ function setMinter(address _minter) external onlyDAO nonReentrant returns (bool) { require(_minter != address(0), 'ElasticDAO: Address Zero'); minter = _minter; return true; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. * * @return string - the symbol of the token */ function symbol() external view returns (string memory) { return _getToken().symbol; } /** * @notice returns the totalSupply of tokens in the DAO * * @dev * t - the total number of tokens in the DAO * lambda - the total number of shares outstanding in the DAO currently * m - current value of the share modifier * k - constant * t = ( lambda * m * k ) * Further math and documentaion of 't' can be found at ../libraries/ElasticMath.sol * * @return uint256 - the value of t */ function totalSupply() external view override returns (uint256) { Token.Instance memory token = _getToken(); return ElasticMath.t(token.lambda, token.k, token.m); } /** * @notice Returns the current lambda value * * @return uint256 lambda */ function totalSupplyInShares() external view override returns (uint256) { Token.Instance memory token = _getToken(); return token.lambda; } /** * @dev Moves @param _amount tokens from the caller's account to @param _to address * * Returns a boolean value indicating whether the operation succeeded * * Emits a {Transfer} event * @return bool */ function transfer(address _to, uint256 _amount) external override nonReentrant returns (bool) { _transfer(msg.sender, _to, _amount); return true; } /** * @dev Moves @param _amount tokens from @param _from to @param _to using the * allowance mechanism. @param _amount is then deducted from the caller's * allowance * * Returns a boolean value indicating whether the operation succeeded * * Emits a {Transfer} event * @return bool */ function transferFrom( address _from, address _to, uint256 _amount ) external override nonReentrant returns (bool) { require(msg.sender == _from || _amount <= _allowances[_from][msg.sender], 'ERC20: Bad Caller'); if (msg.sender != _from && _allowances[_from][msg.sender] != uint256(-1)) { _allowances[_from][msg.sender] = SafeMath.sub(_allowances[_from][msg.sender], _amount); emit Approval(_from, msg.sender, _allowances[_from][msg.sender]); } _transfer(_from, _to, _amount); return true; } // Private function _approve( address _owner, address _spender, uint256 _amount ) internal { require(_owner != address(0), 'ERC20: approve from the zero address'); require(_spender != address(0), 'ERC20: approve to the zero address'); _allowances[_owner][_spender] = _amount; emit Approval(_owner, _spender, _amount); } function _burn(address _account, uint256 _deltaT) internal { Token.Instance memory token = _getToken(); uint256 deltaLambda = ElasticMath.lambdaFromT(_deltaT, token.k, token.m); _burnShares(_account, deltaLambda); } function _burnShares(address _account, uint256 _deltaLambda) internal { Ecosystem.Instance memory ecosystem = _getEcosystem(); Token tokenStorage = Token(ecosystem.tokenModelAddress); Token.Instance memory token = tokenStorage.deserialize(address(this), ecosystem); TokenHolder.Instance memory tokenHolder = _getTokenHolder(_account); bool alreadyTokenHolder = tokenHolder.lambda > 0; uint256 deltaT = ElasticMath.t(_deltaLambda, token.k, token.m); tokenHolder = _updateBalance(tokenHolder, false, _deltaLambda); token.lambda = SafeMath.sub(token.lambda, _deltaLambda); tokenStorage.serialize(token); TokenHolder tokenHolderStorage = TokenHolder(ecosystem.tokenHolderModelAddress); tokenHolderStorage.serialize(tokenHolder); _updateNumberOfTokenHolders(alreadyTokenHolder, token, tokenHolder, tokenStorage); emit Transfer(_account, address(0), deltaT); } function _mint(address _account, uint256 _deltaT) internal { Token.Instance memory token = _getToken(); uint256 deltaLambda = ElasticMath.lambdaFromT(_deltaT, token.k, token.m); _mintShares(_account, deltaLambda); } function _mintShares(address _account, uint256 _deltaLambda) internal { Ecosystem.Instance memory ecosystem = _getEcosystem(); Token tokenStorage = Token(ecosystem.tokenModelAddress); Token.Instance memory token = tokenStorage.deserialize(address(this), ecosystem); TokenHolder.Instance memory tokenHolder = _getTokenHolder(_account); bool alreadyTokenHolder = tokenHolder.lambda > 0; uint256 deltaT = ElasticMath.t(_deltaLambda, token.k, token.m); tokenHolder = _updateBalance(tokenHolder, true, _deltaLambda); token.lambda = SafeMath.add(token.lambda, _deltaLambda); tokenStorage.serialize(token); TokenHolder tokenHolderStorage = TokenHolder(ecosystem.tokenHolderModelAddress); tokenHolderStorage.serialize(tokenHolder); _updateNumberOfTokenHolders(alreadyTokenHolder, token, tokenHolder, tokenStorage); emit Transfer(address(0), _account, deltaT); } function _transfer( address _from, address _to, uint256 _deltaT ) internal { require(_from != _to, 'ElasticDAO: Can not transfer to self'); Ecosystem.Instance memory ecosystem = _getEcosystem(); Token tokenStorage = Token(ecosystem.tokenModelAddress); Token.Instance memory token = tokenStorage.deserialize(address(this), ecosystem); TokenHolder.Instance memory fromTokenHolder = _getTokenHolder(_from); TokenHolder.Instance memory toTokenHolder = _getTokenHolder(_to); bool fromAlreadyTokenHolder = fromTokenHolder.lambda > 0; bool toAlreadyTokenHolder = toTokenHolder.lambda > 0; uint256 deltaLambda = ElasticMath.lambdaFromT(_deltaT, token.k, token.m); uint256 deltaT = ElasticMath.t(deltaLambda, token.k, token.m); fromTokenHolder = _updateBalance(fromTokenHolder, false, deltaLambda); toTokenHolder = _updateBalance(toTokenHolder, true, deltaLambda); TokenHolder tokenHolderStorage = TokenHolder(ecosystem.tokenHolderModelAddress); tokenHolderStorage.serialize(fromTokenHolder); tokenHolderStorage.serialize(toTokenHolder); _updateNumberOfTokenHolders(fromAlreadyTokenHolder, token, fromTokenHolder, tokenStorage); _updateNumberOfTokenHolders(toAlreadyTokenHolder, token, toTokenHolder, tokenStorage); emit Transfer(_from, _to, deltaT); } function _updateBalance( TokenHolder.Instance memory _tokenHolder, bool _isIncreasing, uint256 _deltaLambda ) internal pure returns (TokenHolder.Instance memory) { if (_isIncreasing) { _tokenHolder.lambda = SafeMath.add(_tokenHolder.lambda, _deltaLambda); } else { _tokenHolder.lambda = SafeMath.sub(_tokenHolder.lambda, _deltaLambda); } return _tokenHolder; } function _updateNumberOfTokenHolders( bool alreadyTokenHolder, Token.Instance memory token, TokenHolder.Instance memory tokenHolder, Token tokenStorage ) internal { if (tokenHolder.lambda > 0 && alreadyTokenHolder == false) { tokenStorage.updateNumberOfTokenHolders(token, SafeMath.add(token.numberOfTokenHolders, 1)); } if (tokenHolder.lambda == 0 && alreadyTokenHolder) { tokenStorage.updateNumberOfTokenHolders(token, SafeMath.sub(token.numberOfTokenHolders, 1)); } } // Private Getters function _getDAO() internal view returns (DAO.Instance memory) { Ecosystem.Instance memory ecosystem = _getEcosystem(); return DAO(ecosystem.daoModelAddress).deserialize(daoAddress, ecosystem); } function _getEcosystem() internal view returns (Ecosystem.Instance memory) { return Ecosystem(ecosystemModelAddress).deserialize(daoAddress); } function _getTokenHolder(address _account) internal view returns (TokenHolder.Instance memory) { Ecosystem.Instance memory ecosystem = _getEcosystem(); return TokenHolder(ecosystem.tokenHolderModelAddress).deserialize( _account, ecosystem, Token(ecosystem.tokenModelAddress).deserialize(address(this), ecosystem) ); } function _getToken() internal view returns (Token.Instance memory) { Ecosystem.Instance memory ecosystem = _getEcosystem(); return Token(ecosystem.tokenModelAddress).deserialize(address(this), ecosystem); } } // SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; interface IElasticToken is IERC20 { /** * @dev Returns the amount of shares owned by @param _account. * @param _account - address of the account * @return lambda uint256 - lambda is the number of shares */ function balanceOfInShares(address _account) external view returns (uint256 lambda); /** * @dev Reduces the balance(tokens) of @param _account by @param _amount * @param _account address of the account * @param _amount - the amount by which the number of tokens has to be reduced * @return bool */ function burn(address _account, uint256 _amount) external returns (bool); /** * @dev Reduces the balance(shares) of @param _account by @param _amount * @param _account - address of the account * @param _amount - the amount by which the number of shares has to be reduced * @return bool */ function burnShares(address _account, uint256 _amount) external returns (bool); /** * @dev mints @param _amount tokens for @param _account * @param _account - the address of the account for whom the token have to be minted to * @param _amount - the amount of tokens to be minted * @return bool */ function mint(address _account, uint256 _amount) external returns (bool); /** * @dev mints @param _amount of shares for @param _account * @param _account address of the account * @param _amount - the amount of shares to be minted * @return bool */ function mintShares(address _account, uint256 _amount) external returns (bool); /** * @dev returns total number of token holders * @return uint256 */ function numberOfTokenHolders() external view returns (uint256); /** * @dev Returns the total supply of shares in the DAO * @return lambda uint256 - lambda is the number of shares */ function totalSupplyInShares() external view returns (uint256 lambda); } // SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; import './SafeMath.sol'; /** * @dev Provides functions for performing ElasticDAO specific math. * * These functions correspond with functions provided by the JS SDK and should * always be used instead of doing calculations within other contracts to avoid * any inconsistencies in the math. * * Notes: * * - Dash values represent the state after a transaction has completed successfully. * - Non-dash values represent the current state, before the transaction has completed. * - Lambda is the math term for shares. We typically expose the value to users as * shares instead of lambda because it's easier to grok. */ library ElasticMath { /** * @dev calculates the value of capitalDelta; the amount of ETH backing each * governance token. * @param totalEthValue amount of ETH in the DAO contract * @param totalSupplyOfTokens number of tokens in existance * * capitalDelta = totalEthValue / totalSupplyOfTokens * @return uint256 */ function capitalDelta(uint256 totalEthValue, uint256 totalSupplyOfTokens) internal pure returns (uint256) { return wdiv(totalEthValue, totalSupplyOfTokens); } /** * @dev calculates the value of deltaE; the amount of ETH required to mint deltaLambda * @param deltaLambda = lambdaDash - lambda * @param capitalDeltaValue the ETH/token ratio; see capitalDelta(uint256, uint256) * @param k constant token multiplier - it increases the number of tokens * that each member of the DAO has with respect to their lambda * @param elasticity the percentage by which capitalDelta (cost of entering the DAO) * should increase on every join * @param lambda outstanding shares * @param m - lambda modifier - it's value increases every time someone joins the DAO * * lambdaDash = deltaLambda + lambda * mDash = ( lambdaDash / lambda ) * m * deltaE = capitalDelta * k * ( lambdaDash * mDash * ( 1 + elasticity ) - lambda * m ) * @return uint256 */ function deltaE( uint256 deltaLambda, uint256 capitalDeltaValue, uint256 k, uint256 elasticity, uint256 lambda, uint256 m ) internal pure returns (uint256) { uint256 lambdaDash = SafeMath.add(deltaLambda, lambda); return wmul( wmul(capitalDeltaValue, k), SafeMath.sub( wmul(lambdaDash, wmul(mDash(lambdaDash, lambda, m), revamp(elasticity))), wmul(lambda, m) ) ); } /** * @dev calculates the lambda value given t, k, & m * @param tokens t value; number of tokens for which lambda should be calculated * @param k constant token multiplier - it increases the number of tokens * that each member of the DAO has with respect to their lambda * @param m - lambda modifier - it's value increases every time someone joins the DAO * * lambda = t / ( m * k) * @return uint256 */ function lambdaFromT( uint256 tokens, uint256 k, uint256 m ) internal pure returns (uint256) { return wdiv(tokens, wmul(k, m)); } /** * @dev calculates the future share modifier given the future value of * lambda (lambdaDash), the current value of lambda, and the current share modifier * @param m current share modifier * @param lambda current outstanding shares * @param lambdaDash future outstanding shares * * mDash = ( lambdaDash / lambda ) * m * @return uint256 */ function mDash( uint256 lambdaDash, uint256 lambda, uint256 m ) internal pure returns (uint256) { return wmul(wdiv(lambdaDash, lambda), m); } /** * @dev calculates the value of revamp * @param elasticity the percentage by which capitalDelta should increase * * revamp = 1 + elasticity * @return uint256 */ function revamp(uint256 elasticity) internal pure returns (uint256) { return SafeMath.add(elasticity, 1000000000000000000); } /** * @dev calculates the number of tokens represented by lambda given k & m * @param lambda shares * @param k a constant, initially set by the DAO * @param m share modifier * * t = lambda * m * k * @return uint256 */ function t( uint256 lambda, uint256 k, uint256 m ) internal view returns (uint256) { if (lambda == 0) { return 0; } return wmul(wmul(lambda, k), m); } /** * @dev multiplies two float values, required since solidity does not handle * floating point values * * inspiration: https://github.com/dapphub/ds-math/blob/master/src/math.sol * * @return uint256 */ function wmul(uint256 a, uint256 b) internal pure returns (uint256) { return SafeMath.div( SafeMath.add(SafeMath.mul(a, b), SafeMath.div(1000000000000000000, 2)), 1000000000000000000 ); } /** * @dev divides two float values, required since solidity does not handle * floating point values. * * inspiration: https://github.com/dapphub/ds-math/blob/master/src/math.sol * * @return uint256 */ function wdiv(uint256 a, uint256 b) internal pure returns (uint256) { return SafeMath.div(SafeMath.add(SafeMath.mul(a, 1000000000000000000), SafeMath.div(b, 2)), b); } } // SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; pragma experimental ABIEncoderV2; import '../interfaces/IUniswapV2Pair.sol'; import '../libraries/ElasticMath.sol'; import '../models/DAO.sol'; import '../models/Ecosystem.sol'; import '../models/Token.sol'; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import '@pie-dao/proxy/contracts/PProxy.sol'; import 'hardhat/console.sol'; /** * @dev The ElasticDAO contract outlines and defines all the functionality * such as initialize, Join, exit, etc for an elasticDAO. * * It also serves as the vault for ElasticDAO. */ contract ElasticDAO is ReentrancyGuard { address public deployer; address public ecosystemModelAddress; address public controller; address[] public summoners; address[] public liquidityPools; bool public initialized; event ElasticGovernanceTokenDeployed(address indexed tokenAddress); event MaxVotingLambdaChanged(uint256 value); event ControllerChanged(address value); event ExitDAO(address indexed memberAddress, uint256 shareAmount, uint256 ethAmount); event FailedToFullyPenalize( address indexed memberAddress, uint256 attemptedAmount, uint256 actualAmount ); event JoinDAO(address indexed memberAddress, uint256 shareAmount, uint256 ethAmount); event LiquidityPoolAdded(address indexed poolAddress); event LiquidityPoolRemoved(address indexed poolAddress); event SeedDAO(address indexed summonerAddress, uint256 amount); event SummonedDAO(address indexed summonedBy); modifier onlyAfterSummoning() { DAO.Instance memory dao = _getDAO(); require(dao.summoned, 'ElasticDAO: DAO must be summoned'); _; } modifier onlyAfterTokenInitialized() { Ecosystem.Instance memory ecosystem = _getEcosystem(); bool tokenInitialized = Token(ecosystem.tokenModelAddress).exists( ecosystem.governanceTokenAddress, ecosystem.daoAddress ); require(tokenInitialized, 'ElasticDAO: Please call initializeToken first'); _; } modifier onlyBeforeSummoning() { DAO.Instance memory dao = _getDAO(); require(dao.summoned == false, 'ElasticDAO: DAO must not be summoned'); _; } modifier onlyController() { require(msg.sender == controller, 'ElasticDAO: Only controller'); _; } modifier onlyDeployer() { require(msg.sender == deployer, 'ElasticDAO: Only deployer'); _; } modifier onlySummoners() { Ecosystem.Instance memory ecosystem = _getEcosystem(); DAO daoContract = DAO(ecosystem.daoModelAddress); DAO.Instance memory dao = daoContract.deserialize(address(this), ecosystem); bool summonerCheck = daoContract.isSummoner(dao, msg.sender); require(summonerCheck, 'ElasticDAO: Only summoners'); _; } modifier onlyWhenOpen() { require(address(this).balance > 0, 'ElasticDAO: This DAO is closed'); _; } /** * @notice Initializes and builds the ElasticDAO struct * * @param _ecosystemModelAddress - the address of the ecosystem model * @param _controller the address which can control the core DAO functions * @param _summoners - an array containing the addresses of the summoners * @param _name - the name of the DAO * @param _maxVotingLambda - the maximum amount of lambda that can be used to vote in the DAO * * @dev * Requirements: * - The DAO cannot already be initialized * - The ecosystem model address cannot be the zero address * - The DAO must have atleast one summoner to summon the DAO */ function initialize( address _ecosystemModelAddress, address _controller, address[] memory _summoners, string memory _name, uint256 _maxVotingLambda ) external nonReentrant { require(initialized == false, 'ElasticDAO: Already initialized'); require( _ecosystemModelAddress != address(0) && _controller != address(0), 'ElasticDAO: Address Zero' ); require(_summoners.length > 0, 'ElasticDAO: At least 1 summoner required'); for (uint256 i = 0; i < _summoners.length; i += 1) { if (_summoners[i] == address(0)) { revert('ElasticDAO: Summoner address can not be zero address'); } } controller = _controller; deployer = msg.sender; summoners = _summoners; Ecosystem.Instance memory defaults = Ecosystem(_ecosystemModelAddress).deserialize(address(0)); Ecosystem.Instance memory ecosystem = _buildEcosystem(controller, defaults); ecosystemModelAddress = ecosystem.ecosystemModelAddress; bool success = _buildDAO(_summoners, _name, _maxVotingLambda, ecosystem); initialized = true; require(success, 'ElasticDAO: Build DAO Failed'); } function addLiquidityPool(address _poolAddress) external onlyController nonReentrant returns (bool) { liquidityPools.push(_poolAddress); emit LiquidityPoolAdded(_poolAddress); } /** * @notice initializes the token of the DAO * * @param _name - name of the token * @param _symbol - symbol of the token * @param _eByL -the amount of lambda a summoner gets(per ETH) during the seeding phase of the DAO * @param _elasticity the value by which the cost of entering the DAO increases ( on every join ) * @param _k - is the constant token multiplier * it increases the number of tokens that each member of the DAO has with respect to their lambda * @param _maxLambdaPurchase - is the maximum amount of lambda that can be purchased per wallet * * @dev emits ElasticGovernanceTokenDeployed event * @dev * Requirements: * - Only the deployer of the DAO can initialize the Token */ function initializeToken( string memory _name, string memory _symbol, uint256 _eByL, uint256 _elasticity, uint256 _k, uint256 _maxLambdaPurchase ) external onlyBeforeSummoning onlyDeployer nonReentrant { Ecosystem.Instance memory ecosystem = _getEcosystem(); Token.Instance memory token = _buildToken( controller, _name, _symbol, _eByL, _elasticity, _k, _maxLambdaPurchase, ecosystem ); emit ElasticGovernanceTokenDeployed(token.uuid); } /** * @notice this function is to be used for exiting the DAO * for the underlying ETH value of _deltaLambda * * The eth value of _deltaLambda is calculated using: * * eth to be transfered = ( deltaLambda/lambda ) * totalEthInTheDAO * * @param _deltaLambda - the amount of lambda the address exits with * * Requirement: * - ETH transfer must be successful * @dev emits ExitDAO event */ function exit(uint256 _deltaLambda) external onlyAfterSummoning nonReentrant { // burn the shares Token.Instance memory token = _getToken(); ElasticGovernanceToken tokenContract = ElasticGovernanceToken(token.uuid); // eth to be transfered = ( deltaLambda/lambda ) * totalEthInTheDAO uint256 ratioOfShares = ElasticMath.wdiv(_deltaLambda, token.lambda); uint256 ethToBeTransfered = ElasticMath.wmul(ratioOfShares, address(this).balance); // transfer the eth tokenContract.burnShares(msg.sender, _deltaLambda); (bool success, ) = msg.sender.call{ value: ethToBeTransfered }(''); require(success, 'ElasticDAO: Exit Failed'); emit ExitDAO(msg.sender, _deltaLambda, ethToBeTransfered); } /** * @notice this function returns the length of the liquidity pools array * */ function getLiquidityPoolCount() public view returns (uint256) { return liquidityPools.length; } /** * @notice this function is used to join the DAO after it has been summoned * Joining the DAO is syntactically equal to minting _deltaLambda for the function caller. * * Based on the current state of the DAO, capitalDelta, deltaE, mDash are calulated, * after which maxTokenLambda is minted for the address calling the function. * * @dev documentation and further math regarding capitalDelta, deltaE, * mDash can be found at ../libraries/ElasticMath.sol * @dev emits the JoinDAO event * * @dev Requirements: * (The value of maxLambdaPurchase is set during the initialzing of the DAO) * The correct value of ETH, calculated via deltaE, * must be sent in the transaction by the calling address * The token contract should be successfully be able to mint token.makxLambdaPurchase */ function join() external payable onlyAfterSummoning onlyWhenOpen nonReentrant { Token.Instance memory token = _getToken(); ElasticGovernanceToken tokenContract = ElasticGovernanceToken(token.uuid); uint256 capitalDelta = ElasticMath.capitalDelta( // the current totalBalance of the DAO is inclusive of msg.value, // capitalDelta is to be calculated without the msg.value SafeMath.sub(address(this).balance, msg.value), tokenContract.totalSupply() ); uint256 deltaE = ElasticMath.deltaE( token.maxLambdaPurchase, capitalDelta, token.k, token.elasticity, token.lambda, token.m ); require(msg.value >= deltaE, 'ElasticDAO: Incorrect ETH amount'); // mdash uint256 lambdaDash = SafeMath.add(token.maxLambdaPurchase, token.lambda); uint256 mDash = ElasticMath.mDash(lambdaDash, token.lambda, token.m); // serialize the token Ecosystem.Instance memory ecosystem = _getEcosystem(); Token tokenStorage = Token(ecosystem.tokenModelAddress); token.m = mDash; tokenStorage.serialize(token); // tokencontract mint shares bool success = tokenContract.mintShares(msg.sender, token.maxLambdaPurchase); require(success, 'ElasticDAO: Mint Shares Failed during Join'); for (uint256 i = 0; i < liquidityPools.length; i += 1) { IUniswapV2Pair(liquidityPools[i]).sync(); } // return extra ETH if (success && msg.value > deltaE) { (success, ) = msg.sender.call{ value: SafeMath.sub(msg.value, deltaE) }(''); require(success, 'ElasticDAO: TransactionFailed'); } emit JoinDAO(msg.sender, token.maxLambdaPurchase, msg.value); } /** * @notice penalizes @param _addresses with @param _amounts respectively * * @param _addresses - an array of addresses * @param _amounts - an array containing the amounts each address has to be penalized respectively * * @dev Requirement: * - Each address must have a corresponding amount to be penalized with */ function penalize(address[] memory _addresses, uint256[] memory _amounts) external onlyController nonReentrant { require( _addresses.length == _amounts.length, 'ElasticDAO: An amount is required for each address' ); ElasticGovernanceToken tokenContract = ElasticGovernanceToken(_getToken().uuid); for (uint256 i = 0; i < _addresses.length; i += 1) { uint256 lambda = tokenContract.balanceOfInShares(_addresses[i]); if (lambda < _amounts[i]) { if (lambda != 0) { tokenContract.burnShares(_addresses[i], lambda); } FailedToFullyPenalize(_addresses[i], _amounts[i], lambda); } else { tokenContract.burnShares(_addresses[i], _amounts[i]); } } } function removeLiquidityPool(address _poolAddress) external onlyController nonReentrant returns (bool) { for (uint256 i = 0; i < liquidityPools.length; i += 1) { if (liquidityPools[i] == _poolAddress) { liquidityPools[i] = liquidityPools[liquidityPools.length - 1]; liquidityPools.pop(); } } emit LiquidityPoolRemoved(_poolAddress); } /** * @notice rewards @param _addresess with @param _amounts respectively * * @param _addresses - an array of addresses * @param _amounts - an array containing the amounts each address has to be rewarded respectively * * @dev Requirement: * - Each address must have a corresponding amount to be rewarded with */ function reward(address[] memory _addresses, uint256[] memory _amounts) external onlyController nonReentrant { require( _addresses.length == _amounts.length, 'ElasticDAO: An amount is required for each address' ); ElasticGovernanceToken tokenContract = ElasticGovernanceToken(_getToken().uuid); for (uint256 i = 0; i < _addresses.length; i += 1) { tokenContract.mintShares(_addresses[i], _amounts[i]); } } /** * @notice sets the controller of the DAO, * The controller of the DAO handles various responsibilities of the DAO, * such as burning and minting tokens on behalf of the DAO * * @param _controller - the new address of the controller of the DAO * * @dev emits ControllerChanged event * @dev Requirements: * - The controller must not be the 0 address * - The controller of the DAO should successfully be set as the burner of the tokens of the DAO * - The controller of the DAO should successfully be set as the minter of the tokens of the DAO */ function setController(address _controller) external onlyController nonReentrant { require(_controller != address(0), 'ElasticDAO: Address Zero'); controller = _controller; // Update minter / burner ElasticGovernanceToken tokenContract = ElasticGovernanceToken(_getToken().uuid); bool success = tokenContract.setBurner(controller); require(success, 'ElasticDAO: Set Burner failed during setController'); success = tokenContract.setMinter(controller); require(success, 'ElasticDAO: Set Minter failed during setController'); emit ControllerChanged(controller); } /** * @notice sets the max voting lambda value for the DAO * @param _maxVotingLambda - the value of the maximum amount of lambda that can be used for voting * @dev emits MaxVotingLambdaChanged event */ function setMaxVotingLambda(uint256 _maxVotingLambda) external onlyController nonReentrant { Ecosystem.Instance memory ecosystem = _getEcosystem(); DAO daoStorage = DAO(ecosystem.daoModelAddress); DAO.Instance memory dao = daoStorage.deserialize(address(this), ecosystem); dao.maxVotingLambda = _maxVotingLambda; daoStorage.serialize(dao); emit MaxVotingLambdaChanged(_maxVotingLambda); } /** * @notice seeds the DAO, * Essentially transferring of ETH by a summoner address, in return for lambda is seeding the DAO, * The lambda receieved is given by: * Lambda = Eth / eByL * * @dev seeding of the DAO occurs after the DAO has been initialized, * and before the DAO has been summoned * @dev emits the SeedDAO event */ function seedSummoning() external payable onlyBeforeSummoning onlySummoners onlyAfterTokenInitialized nonReentrant { Token.Instance memory token = _getToken(); uint256 deltaE = msg.value; uint256 deltaLambda = ElasticMath.wdiv(deltaE, token.eByL); ElasticGovernanceToken(token.uuid).mintShares(msg.sender, deltaLambda); emit SeedDAO(msg.sender, deltaLambda); } /** * @notice summons the DAO, * Summoning the DAO results in all summoners getting _deltaLambda * after which people can enter the DAO using the join function * * @param _deltaLambda - the amount of lambda each summoner address receives * * @dev emits SummonedDAO event * @dev Requirement: * The DAO must be seeded with ETH during the seeding phase * (This is to facilitate capitalDelta calculations after the DAO has been summoned). * * @dev documentation and further math regarding capitalDelta * can be found at ../libraries/ElasticMath.sol */ function summon(uint256 _deltaLambda) external onlyBeforeSummoning onlySummoners nonReentrant { require(address(this).balance > 0, 'ElasticDAO: Please seed DAO with ETH to set ETH:EGT ratio'); Ecosystem.Instance memory ecosystem = _getEcosystem(); DAO daoContract = DAO(ecosystem.daoModelAddress); DAO.Instance memory dao = daoContract.deserialize(address(this), ecosystem); Token.Instance memory token = Token(ecosystem.tokenModelAddress).deserialize(ecosystem.governanceTokenAddress, ecosystem); ElasticGovernanceToken tokenContract = ElasticGovernanceToken(token.uuid); // number of summoners can not grow unboundly. it is fixed limit. for (uint256 i = 0; i < dao.numberOfSummoners; i += 1) { tokenContract.mintShares(daoContract.getSummoner(dao, i), _deltaLambda); } dao.summoned = true; daoContract.serialize(dao); emit SummonedDAO(msg.sender); } // Getters function getDAO() external view returns (DAO.Instance memory) { return _getDAO(); } function getEcosystem() external view returns (Ecosystem.Instance memory) { return _getEcosystem(); } /** * @dev creates DAO.Instance record * @param _summoners addresses of the summoners * @param _name name of the DAO * @param _ecosystem instance of Ecosystem the DAO uses * @param _maxVotingLambda - the maximum amount of lambda that can be used to vote in the DAO * @return bool true */ function _buildDAO( address[] memory _summoners, string memory _name, uint256 _maxVotingLambda, Ecosystem.Instance memory _ecosystem ) internal returns (bool) { DAO daoStorage = DAO(_ecosystem.daoModelAddress); DAO.Instance memory dao; dao.uuid = address(this); dao.ecosystem = _ecosystem; dao.maxVotingLambda = _maxVotingLambda; dao.name = _name; dao.summoned = false; dao.summoners = _summoners; daoStorage.serialize(dao); return true; } /** * @dev Deploys proxies leveraging the implementation contracts found on the * default Ecosystem.Instance record. * @param _controller the address which can control the core DAO functions * @param _defaults instance of Ecosystem with the implementation addresses * @return ecosystem Ecosystem.Instance */ function _buildEcosystem(address _controller, Ecosystem.Instance memory _defaults) internal returns (Ecosystem.Instance memory ecosystem) { ecosystem.daoAddress = address(this); ecosystem.daoModelAddress = _deployProxy(_defaults.daoModelAddress, _controller); ecosystem.ecosystemModelAddress = _deployProxy(_defaults.ecosystemModelAddress, _controller); ecosystem.governanceTokenAddress = _deployProxy(_defaults.governanceTokenAddress, _controller); ecosystem.tokenHolderModelAddress = _deployProxy( _defaults.tokenHolderModelAddress, _controller ); ecosystem.tokenModelAddress = _deployProxy(_defaults.tokenModelAddress, _controller); Ecosystem(ecosystem.ecosystemModelAddress).serialize(ecosystem); return ecosystem; } /** * @dev creates a Token.Instance record and initializes the ElasticGovernanceToken. * @param _controller the address which can control the core DAO functions * @param _name name of the token * @param _symbol symbol of the token * @param _eByL initial ETH/token ratio * @param _elasticity the percentage by which capitalDelta should increase * @param _k a constant, initially set by the DAO * @param _maxLambdaPurchase maximum amount of lambda (shares) that can be * minted on each call to the join function in ElasticDAO.sol * @param _ecosystem the DAO's ecosystem instance * @return token Token.Instance */ function _buildToken( address _controller, string memory _name, string memory _symbol, uint256 _eByL, uint256 _elasticity, uint256 _k, uint256 _maxLambdaPurchase, Ecosystem.Instance memory _ecosystem ) internal returns (Token.Instance memory token) { token.eByL = _eByL; token.ecosystem = _ecosystem; token.elasticity = _elasticity; token.k = _k; token.lambda = 0; token.m = 1000000000000000000; token.maxLambdaPurchase = _maxLambdaPurchase; token.name = _name; token.symbol = _symbol; token.uuid = _ecosystem.governanceTokenAddress; // initialize the token within the ecosystem return ElasticGovernanceToken(token.uuid).initialize(_controller, _controller, _ecosystem, token); } function _deployProxy(address _implementationAddress, address _owner) internal returns (address) { PProxy proxy = new PProxy(); proxy.setImplementation(_implementationAddress); proxy.setProxyOwner(_owner); return address(proxy); } // Private function _getDAO() internal view returns (DAO.Instance memory) { Ecosystem.Instance memory ecosystem = _getEcosystem(); return DAO(ecosystem.daoModelAddress).deserialize(address(this), ecosystem); } function _getEcosystem() internal view returns (Ecosystem.Instance memory) { return Ecosystem(ecosystemModelAddress).deserialize(address(this)); } function _getToken() internal view returns (Token.Instance memory) { Ecosystem.Instance memory ecosystem = _getEcosystem(); return Token(ecosystem.tokenModelAddress).deserialize(ecosystem.governanceTokenAddress, ecosystem); } receive() external payable {} fallback() external payable {} } // SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; pragma experimental ABIEncoderV2; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import './Ecosystem.sol'; import './EternalModel.sol'; /** * @author ElasticDAO - https://ElasticDAO.org * @notice This contract is used for storing core DAO data * @dev ElasticDAO network contracts can read/write from this contract */ contract DAO is EternalModel, ReentrancyGuard { struct Instance { address uuid; address[] summoners; bool summoned; string name; uint256 maxVotingLambda; uint256 numberOfSummoners; Ecosystem.Instance ecosystem; } event Serialized(address indexed uuid); /** * @dev deserializes Instance struct * @param _uuid - address of the unique user ID * @return record Instance */ function deserialize(address _uuid, Ecosystem.Instance memory _ecosystem) external view returns (Instance memory record) { record.uuid = _uuid; record.ecosystem = _ecosystem; if (_exists(_uuid)) { record.maxVotingLambda = getUint(keccak256(abi.encode(_uuid, 'maxVotingLambda'))); record.name = getString(keccak256(abi.encode(_uuid, 'name'))); record.numberOfSummoners = getUint(keccak256(abi.encode(_uuid, 'numberOfSummoners'))); record.summoned = getBool(keccak256(abi.encode(_uuid, 'summoned'))); } return record; } /** * @dev checks if @param _uuid exists * @param _uuid - address of the unique user ID * @return recordExists bool */ function exists(address _uuid) external view returns (bool) { return _exists(_uuid); } function getSummoner(Instance memory _dao, uint256 _index) external view returns (address) { return getAddress(keccak256(abi.encode(_dao.uuid, 'summoners', _index))); } /** * @dev checks if @param _uuid where _uuid is msg.sender - is a Summoner * @param _dao DAO.Instance * @param _summonerAddress address * @return bool */ function isSummoner(Instance memory _dao, address _summonerAddress) external view returns (bool) { return getBool(keccak256(abi.encode(_dao.uuid, 'summoner', _summonerAddress))); } /** * @dev serializes Instance struct * @param _record Instance */ function serialize(Instance memory _record) external nonReentrant { require(msg.sender == _record.uuid, 'ElasticDAO: Unauthorized'); setUint(keccak256(abi.encode(_record.uuid, 'maxVotingLambda')), _record.maxVotingLambda); setString(keccak256(abi.encode(_record.uuid, 'name')), _record.name); setBool(keccak256(abi.encode(_record.uuid, 'summoned')), _record.summoned); if (_record.summoners.length > 0) { _record.numberOfSummoners = _record.summoners.length; setUint(keccak256(abi.encode(_record.uuid, 'numberOfSummoners')), _record.numberOfSummoners); for (uint256 i = 0; i < _record.numberOfSummoners; i += 1) { setBool(keccak256(abi.encode(_record.uuid, 'summoner', _record.summoners[i])), true); setAddress(keccak256(abi.encode(_record.uuid, 'summoners', i)), _record.summoners[i]); } } setBool(keccak256(abi.encode(_record.uuid, 'exists')), true); emit Serialized(_record.uuid); } function _exists(address _uuid) internal view returns (bool) { return getBool(keccak256(abi.encode(_uuid, 'exists'))); } } // SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; pragma experimental ABIEncoderV2; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import './EternalModel.sol'; /** * @title ElasticDAO ecosystem * @author ElasticDAO - https://ElasticDAO.org * @notice This contract is used for storing core dao data * @dev ElasticDAO network contracts can read/write from this contract * @dev Serialize - Translation of data from the concerned struct to key-value pairs * @dev Deserialize - Translation of data from the key-value pairs to a struct */ contract Ecosystem is EternalModel, ReentrancyGuard { struct Instance { address daoAddress; // Models address daoModelAddress; address ecosystemModelAddress; address tokenHolderModelAddress; address tokenModelAddress; // Tokens address governanceTokenAddress; } event Serialized(address indexed _daoAddress); /** * @dev deserializes Instance struct * @param _daoAddress - address of the unique user ID * @return record Instance */ function deserialize(address _daoAddress) external view returns (Instance memory record) { if (_exists(_daoAddress)) { record.daoAddress = _daoAddress; record.daoModelAddress = getAddress( keccak256(abi.encode(record.daoAddress, 'daoModelAddress')) ); record.ecosystemModelAddress = address(this); record.governanceTokenAddress = getAddress( keccak256(abi.encode(record.daoAddress, 'governanceTokenAddress')) ); record.tokenHolderModelAddress = getAddress( keccak256(abi.encode(record.daoAddress, 'tokenHolderModelAddress')) ); record.tokenModelAddress = getAddress( keccak256(abi.encode(record.daoAddress, 'tokenModelAddress')) ); } return record; } /** * @dev checks if @param _daoAddress * @param _daoAddress - address of the unique user ID * @return recordExists bool */ function exists(address _daoAddress) external view returns (bool recordExists) { return _exists(_daoAddress); } /** * @dev serializes Instance struct * @param _record Instance */ function serialize(Instance memory _record) external nonReentrant { bool recordExists = _exists(_record.daoAddress); require( msg.sender == _record.daoAddress || (_record.daoAddress == address(0) && !recordExists), 'ElasticDAO: Unauthorized' ); setAddress( keccak256(abi.encode(_record.daoAddress, 'daoModelAddress')), _record.daoModelAddress ); setAddress( keccak256(abi.encode(_record.daoAddress, 'governanceTokenAddress')), _record.governanceTokenAddress ); setAddress( keccak256(abi.encode(_record.daoAddress, 'tokenHolderModelAddress')), _record.tokenHolderModelAddress ); setAddress( keccak256(abi.encode(_record.daoAddress, 'tokenModelAddress')), _record.tokenModelAddress ); setBool(keccak256(abi.encode(_record.daoAddress, 'exists')), true); emit Serialized(_record.daoAddress); } function _exists(address _daoAddress) internal view returns (bool recordExists) { return getBool(keccak256(abi.encode(_daoAddress, 'exists'))); } } // SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; pragma experimental ABIEncoderV2; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import './Ecosystem.sol'; import './EternalModel.sol'; import '../tokens/ElasticGovernanceToken.sol'; /** * @title A data storage for EGT (Elastic Governance Token) * @notice More info about EGT could be found in ./tokens/ElasticGovernanceToken.sol * @notice This contract is used for storing token data * @dev ElasticDAO network contracts can read/write from this contract * Serialize - Translation of data from the concerned struct to key-value pairs * Deserialize - Translation of data from the key-value pairs to a struct */ contract Token is EternalModel, ReentrancyGuard { struct Instance { address uuid; string name; string symbol; uint256 eByL; uint256 elasticity; uint256 k; uint256 lambda; uint256 m; uint256 maxLambdaPurchase; uint256 numberOfTokenHolders; Ecosystem.Instance ecosystem; } event Serialized(address indexed uuid); /** * @dev deserializes Instance struct * @param _uuid - address of the unique user ID * @return record Instance */ function deserialize(address _uuid, Ecosystem.Instance memory _ecosystem) external view returns (Instance memory record) { record.uuid = _uuid; record.ecosystem = _ecosystem; if (_exists(_uuid, _ecosystem.daoAddress)) { record.eByL = getUint(keccak256(abi.encode(_uuid, record.ecosystem.daoAddress, 'eByL'))); record.elasticity = getUint( keccak256(abi.encode(_uuid, record.ecosystem.daoAddress, 'elasticity')) ); record.k = getUint(keccak256(abi.encode(_uuid, record.ecosystem.daoAddress, 'k'))); record.lambda = getUint(keccak256(abi.encode(_uuid, record.ecosystem.daoAddress, 'lambda'))); record.m = getUint(keccak256(abi.encode(_uuid, record.ecosystem.daoAddress, 'm'))); record.maxLambdaPurchase = getUint( keccak256(abi.encode(_uuid, record.ecosystem.daoAddress, 'maxLambdaPurchase')) ); record.name = getString(keccak256(abi.encode(_uuid, record.ecosystem.daoAddress, 'name'))); record.numberOfTokenHolders = getUint( keccak256(abi.encode(_uuid, record.ecosystem.daoAddress, 'numberOfTokenHolders')) ); record.symbol = getString( keccak256(abi.encode(_uuid, record.ecosystem.daoAddress, 'symbol')) ); } return record; } function exists(address _uuid, address _daoAddress) external view returns (bool) { return _exists(_uuid, _daoAddress); } /** * @dev serializes Instance struct * @param _record Instance */ function serialize(Instance memory _record) external nonReentrant { require( msg.sender == _record.uuid || (msg.sender == _record.ecosystem.daoAddress && _exists(_record.uuid, _record.ecosystem.daoAddress)), 'ElasticDAO: Unauthorized' ); setString( keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'name')), _record.name ); setString( keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'symbol')), _record.symbol ); setUint( keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'eByL')), _record.eByL ); setUint( keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'elasticity')), _record.elasticity ); setUint(keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'k')), _record.k); setUint( keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'lambda')), _record.lambda ); setUint(keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'm')), _record.m); setUint( keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'maxLambdaPurchase')), _record.maxLambdaPurchase ); setBool(keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'exists')), true); emit Serialized(_record.uuid); } function updateNumberOfTokenHolders(Instance memory _record, uint256 numberOfTokenHolders) external nonReentrant { require( msg.sender == _record.uuid && _exists(_record.uuid, _record.ecosystem.daoAddress), 'ElasticDAO: Unauthorized' ); setUint( keccak256(abi.encode(_record.uuid, _record.ecosystem.daoAddress, 'numberOfTokenHolders')), numberOfTokenHolders ); } function _exists(address _uuid, address _daoAddress) internal view returns (bool) { return getBool(keccak256(abi.encode(_uuid, _daoAddress, 'exists'))); } } // SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; pragma experimental ABIEncoderV2; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import './Ecosystem.sol'; import './EternalModel.sol'; import './Token.sol'; /** * @title a data storage for Token holders * @author ElasticDAO - https://ElasticDAO.org * @notice This contract is used for storing token data * @dev ElasticDAO network contracts can read/write from this contract * Serialize - Translation of data from the concerned struct to key-value pairs * Deserialize - Translation of data from the key-value pairs to a struct */ contract TokenHolder is EternalModel, ReentrancyGuard { struct Instance { address account; uint256 lambda; Ecosystem.Instance ecosystem; Token.Instance token; } event Serialized(address indexed account, address indexed token); function deserialize( address _account, Ecosystem.Instance memory _ecosystem, Token.Instance memory _token ) external view returns (Instance memory record) { record.account = _account; record.ecosystem = _ecosystem; record.token = _token; if (_exists(_account, _token)) { record.lambda = getUint(keccak256(abi.encode(record.token.uuid, record.account, 'lambda'))); } return record; } function exists(address _account, Token.Instance memory _token) external view returns (bool) { return _exists(_account, _token); } /** * @dev serializes Instance struct * @param _record Instance */ function serialize(Instance memory _record) external nonReentrant { require(msg.sender == _record.token.uuid, 'ElasticDAO: Unauthorized'); setUint(keccak256(abi.encode(_record.token.uuid, _record.account, 'lambda')), _record.lambda); setBool(keccak256(abi.encode(_record.token.uuid, _record.account, 'exists')), true); emit Serialized(_record.account, _record.token.uuid); } function _exists(address _account, Token.Instance memory _token) internal view returns (bool) { return getBool(keccak256(abi.encode(_token.uuid, _account, 'exists'))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity 0.7.2; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, 'SafeMath: addition overflow'); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, 'SafeMath: subtraction overflow'); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, 'SafeMath: multiplication overflow'); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; require(c > 0, 'SafeMath: division by zero'); return c; } } // SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; interface IUniswapV2Pair { function sync() external; } pragma solidity ^0.7.1; import "./PProxyStorage.sol"; contract PProxy is PProxyStorage { bytes32 constant IMPLEMENTATION_SLOT = keccak256(abi.encodePacked("IMPLEMENTATION_SLOT")); bytes32 constant OWNER_SLOT = keccak256(abi.encodePacked("OWNER_SLOT")); modifier onlyProxyOwner() { require(msg.sender == readAddress(OWNER_SLOT), "PProxy.onlyProxyOwner: msg sender not owner"); _; } constructor () public { setAddress(OWNER_SLOT, msg.sender); } function getProxyOwner() public view returns (address) { return readAddress(OWNER_SLOT); } function setProxyOwner(address _newOwner) onlyProxyOwner public { setAddress(OWNER_SLOT, _newOwner); } function getImplementation() public view returns (address) { return readAddress(IMPLEMENTATION_SLOT); } function setImplementation(address _newImplementation) onlyProxyOwner public { setAddress(IMPLEMENTATION_SLOT, _newImplementation); } fallback () external payable { return internalFallback(); } function internalFallback() internal virtual { address contractAddr = readAddress(IMPLEMENTATION_SLOT); assembly { let ptr := mload(0x40) calldatacopy(ptr, 0, calldatasize()) let result := delegatecall(gas(), contractAddr, ptr, calldatasize(), 0, 0) let size := returndatasize() returndatacopy(ptr, 0, size) switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: GPLv3 pragma solidity 0.7.2; pragma experimental ABIEncoderV2; /** * @title Implementation of Eternal Storage for ElasticDAO - * - (https://fravoll.github.io/solidity-patterns/eternal_storage.html) * @author ElasticDAO - https://ElasticDAO.org * @notice This contract is used for storing contract network data * @dev ElasticDAO network contracts can read/write from this contract */ contract EternalModel { struct Storage { mapping(bytes32 => address) addressStorage; mapping(bytes32 => bool) boolStorage; mapping(bytes32 => bytes) bytesStorage; mapping(bytes32 => int256) intStorage; mapping(bytes32 => string) stringStorage; mapping(bytes32 => uint256) uIntStorage; } Storage internal s; /** * @notice Getter Functions */ /** * @notice Gets stored contract data in unit256 format * @param _key bytes32 location should be keccak256 and abi.encodePacked * @return uint256 _value from storage _key location */ function getUint(bytes32 _key) internal view returns (uint256) { return s.uIntStorage[_key]; } /** * @notice Get stored contract data in string format * @param _key bytes32 location should be keccak256 and abi.encodePacked * @return string _value from storage _key location */ function getString(bytes32 _key) internal view returns (string memory) { return s.stringStorage[_key]; } /** * @notice Get stored contract data in address format * @param _key bytes32 location should be keccak256 and abi.encodePacked * @return address _value from storage _key location */ function getAddress(bytes32 _key) internal view returns (address) { return s.addressStorage[_key]; } /** * @notice Get stored contract data in bool format * @param _key bytes32 location should be keccak256 and abi.encodePacked * @return bool _value from storage _key location */ function getBool(bytes32 _key) internal view returns (bool) { return s.boolStorage[_key]; } /** * @notice Setters Functions */ /** * @notice Store contract data in uint256 format * @dev restricted to latest ElasticDAO Networks contracts * @param _key bytes32 location should be keccak256 and abi.encodePacked * @param _value uint256 value */ function setUint(bytes32 _key, uint256 _value) internal { s.uIntStorage[_key] = _value; } /** * @notice Store contract data in string format * @dev restricted to latest ElasticDAO Networks contracts * @param _key bytes32 location should be keccak256 and abi.encodePacked * @param _value string value */ function setString(bytes32 _key, string memory _value) internal { s.stringStorage[_key] = _value; } /** * @notice Store contract data in address format * @dev restricted to latest ElasticDAO Networks contracts * @param _key bytes32 location should be keccak256 and abi.encodePacked * @param _value address value */ function setAddress(bytes32 _key, address _value) internal { s.addressStorage[_key] = _value; } /** * @notice Store contract data in bool format * @dev restricted to latest ElasticDAO Networks contracts * @param _key bytes32 location should be keccak256 and abi.encodePacked * @param _value bool value */ function setBool(bytes32 _key, bool _value) internal { s.boolStorage[_key] = _value; } } pragma solidity ^0.7.1; contract PProxyStorage { function readBool(bytes32 _key) public view returns(bool) { return storageRead(_key) == bytes32(uint256(1)); } function setBool(bytes32 _key, bool _value) internal { if(_value) { storageSet(_key, bytes32(uint256(1))); } else { storageSet(_key, bytes32(uint256(0))); } } function readAddress(bytes32 _key) public view returns(address) { return bytes32ToAddress(storageRead(_key)); } function setAddress(bytes32 _key, address _value) internal { storageSet(_key, addressToBytes32(_value)); } function storageRead(bytes32 _key) public view returns(bytes32) { bytes32 value; //solium-disable-next-line security/no-inline-assembly assembly { value := sload(_key) } return value; } function storageSet(bytes32 _key, bytes32 _value) internal { // targetAddress = _address; // No! bytes32 implAddressStorageKey = _key; //solium-disable-next-line security/no-inline-assembly assembly { sstore(implAddressStorageKey, _value) } } function bytes32ToAddress(bytes32 _value) public pure returns(address) { return address(uint160(uint256(_value))); } function addressToBytes32(address _value) public pure returns(bytes32) { return bytes32(uint256(_value)); } }
Initializes and builds the ElasticDAO struct _ecosystemModelAddress - the address of the ecosystem model _controller the address which can control the core DAO functions _summoners - an array containing the addresses of the summoners _name - the name of the DAO _maxVotingLambda - the maximum amount of lambda that can be used to vote in the DAO Requirements: - The DAO cannot already be initialized - The ecosystem model address cannot be the zero address - The DAO must have atleast one summoner to summon the DAO/
function initialize( address _ecosystemModelAddress, address _controller, address[] memory _summoners, string memory _name, uint256 _maxVotingLambda ) external nonReentrant { require(initialized == false, 'ElasticDAO: Already initialized'); require( _ecosystemModelAddress != address(0) && _controller != address(0), 'ElasticDAO: Address Zero' ); require(_summoners.length > 0, 'ElasticDAO: At least 1 summoner required'); for (uint256 i = 0; i < _summoners.length; i += 1) { if (_summoners[i] == address(0)) { revert('ElasticDAO: Summoner address can not be zero address'); } } controller = _controller; deployer = msg.sender; summoners = _summoners; Ecosystem.Instance memory defaults = Ecosystem(_ecosystemModelAddress).deserialize(address(0)); Ecosystem.Instance memory ecosystem = _buildEcosystem(controller, defaults); ecosystemModelAddress = ecosystem.ecosystemModelAddress; bool success = _buildDAO(_summoners, _name, _maxVotingLambda, ecosystem); initialized = true; require(success, 'ElasticDAO: Build DAO Failed'); }
10,474,416
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (governance/Governor.sol) pragma solidity ^0.8.0; import "../utils/cryptography/ECDSA.sol"; import "../utils/cryptography/draft-EIP712.sol"; import "../utils/introspection/ERC165.sol"; import "../utils/math/SafeCast.sol"; import "../utils/Address.sol"; import "../utils/Context.sol"; import "./IGovernor.sol"; /** * @dev Core of the governance system, designed to be extended though various modules. * * This contract is abstract and requires several function to be implemented in various modules: * * - A counting module must implement {quorum}, {_quorumReached}, {_voteSucceeded} and {_countVote} * - A voting module must implement {getVotes} * - Additionaly, the {votingPeriod} must also be implemented * * _Available since v4.3._ */ abstract contract Governor is Context, ERC165, EIP712, IGovernor { using SafeCast for uint256; bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)"); struct ProposalCore { address author; string description; bool exists; } uint256[] private _proposalIds; string private _name; bool private _canceled; mapping(uint256 => ProposalCore) private _proposals; mapping(address => uint256) private _numSubmissions; /** * @dev Restrict access of functions to the governance executor, which may be the Governor itself or a timelock * contract, as specified by {_executor}. This generally means that function with this modifier must be voted on and * executed through the governance protocol. */ modifier onlyGovernance() { require(_msgSender() == _executor(), "Governor: onlyGovernance"); _; } /** * @dev Sets the value for {name} and {version} */ constructor(string memory name_) EIP712(name_, version()) { _name = name_; } /** * @dev Function to receive ETH that will be handled by the governor (disabled if executor is a third party contract) */ receive() external payable virtual { require(_executor() == address(this)); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) { return interfaceId == type(IGovernor).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IGovernor-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IGovernor-version}. */ function version() public view virtual override returns (string memory) { return "1"; } /** * @dev See {IGovernor-hashProposal}. * * The proposal id is produced by hashing the RLC encoded `targets` array, the `values` array, the `calldatas` array * and the descriptionHash (bytes32 which itself is the keccak256 hash of the description string). This proposal id * can be produced from the proposal data which is part of the {ProposalCreated} event. It can even be computed in * advance, before the proposal is submitted. * * Note that the chainId and the governor address are not part of the proposal id computation. Consequently, the * same proposal (with same operation and same description) will have the same id if submitted on multiple governors * accross multiple networks. This also means that in order to execute the same operation twice (on the same * governor) the proposer will have to change the description in order to avoid proposal id conflicts. */ function hashProposal( string memory proposalDescription ) public pure virtual override returns (uint256) { return uint256(keccak256(abi.encode(proposalDescription))); } /** * @dev See {IGovernor-state}. */ function state() public view virtual override returns (ContestState) { if (_canceled) { return ContestState.Canceled; } uint256 voteStartTimestamp = voteStart(); if (voteStartTimestamp >= block.timestamp) { return ContestState.Queued; } uint256 deadlineTimestamp = contestDeadline(); if (deadlineTimestamp >= block.timestamp) { return ContestState.Active; } return ContestState.Completed; } /** * @dev Return all proposals. */ function getAllProposalIds() public view virtual returns (uint256[] memory) { return _proposalIds; } /** * @dev See {IGovernor-voteStart}. */ function voteStart() public view virtual override returns (uint256) { return contestStart() + votingDelay(); } /** * @dev See {IGovernor-contestDeadline}. */ function contestDeadline() public view virtual override returns (uint256) { return voteStart() + votingPeriod(); } /** * @dev Part of the Governor Bravo's interface: _"The number of votes required in order for a voter to become a proposer"_. */ function proposalThreshold() public view virtual returns (uint256) { return 0; } /** * @dev _"The number of proposals that a proposer who meets the proposalThreshold can submit for this contest"_. */ function numAllowedProposalSubmissions() public view virtual returns (uint256) { return 1; } /** * @dev Max number of proposals allowed in this contest */ function maxProposalCount() public view virtual returns (uint256) { return 100; } /** * @dev Retrieve proposal data"_. */ function getProposal(uint256 proposalId) public view virtual returns (ProposalCore memory) { return _proposals[proposalId]; } /** * @dev Get the number of proposal submissions for a given address. */ function getNumSubmissions(address account) public view virtual returns (uint256) { return _numSubmissions[account]; } /** * @dev Register a vote with a given support and voting weight. * * Note: Support is generic and can represent various things depending on the voting system used. */ function _countVote( uint256 proposalId, address account, uint8 support, uint256 numVotes, uint256 totalVotes ) internal virtual; /** * @dev See {IGovernor-propose}. */ function propose( string memory proposalDescription ) public virtual override returns (uint256) { require(state() == ContestState.Queued, "Governor: contest must be queued for proposals to be submitted"); require(_numSubmissions[msg.sender] < numAllowedProposalSubmissions(), "Governor: the same cannot submit more than the numAllowedProposalSubmissions for this contest"); require(_proposalIds.length < maxProposalCount(), "Governor: the max number of proposals have been submitted"); require( getCurrentVotes(msg.sender) >= proposalThreshold(), "GovernorCompatibilityBravo: proposer votes below proposal threshold" ); require(bytes(proposalDescription).length != 0, "Governor: empty proposal"); uint256 proposalId = hashProposal(proposalDescription); require(!_proposals[proposalId].exists, "Governor: duplicate proposals not allowed"); _proposalIds.push(proposalId); _proposals[proposalId] = ProposalCore({author: msg.sender, description: proposalDescription, exists: true}); _numSubmissions[msg.sender] += 1; emit ProposalCreated( proposalId, proposalDescription, _msgSender() ); return proposalId; } /** * @dev Delete proposals. * * Emits a {IGovernor-ProposalsDeleted} event. */ function deleteProposals(uint256[] memory proposalIds) public virtual { require(msg.sender == creator()); for(uint index=0; index<proposalIds.length; index++){ _proposals[proposalIds[index]].description = "This proposal has been deleted by the creator of the contest."; } emit ProposalsDeleted(proposalIds); } /** * @dev * * Emits a {IGovernor-ContestCanceled} event. */ function cancel() public virtual { require(msg.sender == creator()); ContestState status = state(); require( status != ContestState.Canceled && status != ContestState.Completed, "Governor: contest not active" ); _canceled = true; emit ContestCanceled(); } /** * @dev See {IGovernor-castVote}. */ function castVote(uint256 proposalId, uint8 support, uint256 numVotes) public virtual override returns (uint256) { address voter = _msgSender(); return _castVote(proposalId, voter, support, numVotes, ""); } /** * @dev See {IGovernor-castVoteWithReason}. */ function castVoteWithReason( uint256 proposalId, uint8 support, uint256 numVotes, string calldata reason ) public virtual override returns (uint256) { address voter = _msgSender(); return _castVote(proposalId, voter, support, numVotes, reason); } /** * @dev See {IGovernor-castVoteBySig}. */ function castVoteBySig( uint256 proposalId, uint8 support, uint256 numVotes, uint8 v, bytes32 r, bytes32 s ) public virtual override returns (uint256) { address voter = ECDSA.recover( _hashTypedDataV4(keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support))), v, r, s ); return _castVote(proposalId, voter, support, numVotes, ""); } /** * @dev Internal vote casting mechanism: Check that the vote is pending, that it has not been cast yet, retrieve * voting weight using {IGovernor-getVotes} and call the {_countVote} internal function. * * Emits a {IGovernor-VoteCast} event. */ function _castVote( uint256 proposalId, address account, uint8 support, uint256 numVotes, string memory reason ) internal virtual returns (uint256) { require(state() == ContestState.Active, "Governor: vote not currently active"); require(numVotes > 0, "GovernorVotingSimple: cannot vote with 0 or fewer votes"); uint256 totalVotes = getVotes(account, contestSnapshot()); require(totalVotes > 0, "GovernorVotingSimple: you must have greater than 0 delegated votes at the snapshot in order to vote"); _countVote(proposalId, account, support, numVotes, totalVotes); emit VoteCast(account, proposalId, support, numVotes, reason); return totalVotes; } /** * @dev Address through which the governor executes action. Will be overloaded by module that execute actions * through another contract such as a timelock. */ function _executor() internal view virtual returns (address) { return address(this); } }
See {IGovernor-contestDeadline}./
function contestDeadline() public view virtual override returns (uint256) { return voteStart() + votingPeriod(); }
12,635,395
// SPDX-License-Identifier: GPL-3.0-or-later // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "../../../solidity-utils/contracts/openzeppelin/EnumerableMap.sol"; import "../../../solidity-utils/contracts/openzeppelin/ReentrancyGuard.sol"; import "../../../solidity-utils/contracts/helpers/ERC20Helpers.sol"; import "../../../solidity-utils/contracts/helpers/WordCodec.sol"; import "../BaseWeightedPool.sol"; import "../WeightedPoolUserData.sol"; import "./WeightCompression.sol"; /** * @dev Weighted Pool with mutable tokens and weights, designed to be used in conjunction with a pool controller * contract (as the owner, containing any specific business logic). Since the pool itself permits "dangerous" * operations, it should never be deployed with an EOA as the owner. * * Pool controllers can add functionality: for example, allow the effective "owner" to be transferred to another * address. (The actual pool owner is still immutable, set to the pool controller contract.) Another pool owner * might allow fine-grained permissioning of protected operations: perhaps a multisig can add/remove tokens, but * a third-party EOA is allowed to set the swap fees. * * Pool controllers might also impose limits on functionality so that operations that might endanger LPs can be * performed more safely. For instance, the pool by itself places no restrictions on the duration of a gradual * weight change, but a pool controller might restrict this in various ways, from a simple minimum duration, * to a more complex rate limit. * * Pool controllers can also serve as intermediate contracts to hold tokens, deploy timelocks, consult with other * protocols or on-chain oracles, or bundle several operations into one transaction that re-entrancy protection * would prevent initiating from the pool contract. * * Managed Pools and their controllers are designed to support many asset management use cases, including: large * token counts, rebalancing through token changes, gradual weight or fee updates, circuit breakers for * IL-protection, and more. */ contract ManagedPool is BaseWeightedPool, ReentrancyGuard { // solhint-disable not-rely-on-time using FixedPoint for uint256; using WordCodec for bytes32; using WeightCompression for uint256; using WeightedPoolUserData for bytes; using EnumerableMap for EnumerableMap.IERC20ToUint256Map; // State variables // The upper bound is WeightedMath.MAX_WEIGHTED_TOKENS, but this is constrained by other factors, such as Pool // creation gas consumption. uint256 private constant _MAX_MANAGED_TOKENS = 50; // Percentage of swap fees that are allocated to the Pool owner. uint256 private immutable _managementSwapFeePercentage; uint256 private constant _MAX_MANAGEMENT_SWAP_FEE_PERCENTAGE = 1e18; // 100% // Use the _miscData slot in BasePool // First 64 bits are reserved for the swap fee // // Store non-token-based values: // Start/end timestamps for gradual weight update // Cache total tokens // [ 64 bits | 119 bits | 1 bit | 32 bits | 32 bits | 7 bits | 1 bit ] // [ reserved | unused | restrict LP | end time | start time | total tokens | swap flag ] // |MSB LSB| uint256 private constant _SWAP_ENABLED_OFFSET = 0; uint256 private constant _TOTAL_TOKENS_OFFSET = 1; uint256 private constant _START_TIME_OFFSET = 8; uint256 private constant _END_TIME_OFFSET = 40; uint256 private constant _MUST_ALLOWLIST_LPS_OFFSET = 72; // 7 bits is enough for the token count, since _MAX_MANAGED_TOKENS is 50 // Store scaling factor and start/end weights for each token // Mapping should be more efficient than trying to compress it further // [ 155 bits| 5 bits | 32 bits | 64 bits | // [ unused | decimals | end weight | start weight | // |MSB LSB| mapping(IERC20 => bytes32) private _tokenState; EnumerableMap.IERC20ToUint256Map private _tokenCollectedManagementFees; uint256 private constant _START_WEIGHT_OFFSET = 0; uint256 private constant _END_WEIGHT_OFFSET = 64; uint256 private constant _DECIMAL_DIFF_OFFSET = 96; // If mustAllowlistLPs is enabled, this is the list of addresses allowed to join the pool mapping(address => bool) private _allowedAddresses; // Event declarations event GradualWeightUpdateScheduled( uint256 startTime, uint256 endTime, uint256[] startWeights, uint256[] endWeights ); event SwapEnabledSet(bool swapEnabled); event MustAllowlistLPsSet(bool mustAllowlistLPs); event ManagementFeePercentageChanged(uint256 managementFeePercentage); event ManagementFeesCollected(IERC20[] tokens, uint256[] amounts); event AllowlistAddressAdded(address indexed member); event AllowlistAddressRemoved(address indexed member); struct NewPoolParams { IVault vault; string name; string symbol; IERC20[] tokens; uint256[] normalizedWeights; address[] assetManagers; uint256 swapFeePercentage; uint256 pauseWindowDuration; uint256 bufferPeriodDuration; address owner; bool swapEnabledOnStart; bool mustAllowlistLPs; uint256 managementSwapFeePercentage; } constructor(NewPoolParams memory params) BaseWeightedPool( params.vault, params.name, params.symbol, params.tokens, params.assetManagers, params.swapFeePercentage, params.pauseWindowDuration, params.bufferPeriodDuration, params.owner ) { uint256 totalTokens = params.tokens.length; InputHelpers.ensureInputLengthMatch(totalTokens, params.normalizedWeights.length, params.assetManagers.length); _setMiscData(_getMiscData().insertUint7(totalTokens, _TOTAL_TOKENS_OFFSET)); // Double check it fits in 7 bits _require(_getTotalTokens() == totalTokens, Errors.MAX_TOKENS); // This must be inlined in the constructor as we're setting an immutable variable. _require( params.managementSwapFeePercentage <= _MAX_MANAGEMENT_SWAP_FEE_PERCENTAGE, Errors.MAX_MANAGEMENT_SWAP_FEE_PERCENTAGE ); uint256 currentTime = block.timestamp; _startGradualWeightChange( currentTime, currentTime, params.normalizedWeights, params.normalizedWeights, params.tokens ); // Initialize the accrued management fees map with the Pool's tokens and zero collected fees. for (uint256 i = 0; i < totalTokens; ++i) { _tokenCollectedManagementFees.set(params.tokens[i], 0); } // If false, the pool will start in the disabled state (prevents front-running the enable swaps transaction). _setSwapEnabled(params.swapEnabledOnStart); // If true, only addresses on the manager-controlled allowlist may join the pool. _setMustAllowlistLPs(params.mustAllowlistLPs); _managementSwapFeePercentage = params.managementSwapFeePercentage; emit ManagementFeePercentageChanged(params.managementSwapFeePercentage); } /** * @dev Returns true if swaps are enabled. */ function getSwapEnabled() public view returns (bool) { return _getMiscData().decodeBool(_SWAP_ENABLED_OFFSET); } /** * @dev Returns true if the allowlist for LPs is enabled. */ function getMustAllowlistLPs() public view returns (bool) { return _getMiscData().decodeBool(_MUST_ALLOWLIST_LPS_OFFSET); } /** * @dev Verifies that a given address is allowed to hold tokens. */ function isAllowedAddress(address member) public view returns (bool) { return !getMustAllowlistLPs() || _allowedAddresses[member]; } /** * @dev Returns the management swap fee percentage as a 18-decimals fixed point number. */ function getManagementSwapFeePercentage() public view returns (uint256) { return _managementSwapFeePercentage; } /** * @dev Return start time, end time, and endWeights as an array. * Current weights should be retrieved via `getNormalizedWeights()`. */ function getGradualWeightUpdateParams() external view returns ( uint256 startTime, uint256 endTime, uint256[] memory endWeights ) { // Load current pool state from storage bytes32 poolState = _getMiscData(); startTime = poolState.decodeUint32(_START_TIME_OFFSET); endTime = poolState.decodeUint32(_END_TIME_OFFSET); (IERC20[] memory tokens, , ) = getVault().getPoolTokens(getPoolId()); uint256 totalTokens = tokens.length; endWeights = new uint256[](totalTokens); for (uint256 i = 0; i < totalTokens; i++) { endWeights[i] = _tokenState[tokens[i]].decodeUint32(_END_WEIGHT_OFFSET).uncompress32(); } } function _getMaxTokens() internal pure virtual override returns (uint256) { return _MAX_MANAGED_TOKENS; } function _getTotalTokens() internal view virtual override returns (uint256) { return _getMiscData().decodeUint7(_TOTAL_TOKENS_OFFSET); } /** * @dev Schedule a gradual weight change, from the current weights to the given endWeights, * over startTime to endTime. */ function updateWeightsGradually( uint256 startTime, uint256 endTime, uint256[] memory endWeights ) external authenticate whenNotPaused nonReentrant { InputHelpers.ensureInputLengthMatch(_getTotalTokens(), endWeights.length); // If the start time is in the past, "fast forward" to start now // This avoids discontinuities in the weight curve. Otherwise, if you set the start/end times with // only 10% of the period in the future, the weights would immediately jump 90% uint256 currentTime = block.timestamp; startTime = Math.max(currentTime, startTime); _require(startTime <= endTime, Errors.GRADUAL_UPDATE_TIME_TRAVEL); (IERC20[] memory tokens, , ) = getVault().getPoolTokens(getPoolId()); _startGradualWeightChange(startTime, endTime, _getNormalizedWeights(), endWeights, tokens); } function getCollectedManagementFees() public view returns (IERC20[] memory tokens, uint256[] memory collectedFees) { tokens = new IERC20[](_getTotalTokens()); collectedFees = new uint256[](_getTotalTokens()); for (uint256 i = 0; i < _getTotalTokens(); ++i) { // We can use unchecked getters as we know the map has the same size (and order!) as the Pool's tokens. (IERC20 token, uint256 fees) = _tokenCollectedManagementFees.unchecked_at(i); tokens[i] = token; collectedFees[i] = fees; } _downscaleDownArray(collectedFees, _scalingFactors()); } function withdrawCollectedManagementFees(address recipient) external authenticate whenNotPaused nonReentrant { (IERC20[] memory tokens, uint256[] memory collectedFees) = getCollectedManagementFees(); getVault().exitPool( getPoolId(), address(this), payable(recipient), IVault.ExitPoolRequest({ assets: _asIAsset(tokens), minAmountsOut: collectedFees, userData: abi.encode(WeightedPoolUserData.ExitKind.MANAGEMENT_FEE_TOKENS_OUT), toInternalBalance: false }) ); // Technically collectedFees is the minimum amount, not the actual amount. However, since no fees will be // collected during the exit, it will also be the actual amount. emit ManagementFeesCollected(tokens, collectedFees); } /** * @dev Adds an address to the allowlist. */ function addAllowedAddress(address member) external authenticate whenNotPaused { _require(getMustAllowlistLPs(), Errors.UNAUTHORIZED_OPERATION); _require(!_allowedAddresses[member], Errors.ADDRESS_ALREADY_ALLOWLISTED); _allowedAddresses[member] = true; emit AllowlistAddressAdded(member); } /** * @dev Removes an address from the allowlist. */ function removeAllowedAddress(address member) external authenticate whenNotPaused { _require(_allowedAddresses[member], Errors.ADDRESS_NOT_ALLOWLISTED); delete _allowedAddresses[member]; emit AllowlistAddressRemoved(member); } /** * @dev Can enable/disable the LP allowlist. Note that any addresses added to the allowlist * will be retained if the allowlist is toggled off and back on again. */ function setMustAllowlistLPs(bool mustAllowlistLPs) external authenticate whenNotPaused { _setMustAllowlistLPs(mustAllowlistLPs); } function _setMustAllowlistLPs(bool mustAllowlistLPs) private { _setMiscData(_getMiscData().insertBool(mustAllowlistLPs, _MUST_ALLOWLIST_LPS_OFFSET)); emit MustAllowlistLPsSet(mustAllowlistLPs); } /** * @dev Can enable/disable trading */ function setSwapEnabled(bool swapEnabled) external authenticate whenNotPaused { _setSwapEnabled(swapEnabled); } function _setSwapEnabled(bool swapEnabled) private { _setMiscData(_getMiscData().insertBool(swapEnabled, _SWAP_ENABLED_OFFSET)); emit SwapEnabledSet(swapEnabled); } function _scalingFactor(IERC20 token) internal view virtual override returns (uint256) { return _readScalingFactor(_getTokenData(token)); } function _scalingFactors() internal view virtual override returns (uint256[] memory scalingFactors) { (IERC20[] memory tokens, , ) = getVault().getPoolTokens(getPoolId()); uint256 numTokens = tokens.length; scalingFactors = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { scalingFactors[i] = _readScalingFactor(_tokenState[tokens[i]]); } } function _getNormalizedWeight(IERC20 token) internal view override returns (uint256) { uint256 pctProgress = _calculateWeightChangeProgress(); bytes32 tokenData = _getTokenData(token); return _interpolateWeight(tokenData, pctProgress); } function _getNormalizedWeights() internal view override returns (uint256[] memory normalizedWeights) { (IERC20[] memory tokens, , ) = getVault().getPoolTokens(getPoolId()); uint256 numTokens = tokens.length; normalizedWeights = new uint256[](numTokens); uint256 pctProgress = _calculateWeightChangeProgress(); for (uint256 i = 0; i < numTokens; i++) { bytes32 tokenData = _tokenState[tokens[i]]; normalizedWeights[i] = _interpolateWeight(tokenData, pctProgress); } } function _getNormalizedWeightsAndMaxWeightIndex() internal view override returns (uint256[] memory normalizedWeights, uint256 maxWeightTokenIndex) { normalizedWeights = _getNormalizedWeights(); maxWeightTokenIndex = 0; uint256 maxNormalizedWeight = normalizedWeights[0]; for (uint256 i = 1; i < normalizedWeights.length; i++) { if (normalizedWeights[i] > maxNormalizedWeight) { maxWeightTokenIndex = i; maxNormalizedWeight = normalizedWeights[i]; } } } // Swap overrides - revert unless swaps are enabled function _onSwapGivenIn( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) internal override returns (uint256) { _require(getSwapEnabled(), Errors.SWAPS_DISABLED); return super._onSwapGivenIn(swapRequest, currentBalanceTokenIn, currentBalanceTokenOut); } function _onSwapGivenOut( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) internal override returns (uint256) { _require(getSwapEnabled(), Errors.SWAPS_DISABLED); return super._onSwapGivenOut(swapRequest, currentBalanceTokenIn, currentBalanceTokenOut); } /** * @dev Used to adjust balances by subtracting all collected fees from them, as if they had been withdrawn from the * Vault. */ function _subtractCollectedFees(uint256[] memory balances) private view { for (uint256 i = 0; i < _getTotalTokens(); ++i) { // We can use unchecked getters as we know the map has the same size (and order!) as the Pool's tokens. balances[i] = balances[i].sub(_tokenCollectedManagementFees.unchecked_valueAt(i)); } } // We override _onJoinPool and _onExitPool as we need to not compute the current invariant and calculate protocol // fees, since that mechanism does not work for Pools in which the weights change over time. Instead, this Pool // always pays zero protocol fees. // Additionally, we also check that only non-swap join and exit kinds are allowed while swaps are disabled. function getLastInvariant() public pure override returns (uint256) { _revert(Errors.UNHANDLED_BY_MANAGED_POOL); } function _onJoinPool( bytes32, address sender, address, uint256[] memory balances, uint256, uint256, uint256[] memory scalingFactors, bytes memory userData ) internal virtual override whenNotPaused // All joins are disabled while the contract is paused. returns ( uint256 bptAmountOut, uint256[] memory amountsIn, uint256[] memory dueProtocolFeeAmounts ) { // If swaps are disabled, the only join kind that is allowed is the proportional one, as all others involve // implicit swaps and alter token prices. _require( getSwapEnabled() || userData.joinKind() == WeightedPoolUserData.JoinKind.ALL_TOKENS_IN_FOR_EXACT_BPT_OUT, Errors.INVALID_JOIN_EXIT_KIND_WHILE_SWAPS_DISABLED ); // Check allowlist for LPs, if applicable _require(isAllowedAddress(sender), Errors.ADDRESS_NOT_ALLOWLISTED); _subtractCollectedFees(balances); (bptAmountOut, amountsIn) = _doJoin(balances, _getNormalizedWeights(), scalingFactors, userData); dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); } function _onExitPool( bytes32, address sender, address, uint256[] memory balances, uint256, uint256, uint256[] memory scalingFactors, bytes memory userData ) internal virtual override returns ( uint256 bptAmountIn, uint256[] memory amountsOut, uint256[] memory dueProtocolFeeAmounts ) { // Exits are not completely disabled while the contract is paused: proportional exits (exact BPT in for tokens // out) remain functional. // If swaps are disabled, the only exit kind that is allowed is the proportional one (as all others involve // implicit swaps and alter token prices) and management fee collection (as there's no point in restricting // that). WeightedPoolUserData.ExitKind kind = userData.exitKind(); _require( getSwapEnabled() || kind == WeightedPoolUserData.ExitKind.EXACT_BPT_IN_FOR_TOKENS_OUT || kind == WeightedPoolUserData.ExitKind.MANAGEMENT_FEE_TOKENS_OUT, Errors.INVALID_JOIN_EXIT_KIND_WHILE_SWAPS_DISABLED ); _subtractCollectedFees(balances); (bptAmountIn, amountsOut) = _doManagedPoolExit( sender, balances, _getNormalizedWeights(), scalingFactors, userData ); dueProtocolFeeAmounts = new uint256[](_getTotalTokens()); } function _doManagedPoolExit( address sender, uint256[] memory balances, uint256[] memory normalizedWeights, uint256[] memory scalingFactors, bytes memory userData ) internal returns (uint256, uint256[] memory) { WeightedPoolUserData.ExitKind kind = userData.exitKind(); if (kind == WeightedPoolUserData.ExitKind.MANAGEMENT_FEE_TOKENS_OUT) { return _exitManagerFeeTokensOut(sender); } else { return _doExit(balances, normalizedWeights, scalingFactors, userData); } } function _exitManagerFeeTokensOut(address sender) private whenNotPaused returns (uint256 bptAmountIn, uint256[] memory amountsOut) { // This exit function is disabled if the contract is paused. // This exit function can only be called by the Pool itself - the authorization logic that governs when that // call can be made resides in withdrawCollectedManagementFees. _require(sender == address(this), Errors.UNAUTHORIZED_EXIT); // Since what we're doing is sending out collected management fees, we don't require any BPT in exchange: we // simply send those funds over. bptAmountIn = 0; amountsOut = new uint256[](_getTotalTokens()); for (uint256 i = 0; i < _getTotalTokens(); ++i) { // We can use unchecked getters and setters as we know the map has the same size (and order!) as the Pool's // tokens. amountsOut[i] = _tokenCollectedManagementFees.unchecked_valueAt(i); _tokenCollectedManagementFees.unchecked_setAt(i, 0); } } function _tokenAddressToIndex(IERC20 token) internal view override returns (uint256) { return _tokenCollectedManagementFees.indexOf(token, Errors.INVALID_TOKEN); } function _processSwapFeeAmount(uint256 index, uint256 amount) internal virtual override { if (amount > 0) { uint256 managementFeeAmount = amount.mulDown(_managementSwapFeePercentage); uint256 previousCollectedFees = _tokenCollectedManagementFees.unchecked_valueAt(index); _tokenCollectedManagementFees.unchecked_setAt(index, previousCollectedFees.add(managementFeeAmount)); } super._processSwapFeeAmount(index, amount); } // Pool swap hook override - subtract collected fees from all token amounts. We do this here as the original // `onSwap` does quite a bit of work, including computing swap fees, so we need to intercept that. function onSwap( SwapRequest memory swapRequest, uint256 currentBalanceTokenIn, uint256 currentBalanceTokenOut ) public override returns (uint256) { uint256 tokenInUpscaledCollectedFees = _tokenCollectedManagementFees.get( swapRequest.tokenIn, Errors.INVALID_TOKEN ); uint256 adjustedBalanceTokenIn = currentBalanceTokenIn.sub( _downscaleDown(tokenInUpscaledCollectedFees, _scalingFactor(swapRequest.tokenIn)) ); uint256 tokenOutUpscaledCollectedFees = _tokenCollectedManagementFees.get( swapRequest.tokenOut, Errors.INVALID_TOKEN ); uint256 adjustedBalanceTokenOut = currentBalanceTokenOut.sub( _downscaleDown(tokenOutUpscaledCollectedFees, _scalingFactor(swapRequest.tokenOut)) ); return super.onSwap(swapRequest, adjustedBalanceTokenIn, adjustedBalanceTokenOut); } /** * @dev When calling updateWeightsGradually again during an update, reset the start weights to the current weights, * if necessary. Time travel elements commented out. */ function _startGradualWeightChange( uint256 startTime, uint256 endTime, uint256[] memory startWeights, uint256[] memory endWeights, IERC20[] memory tokens ) internal virtual { uint256 normalizedSum = 0; bytes32 tokenState; for (uint256 i = 0; i < endWeights.length; i++) { uint256 endWeight = endWeights[i]; _require(endWeight >= WeightedMath._MIN_WEIGHT, Errors.MIN_WEIGHT); IERC20 token = tokens[i]; // Tokens with more than 18 decimals are not supported // Scaling calculations must be exact/lossless // Store decimal difference instead of actual scaling factor _tokenState[token] = tokenState .insertUint64(startWeights[i].compress64(), _START_WEIGHT_OFFSET) .insertUint32(endWeight.compress32(), _END_WEIGHT_OFFSET) .insertUint5(uint256(18).sub(ERC20(address(token)).decimals()), _DECIMAL_DIFF_OFFSET); normalizedSum = normalizedSum.add(endWeight); } // Ensure that the normalized weights sum to ONE _require(normalizedSum == FixedPoint.ONE, Errors.NORMALIZED_WEIGHT_INVARIANT); _setMiscData( _getMiscData().insertUint32(startTime, _START_TIME_OFFSET).insertUint32(endTime, _END_TIME_OFFSET) ); emit GradualWeightUpdateScheduled(startTime, endTime, startWeights, endWeights); } function _readScalingFactor(bytes32 tokenState) private pure returns (uint256) { uint256 decimalsDifference = tokenState.decodeUint5(_DECIMAL_DIFF_OFFSET); return FixedPoint.ONE * 10**decimalsDifference; } /** * @dev Extend ownerOnly functions to include the Managed Pool control functions. */ function _isOwnerOnlyAction(bytes32 actionId) internal view override returns (bool) { return (actionId == getActionId(ManagedPool.updateWeightsGradually.selector)) || (actionId == getActionId(ManagedPool.setSwapEnabled.selector)) || (actionId == getActionId(ManagedPool.withdrawCollectedManagementFees.selector)) || (actionId == getActionId(ManagedPool.addAllowedAddress.selector)) || (actionId == getActionId(ManagedPool.removeAllowedAddress.selector)) || (actionId == getActionId(ManagedPool.setMustAllowlistLPs.selector)) || super._isOwnerOnlyAction(actionId); } /** * @dev Returns a fixed-point number representing how far along the current weight change is, where 0 means the * change has not yet started, and FixedPoint.ONE means it has fully completed. */ function _calculateWeightChangeProgress() private view returns (uint256) { uint256 currentTime = block.timestamp; bytes32 poolState = _getMiscData(); uint256 startTime = poolState.decodeUint32(_START_TIME_OFFSET); uint256 endTime = poolState.decodeUint32(_END_TIME_OFFSET); if (currentTime >= endTime) { return FixedPoint.ONE; } else if (currentTime <= startTime) { return 0; } uint256 totalSeconds = endTime - startTime; uint256 secondsElapsed = currentTime - startTime; // In the degenerate case of a zero duration change, consider it completed (and avoid division by zero) return secondsElapsed.divDown(totalSeconds); } function _interpolateWeight(bytes32 tokenData, uint256 pctProgress) private pure returns (uint256 finalWeight) { uint256 startWeight = tokenData.decodeUint64(_START_WEIGHT_OFFSET).uncompress64(); uint256 endWeight = tokenData.decodeUint32(_END_WEIGHT_OFFSET).uncompress32(); if (pctProgress == 0 || startWeight == endWeight) return startWeight; if (pctProgress >= FixedPoint.ONE) return endWeight; if (startWeight > endWeight) { uint256 weightDelta = pctProgress.mulDown(startWeight - endWeight); return startWeight - weightDelta; } else { uint256 weightDelta = pctProgress.mulDown(endWeight - startWeight); return startWeight + weightDelta; } } function _getTokenData(IERC20 token) private view returns (bytes32 tokenData) { tokenData = _tokenState[token]; // A valid token can't be zero (must have non-zero weights) _require(tokenData != 0, Errors.INVALID_TOKEN); } }
Schedule a gradual weight change, from the current weights to the given endWeights, over startTime to endTime./ If the start time is in the past, "fast forward" to start now This avoids discontinuities in the weight curve. Otherwise, if you set the start/end times with only 10% of the period in the future, the weights would immediately jump 90%
function updateWeightsGradually( uint256 startTime, uint256 endTime, uint256[] memory endWeights ) external authenticate whenNotPaused nonReentrant { InputHelpers.ensureInputLengthMatch(_getTotalTokens(), endWeights.length); uint256 currentTime = block.timestamp; startTime = Math.max(currentTime, startTime); _require(startTime <= endTime, Errors.GRADUAL_UPDATE_TIME_TRAVEL); (IERC20[] memory tokens, , ) = getVault().getPoolTokens(getPoolId()); _startGradualWeightChange(startTime, endTime, _getNormalizedWeights(), endWeights, tokens); }
6,380,767
pragma solidity ^0.5.8; import "openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "openzeppelin-solidity/contracts/math/Math.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "solidity-bytes-utils/contracts/BytesLib.sol"; import "./IntegerSortedLinkedList.sol"; import "./UsingBondedDeposits.sol"; import "./interfaces/IGovernance.sol"; import "../stability/FractionUtil.sol"; import "../common/Initializable.sol"; // TODO(asa): Hardcode minimum times for queueExpiry, etc. /** * @title A contract for making, passing, and executing on-chain governance proposals. */ contract Governance is IGovernance, Ownable, Initializable, UsingBondedDeposits, ReentrancyGuard { using SafeMath for uint256; using FractionUtil for FractionUtil.Fraction; using IntegerSortedLinkedList for SortedLinkedList.List; using BytesLib for bytes; // TODO(asa): Consider a delay stage. enum ProposalStage { None, Queued, Approval, Referendum, Execution, Expiration } enum VoteValue { None, Abstain, No, Yes } struct VoteRecord { VoteValue value; uint256 proposalId; } struct Voter { // Key of the proposal voted for in the proposal queue uint256 upvotedProposal; uint256 mostRecentReferendumProposal; // Maps a `dequeued` index to a voter's vote record. mapping(uint256 => VoteRecord) referendumVotes; } // TODO(asa): Reduce storage usage here. struct VoteTotals { uint256 abstain; uint256 yes; uint256 no; } struct Transaction { uint256 value; address destination; bytes data; } struct Proposal { address proposer; uint256 deposit; uint256 timestamp; VoteTotals votes; Transaction[] transactions; bool approved; } struct ContractConstitution { FractionUtil.Fraction defaultThreshold; // Maps a function ID to a corresponding passing function, overriding the // default. mapping(bytes4 => FractionUtil.Fraction) functionThresholds; } struct StageDurations { uint256 approval; uint256 referendum; uint256 execution; } StageDurations public stageDurations; uint256 public queueExpiry; uint256 public dequeueFrequency; address public approver; uint256 public lastDequeue; uint256 public concurrentProposals; uint256 public proposalCount; uint256 public minDeposit; mapping(address => uint256) public refundedDeposits; mapping(address => ContractConstitution) private constitution; mapping(uint256 => Proposal) private proposals; mapping(address => Voter) public voters; SortedLinkedList.List private queue; uint256[] public dequeued; uint256[] public emptyIndices; event ApproverSet( address approver ); event ConcurrentProposalsSet( uint256 concurrentProposals ); event MinDepositSet( uint256 minDeposit ); event QueueExpirySet( uint256 queueExpiry ); event DequeueFrequencySet( uint256 dequeueFrequency ); event ApprovalStageDurationSet( uint256 approvalStageDuration ); event ReferendumStageDurationSet( uint256 referendumStageDuration ); event ExecutionStageDurationSet( uint256 executionStageDuration ); event ConstitutionSet( address indexed destination, bytes4 indexed functionId, uint256 numerator, uint256 denominator ); event ProposalQueued( uint256 indexed proposalId, address indexed proposer, uint256 transactionCount, uint256 deposit, uint256 timestamp ); event ProposalUpvoted( uint256 indexed proposalId, address indexed account, uint256 upvotes ); event ProposalUpvoteRevoked( uint256 indexed proposalId, address indexed account, uint256 revokedUpvotes ); event ProposalDequeued( uint256 indexed proposalId, uint256 timestamp ); event ProposalApproved( uint256 indexed proposalId ); event ProposalVoted( uint256 indexed proposalId, address indexed account, uint256 value, uint256 weight ); event ProposalExecuted( uint256 indexed proposalId ); event ProposalExpired( uint256 proposalId ); function() external payable {} // solhint-disable no-empty-blocks /** * @notice Initializes critical variables. * @param registryAddress The address of the registry contract. * @param _approver The address that needs to approve proposals to move to the referendum stage. * @param _concurrentProposals The number of proposals to dequeue at once. * @param _minDeposit The minimum Celo Gold deposit needed to make a proposal. * @param _queueExpiry The number of seconds a proposal can stay in the queue before expiring. * @param _dequeueFrequency The number of seconds before the next batch of proposals can be * dequeued. * @param approvalStageDuration The number of seconds the approver has to approve a proposal * after it is dequeued. * @param referendumStageDuration The number of seconds users have to vote on a dequeued proposal * after the approval stage ends. * @param executionStageDuration The number of seconds users have to execute a passed proposal * after the referendum stage ends. * @dev Should be called only once. */ function initialize( address registryAddress, address _approver, uint256 _concurrentProposals, uint256 _minDeposit, uint256 _queueExpiry, uint256 _dequeueFrequency, uint256 approvalStageDuration, uint256 referendumStageDuration, uint256 executionStageDuration ) external initializer { require( _approver != address(0) && _concurrentProposals != 0 && _minDeposit != 0 && _queueExpiry != 0 && _dequeueFrequency != 0 && approvalStageDuration != 0 && referendumStageDuration != 0 && executionStageDuration != 0 ); _transferOwnership(msg.sender); setRegistry(registryAddress); approver = _approver; concurrentProposals = _concurrentProposals; minDeposit = _minDeposit; queueExpiry = _queueExpiry; dequeueFrequency = _dequeueFrequency; stageDurations.approval = approvalStageDuration; stageDurations.referendum = referendumStageDuration; stageDurations.execution = executionStageDuration; // solhint-disable-next-line not-rely-on-time lastDequeue = now; } /** * @notice Updates the address that has permission to approve proposals in the approval stage. * @param _approver The address that has permission to approve proposals in the approval stage. */ function setApprover(address _approver) external onlyOwner { require(_approver != address(0) && _approver != approver); approver = _approver; emit ApproverSet(_approver); } /** * @notice Updates the number of proposals to dequeue at a time. * @param _concurrentProposals The number of proposals to dequeue at at a time. */ function setConcurrentProposals(uint256 _concurrentProposals) external onlyOwner { require(_concurrentProposals > 0 && _concurrentProposals != concurrentProposals); concurrentProposals = _concurrentProposals; emit ConcurrentProposalsSet(_concurrentProposals); } /** * @notice Updates the minimum deposit needed to make a proposal. * @param _minDeposit The minimum Celo Gold deposit needed to make a proposal. */ function setMinDeposit(uint256 _minDeposit) external onlyOwner { require(_minDeposit != minDeposit); minDeposit = _minDeposit; emit MinDepositSet(_minDeposit); } /** * @notice Updates the number of seconds before a queued proposal expires. * @param _queueExpiry The number of seconds a proposal can stay in the queue before expiring. */ function setQueueExpiry(uint256 _queueExpiry) external onlyOwner { require(_queueExpiry > 0 && _queueExpiry != queueExpiry); queueExpiry = _queueExpiry; emit QueueExpirySet(_queueExpiry); } /** * @notice Updates the minimum number of seconds before the next batch of proposals can be * dequeued. * @param _dequeueFrequency The number of seconds before the next batch of proposals can be * dequeued. */ function setDequeueFrequency(uint256 _dequeueFrequency) external onlyOwner { require(_dequeueFrequency > 0 && _dequeueFrequency != dequeueFrequency); dequeueFrequency = _dequeueFrequency; emit DequeueFrequencySet(_dequeueFrequency); } /** * @notice Updates the number of seconds proposals stay in the approval stage. * @param approvalStageDuration The number of seconds proposals stay in the approval stage. */ function setApprovalStageDuration(uint256 approvalStageDuration) external onlyOwner { require(approvalStageDuration > 0 && approvalStageDuration != stageDurations.approval); stageDurations.approval = approvalStageDuration; emit ApprovalStageDurationSet(approvalStageDuration); } /** * @notice Updates the number of seconds proposals stay in the referendum stage. * @param referendumStageDuration The number of seconds proposals stay in the referendum stage. */ function setReferendumStageDuration(uint256 referendumStageDuration) external onlyOwner { require(referendumStageDuration > 0 && referendumStageDuration != stageDurations.referendum); stageDurations.referendum = referendumStageDuration; emit ReferendumStageDurationSet(referendumStageDuration); } /** * @notice Updates the number of seconds proposals stay in the execution stage. * @param executionStageDuration The number of seconds proposals stay in the execution stage. */ function setExecutionStageDuration(uint256 executionStageDuration) external onlyOwner { require(executionStageDuration > 0 && executionStageDuration != stageDurations.execution); stageDurations.execution = executionStageDuration; emit ExecutionStageDurationSet(executionStageDuration); } /** * @notice Updates the ratio of yes:yes+no votes needed for a specific class of proposals to pass. * @param destination The destination of proposals for which this threshold should apply. * @param functionId The function ID of proposals for which this threshold should apply. Zero * will set the default. * @param numerator The numerator of the threshold. * @param denominator The denominator of the threshold. * @dev If no constitution is explicitly set the default is a simple majority, i.e. 1:2. */ function setConstitution( address destination, bytes4 functionId, uint256 numerator, uint256 denominator ) external onlyOwner { // TODO(asa): https://github.com/celo-org/celo-monorepo/pull/3414#discussion_r283588332 require(destination != address(0) && numerator > 0 && denominator > 0); FractionUtil.Fraction memory threshold = FractionUtil.Fraction(numerator, denominator); FractionUtil.Fraction memory majority = FractionUtil.Fraction(1, 2); FractionUtil.Fraction memory unanimous = FractionUtil.Fraction(1, 1); require(threshold.isGreaterThan(majority) && threshold.isLessThanOrEqualTo(unanimous)); if (functionId == 0) { constitution[destination].defaultThreshold = threshold; } else { constitution[destination].functionThresholds[functionId] = threshold; } emit ConstitutionSet(destination, functionId, numerator, denominator); } /** * @notice Creates a new proposal and adds it to end of the queue with no upvotes. * @param values The values of Celo Gold to be sent in the proposed transactions. * @param destinations The destination addresses of the proposed transactions. * @param data The concatenated data to be included in the proposed transactions. * @param dataLengths The lengths of each transaction's data. * @return The ID of the newly proposed proposal. * @dev The minimum deposit must be included with the proposal, returned if/when the proposal is * dequeued. */ function propose( uint256[] calldata values, address[] calldata destinations, bytes calldata data, uint256[] calldata dataLengths ) external payable returns (uint256) { dequeueProposalsIfReady(); require(msg.value >= minDeposit); require(values.length == destinations.length && destinations.length == dataLengths.length); uint256 transactionCount = values.length; proposalCount = proposalCount.add(1); Proposal storage proposal = proposals[proposalCount]; proposal.proposer = msg.sender; proposal.deposit = msg.value; // solhint-disable-next-line not-rely-on-time proposal.timestamp = now; uint256 dataPosition = 0; for (uint256 i = 0; i < transactionCount; i = i.add(1)) { proposal.transactions.push( Transaction(values[i], destinations[i], data.slice(dataPosition, dataLengths[i])) ); dataPosition = dataPosition.add(dataLengths[i]); } queue.push(proposalCount); // solhint-disable-next-line not-rely-on-time emit ProposalQueued(proposalCount, msg.sender, proposal.transactions.length, msg.value, now); return proposalCount; } /** * @notice Upvotes a queued proposal. * @param proposalId The ID of the proposal to upvote. * @param lesser The ID of the proposal that will be just behind `proposalId` in the queue. * @param greater The ID of the proposal that will be just ahead `proposalId` in the queue. * @return Whether or not the upvote was made successfully. * @dev Provide 0 for `lesser`/`greater` when the proposal will be at the tail/head of the queue. * @dev Reverts if the account has already upvoted a proposal in the queue. */ function upvote( uint256 proposalId, uint256 lesser, uint256 greater ) external nonReentrant returns (bool) { address account = getAccountFromVoter(msg.sender); require(!isVotingFrozen(account)); // TODO(asa): When upvoting a proposal that will get dequeued, should we let the tx succeed // and return false? dequeueProposalsIfReady(); // If acting on an expired proposal, expire the proposal and take no action. // solhint-disable-next-line not-rely-on-time if (queue.contains(proposalId) && now >= proposals[proposalId].timestamp.add(queueExpiry)) { queue.remove(proposalId); emit ProposalExpired(proposalId); return false; } Voter storage voter = voters[account]; // We can upvote a proposal in the queue if we're not already upvoting a proposal in the queue. uint256 weight = getAccountWeight(account); require( isQueued(proposalId) && (voter.upvotedProposal == 0 || !queue.contains(voter.upvotedProposal)) && weight > 0 ); uint256 upvotes = queue.getValue(proposalId).add(uint256(weight)); queue.update( proposalId, upvotes, lesser, greater ); voter.upvotedProposal = proposalId; emit ProposalUpvoted(proposalId, account, weight); return true; } /** * @notice Revokes an upvote on a queued proposal. * @param lesser The ID of the proposal that will be just behind the previously upvoted proposal * in the queue. * @param greater The ID of the proposal that will be just ahead of the previously upvoted * proposal in the queue. * @return Whether or not the upvote was revoked successfully. * @dev Provide 0 for `lesser`/`greater` when the proposal will be at the tail/head of the queue. */ function revokeUpvote( uint256 lesser, uint256 greater ) external nonReentrant returns (bool) { dequeueProposalsIfReady(); address account = getAccountFromVoter(msg.sender); Voter storage voter = voters[account]; uint256 proposalId = voter.upvotedProposal; Proposal storage proposal = proposals[proposalId]; require(_proposalExists(proposal)); // If acting on an expired proposal, expire the proposal. // TODO(asa): Break this out into a separate function. if (queue.contains(proposalId)) { // solhint-disable-next-line not-rely-on-time if (now >= proposal.timestamp.add(queueExpiry)) { queue.remove(proposalId); emit ProposalExpired(proposalId); } else { uint256 weight = getAccountWeight(account); require(weight > 0); queue.update( proposalId, queue.getValue(proposalId).sub(weight), lesser, greater ); emit ProposalUpvoteRevoked(proposalId, account, weight); } } voter.upvotedProposal = 0; return true; } // TODO(asa): Consider allowing approval to be revoked. // TODO(asa): Everywhere we use an index, require it's less than the array length /** * @notice Approves a proposal in the approval stage. * @param proposalId The ID of the proposal to approve. * @param index The index of the proposal ID in `dequeued`. * @return Whether or not the approval was made successfully. */ function approve(uint256 proposalId, uint256 index) external returns (bool) { dequeueProposalsIfReady(); Proposal storage proposal = proposals[proposalId]; require(_proposalExists(proposal) && dequeued[index] == proposalId); if (isDequeuedProposalExpired(proposalId)) { deleteDequeuedProposal(proposalId, index); return false; } ProposalStage stage = _getDequeuedProposalStage(proposal.timestamp); require(msg.sender == approver && !proposal.approved && stage == ProposalStage.Approval); proposal.approved = true; emit ProposalApproved(proposalId); return true; } /** * @notice Votes on a proposal in the referendum stage. * @param proposalId The ID of the proposal to vote on. * @param index The index of the proposal ID in `dequeued`. * @param value Whether to vote yes, no, or abstain. * @return Whether or not the vote was cast successfully. */ /* solhint-disable code-complexity */ function vote( uint256 proposalId, uint256 index, VoteValue value ) external returns (bool) { address account = getAccountFromVoter(msg.sender); require(!isVotingFrozen(account)); dequeueProposalsIfReady(); Proposal storage proposal = proposals[proposalId]; require(_proposalExists(proposal) && dequeued[index] == proposalId); if (isDequeuedProposalExpired(proposalId)) { deleteDequeuedProposal(proposalId, index); return false; } ProposalStage stage = _getDequeuedProposalStage(proposal.timestamp); Voter storage voter = voters[account]; uint256 weight = getAccountWeight(account); require( proposal.approved && stage == ProposalStage.Referendum && value != VoteValue.None && weight > 0 ); VoteRecord storage voteRecord = voter.referendumVotes[index]; // If we've already voted on this proposal, subtract the previous vote. if (voteRecord.proposalId == proposalId) { if (voteRecord.value == VoteValue.Abstain) { proposal.votes.abstain = proposal.votes.abstain.sub(weight); } else if (voteRecord.value == VoteValue.Yes) { proposal.votes.yes = proposal.votes.yes.sub(weight); } else if (voteRecord.value == VoteValue.No) { proposal.votes.no = proposal.votes.no.sub(weight); } } // Add new vote. if (value == VoteValue.Abstain) { proposal.votes.abstain = proposal.votes.abstain.add(weight); } else if (value == VoteValue.Yes) { proposal.votes.yes = proposal.votes.yes.add(weight); } else if (value == VoteValue.No) { proposal.votes.no = proposal.votes.no.add(weight); } voteRecord.proposalId = proposalId; voteRecord.value = value; if (proposal.timestamp > voter.mostRecentReferendumProposal) { voter.mostRecentReferendumProposal = proposalId; } emit ProposalVoted(proposalId, account, uint256(value), weight); return true; } /* solhint-enable code-complexity */ /** * @notice Executes a proposal in the execution stage, removing it from `dequeued`. * @param proposalId The ID of the proposal to vote on. * @param index The index of the proposal ID in `dequeued`. * @return Whether or not the proposal was executed successfully. * @dev Does not remove the proposal if the execution fails. */ function execute(uint256 proposalId, uint256 index) external returns (bool) { dequeueProposalsIfReady(); Proposal storage proposal = proposals[proposalId]; require(_proposalExists(proposal) && dequeued[index] == proposalId); bool expired = isDequeuedProposalExpired(proposalId); if (!expired) { // TODO(asa): Think through the effects of changing the passing function ProposalStage stage = _getDequeuedProposalStage(proposal.timestamp); require( proposal.approved && stage == ProposalStage.Execution && isProposalPassing(proposalId) ); for (uint256 i = 0; i < proposal.transactions.length; i = i.add(1)) { bool transactionExecuted = externalCall( proposal.transactions[i].destination, proposal.transactions[i].value, proposal.transactions[i].data.length, proposal.transactions[i].data ); // reverts proposal if any transaction fails require(transactionExecuted, "all transactions must succeed"); } emit ProposalExecuted( proposalId ); } // must have executed fully or proposal has expired if code reaches this point deleteDequeuedProposal(proposalId, index); return !expired; } /** * @notice Withdraws refunded Celo Gold deposits. * @return Whether or not the withdraw was successful. */ function withdraw() external nonReentrant returns (bool) { uint256 value = refundedDeposits[msg.sender]; require(value > 0 && value <= address(this).balance); refundedDeposits[msg.sender] = 0; msg.sender.transfer(value); return true; } /** * @notice Returns the number of seconds proposals stay in the approval stage. * @return The number of seconds proposals stay in the approval stage. */ function getApprovalStageDuration() external view returns (uint256) { return stageDurations.approval; } /** * @notice Returns the number of seconds proposals stay in the referendum stage. * @return The number of seconds proposals stay in the referendum stage. */ function getReferendumStageDuration() external view returns (uint256) { return stageDurations.referendum; } /** * @notice Returns the number of seconds proposals stay in the execution stage. * @return The number of seconds proposals stay in the execution stage. */ function getExecutionStageDuration() external view returns (uint256) { return stageDurations.execution; } /** * @notice Returns the constitution for a particular destination and function ID. * @param destination The destination address to get the constitution for. * @param functionId The function ID to get the constitution for, zero for the destination * default. * @return The ratio of yes:no votes needed in order to pass the proposal. */ function getConstitution( address destination, bytes4 functionId ) external view returns (uint256, uint256) { FractionUtil.Fraction memory threshold = _getConstitution(destination, functionId); return (threshold.numerator, threshold.denominator); } /** * @notice Returns whether or not a proposal exists. * @param proposalId The ID of the proposal. * @return Whether or not the proposal exists. */ function proposalExists(uint256 proposalId) external view returns (bool) { Proposal storage proposal = proposals[proposalId]; return _proposalExists(proposal); } /** * @notice Returns an unpacked proposal struct with its transaction count. * @param proposalId The ID of the proposal to unpack. * @return The unpacked proposal with its transaction count. */ function getProposal( uint256 proposalId ) external view returns (address, uint256, uint256, uint256) { Proposal storage proposal = proposals[proposalId]; return ( proposal.proposer, proposal.deposit, proposal.timestamp, proposal.transactions.length ); } /** * @notice Returns a specified transaction in a proposal. * @param proposalId The ID of the proposal to query. * @param index The index of the specified transaction in the proposal's transaction list. * @return The specified transaction. */ function getProposalTransaction( uint256 proposalId, uint256 index ) external view returns (uint256, address, bytes memory) { Proposal storage proposal = proposals[proposalId]; require(index < proposal.transactions.length, "transaction index out of bounds"); return ( proposal.transactions[index].value, proposal.transactions[index].destination, proposal.transactions[index].data ); } /** * @notice Returns whether or not a proposal has been approved. * @param proposalId The ID of the proposal. * @return Whether or not the proposal has been approved. */ function isApproved(uint256 proposalId) external view returns (bool) { return proposals[proposalId].approved; } /** * @notice Returns the referendum vote totals for a proposal. * @param proposalId The ID of the proposal. * @return The yes, no, and abstain vote totals. */ function getVoteTotals(uint256 proposalId) external view returns (uint256, uint256, uint256) { Proposal storage proposal = proposals[proposalId]; return (proposal.votes.yes, proposal.votes.no, proposal.votes.abstain); } /** * @notice Returns an accounts vote record on a particular index in `dequeued`. * @param account The address of the account to get the record for. * @param index The index in `dequeued`. * @return The corresponding proposal ID and vote value. */ function getVoteRecord(address account, uint256 index) external view returns (uint256, uint256) { VoteRecord storage record = voters[account].referendumVotes[index]; return (record.proposalId, uint256(record.value)); } /** * @notice Returns the number of proposals in the queue. * @return The number of proposals in the queue. */ function getQueueLength() external view returns (uint256) { return queue.list.numElements; } /** * @notice Returns the number of upvotes the queued proposal has received. * @param proposalId The ID of the proposal. * @return The number of upvotes a queued proposal has received. */ function getUpvotes(uint256 proposalId) external view returns (uint256) { require(isQueued(proposalId)); return queue.getValue(proposalId); } /** * @notice Returns the proposal ID and upvote total for all queued proposals. * @return The proposal ID and upvote total for all queued proposals. * @dev Note that this includes expired proposals that have yet to be removed from the queue. */ function getQueue() external view returns (uint256[] memory, uint256[] memory) { return queue.getElements(); } /** * @notice Returns the dequeued proposal IDs. * @return The dequeued proposal IDs. */ function getDequeue() external view returns (uint256[] memory) { return dequeued; } /** * @notice Returns the ID of the proposal upvoted by `account`. * @param account The address of the account. * @return The ID of the proposal upvoted by `account`. */ function getUpvotedProposal(address account) external view returns (uint256) { return voters[account].upvotedProposal; } /** * @notice Returns the ID of the most recently dequeued proposal voted on by `account`. * @param account The address of the account. * @return The ID of the most recently dequeued proposal voted on by `account`.. */ function getMostRecentReferendumProposal(address account) external view returns (uint256) { return voters[account].mostRecentReferendumProposal; } /** * @notice Returns whether or not a particular account is voting on proposals. * @param account The address of the account. * @return Whether or not the account is voting on proposals. */ function isVoting(address account) external view returns (bool) { Voter storage voter = voters[account]; bool isVotingQueue = voter.upvotedProposal != 0 && isQueued(voter.upvotedProposal); Proposal storage proposal = proposals[voter.mostRecentReferendumProposal]; bool isVotingReferendum = ( _getDequeuedProposalStage(proposal.timestamp) == ProposalStage.Referendum ); return isVotingQueue || isVotingReferendum; } /** * @notice Removes the proposals with the most upvotes from the queue, moving them to the * approval stage. * @dev If any of the top proposals have expired, they are deleted. */ function dequeueProposalsIfReady() public { // solhint-disable-next-line not-rely-on-time if (now >= lastDequeue.add(dequeueFrequency)) { uint256 numProposalsToDequeue = Math.min(concurrentProposals, queue.list.numElements); uint256[] memory dequeuedIds = queue.popN(numProposalsToDequeue); for (uint256 i = 0; i < numProposalsToDequeue; i = i.add(1)) { uint256 proposalId = dequeuedIds[i]; Proposal storage proposal = proposals[proposalId]; // solhint-disable-next-line not-rely-on-time if (now >= proposal.timestamp.add(queueExpiry)) { emit ProposalExpired(proposalId); continue; } refundedDeposits[proposal.proposer] = refundedDeposits[proposal.proposer].add( proposal.deposit ); // solhint-disable-next-line not-rely-on-time proposal.timestamp = now; if (emptyIndices.length > 0) { uint256 indexOfLastEmptyIndex = emptyIndices.length.sub(1); dequeued[emptyIndices[indexOfLastEmptyIndex]] = proposalId; // TODO(asa): We can save gas by not deleting here delete emptyIndices[indexOfLastEmptyIndex]; emptyIndices.length = indexOfLastEmptyIndex; } else { dequeued.push(proposalId); } // solhint-disable-next-line not-rely-on-time emit ProposalDequeued(proposalId, now); } // solhint-disable-next-line not-rely-on-time lastDequeue = now; } } /** * @notice Returns whether or not a proposal is in the queue. * @param proposalId The ID of the proposal. * @return Whether or not the proposal is in the queue. */ function isQueued(uint256 proposalId) public view returns (bool) { // solhint-disable-next-line not-rely-on-time return queue.contains(proposalId) && now < proposals[proposalId].timestamp.add(queueExpiry); } // TODO(asa): Pass proposal as argument for gas optimization /** * @notice Returns whether or not a particular proposal is passing according to the constitution. * @param proposalId The ID of the proposal. * @return Whether or not the proposal is passing. */ function isProposalPassing(uint256 proposalId) public view returns (bool) { Proposal storage proposal = proposals[proposalId]; // yesRatio can be undefined, which is not a problem for isGreaterThan FractionUtil.Fraction memory yesRatio = FractionUtil.Fraction( proposal.votes.yes, proposal.votes.yes.add(proposal.votes.no) ); for (uint256 i = 0; i < proposal.transactions.length; i = i.add(1)) { bytes4 functionId = extractFunctionSignature(proposal.transactions[i].data); FractionUtil.Fraction memory threshold = _getConstitution( proposal.transactions[i].destination, functionId ); if (yesRatio.isLessThanOrEqualTo(threshold)) { return false; } } return true; } function getDequeuedProposalStage(uint256 dequeueTime) external view returns (ProposalStage) { return _getDequeuedProposalStage(dequeueTime); } /** * @notice Returns the stage of a dequeued proposal. * @param dequeueTime The timestamp in seconds since epoch of when the proposal was dequeued. * @return The stage of the dequeued proposal. */ function _getDequeuedProposalStage(uint256 dequeueTime) private view returns (ProposalStage) { // solhint-disable-next-line not-rely-on-time if (now >= stageStartTime(dequeueTime, ProposalStage.Expiration)) { return ProposalStage.Expiration; // solhint-disable-next-line not-rely-on-time } else if (now >= stageStartTime(dequeueTime, ProposalStage.Execution)) { return ProposalStage.Execution; // solhint-disable-next-line not-rely-on-time } else if (now >= stageStartTime(dequeueTime, ProposalStage.Referendum)) { return ProposalStage.Referendum; } else { return ProposalStage.Approval; } } /** * @notice Returns the starting time for a particular stage. * @param dequeueTime The timestamp of when the proposal was dequeued. * @param stage The stage to return the start time for. * @return The stage start time. */ function stageStartTime(uint256 dequeueTime, ProposalStage stage) public view returns (uint256) { if (stage == ProposalStage.Approval) { return dequeueTime; } else if (stage == ProposalStage.Referendum) { return dequeueTime.add(stageDurations.approval); } else if (stage == ProposalStage.Execution) { return dequeueTime.add(stageDurations.approval).add(stageDurations.referendum); } else if (stage == ProposalStage.Expiration) { return dequeueTime.add(stageDurations.approval).add(stageDurations.referendum).add( stageDurations.execution ); } else { require(false); } } /** * @notice Deletes a dequeued proposal. * @param proposalId The ID of the proposal to delete. * @param index The index of the proposal ID in `dequeued`. */ function deleteDequeuedProposal(uint256 proposalId, uint256 index) private { dequeued[index] = 0; emptyIndices.push(index); delete proposals[proposalId]; } /** * @notice Extracts the first four bytes of a byte array. * @param input The byte array. * @return The first four bytes of `input`. */ function extractFunctionSignature(bytes memory input) private pure returns (bytes4) { bytes4 output; /* solhint-disable no-inline-assembly */ assembly { mstore(output, input) mstore(add(output, 4), add(input, 4)) } /* solhint-enable no-inline-assembly */ return output; } // TODO(asa): Pass the proposal as an argument for gas optimization /** * @notice Returns whether or not a dequeued proposal has expired. * @param proposalId The ID of the proposal to delete. * @return Whether or not the dequeued proposal has expired. */ function isDequeuedProposalExpired(uint256 proposalId) private view returns (bool) { Proposal storage proposal = proposals[proposalId]; ProposalStage stage = _getDequeuedProposalStage(proposal.timestamp); // The proposal is considered expired under the following conditions: // 1. Past the approval stage and not approved. // 2. Past the referendum stage and not passed. // 3. Past the execution stage. return ( (stage > ProposalStage.Execution) || (stage > ProposalStage.Referendum && !isProposalPassing(proposalId)) || (stage > ProposalStage.Approval && !proposal.approved) ); } /** * @notice Returns whether or not a proposal exists. * @param proposal The proposal. * @return Whether or not the proposal exists. */ function _proposalExists(Proposal storage proposal) private view returns (bool) { return proposal.timestamp > 0; } /** * @notice Returns the constitution for a particular destination and function ID. * @param destination The destination address to get the constitution for. * @param functionId The function ID to get the constitution for, zero for the destination * default. * @return The ratio of yes:no votes needed in order to pass the proposal. */ function _getConstitution( address destination, bytes4 functionId ) private view returns (FractionUtil.Fraction memory) { // Default to a simple majority. FractionUtil.Fraction memory threshold = FractionUtil.Fraction(1, 2); if (constitution[destination].functionThresholds[functionId].exists()) { threshold = constitution[destination].functionThresholds[functionId]; } else if (constitution[destination].defaultThreshold.exists()) { threshold = constitution[destination].defaultThreshold; } return threshold; } // call has been separated into its own function in order to take advantage // of the Solidity's code generator to produce a loop that copies tx.data into memory. /** * @notice Executes a function call. * @param value The value of Celo Gold to be sent with the function call. * @param destination The destination address of the function call. * @param dataLength The length of the data to be included in the function call. * @param data The data to be included in the function call. */ function externalCall( address destination, uint value, uint dataLength, bytes memory data ) private nonReentrant returns (bool) { bool result; /* solhint-disable no-inline-assembly */ assembly { /* solhint-disable max-line-length */ let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention) let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that result := call( sub(gas, 34710), // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) + // callNewAccountGas (25000, in case the destination address does not exist and needs creating) destination, value, d, dataLength, // Size of the input (in bytes) - this is what fixes the padding problem x, 0 // Output is ignored, therefore the output size is zero ) /* solhint-enable max-line-length */ } /* solhint-enable no-inline-assembly */ return result; } }
Removes the proposals with the most upvotes from the queue, moving them to the approval stage. If any of the top proposals have expired, they are deleted./ solhint-disable-next-line not-rely-on-time solhint-disable-next-line not-rely-on-time TODO(asa): We can save gas by not deleting here
function dequeueProposalsIfReady() public { if (now >= lastDequeue.add(dequeueFrequency)) { uint256 numProposalsToDequeue = Math.min(concurrentProposals, queue.list.numElements); uint256[] memory dequeuedIds = queue.popN(numProposalsToDequeue); for (uint256 i = 0; i < numProposalsToDequeue; i = i.add(1)) { uint256 proposalId = dequeuedIds[i]; Proposal storage proposal = proposals[proposalId]; if (now >= proposal.timestamp.add(queueExpiry)) { emit ProposalExpired(proposalId); continue; } refundedDeposits[proposal.proposer] = refundedDeposits[proposal.proposer].add( proposal.deposit ); if (emptyIndices.length > 0) { uint256 indexOfLastEmptyIndex = emptyIndices.length.sub(1); dequeued[emptyIndices[indexOfLastEmptyIndex]] = proposalId; delete emptyIndices[indexOfLastEmptyIndex]; emptyIndices.length = indexOfLastEmptyIndex; dequeued.push(proposalId); } } } }
12,589,504
./full_match/4/0xC92a0b9d1e6237fa7bCC0185f0B0A7b6c11286f6/sources/PermaNFT.sol
----- admin functions -----
function setAllowedCreatorsOnly(bool allowedCreatorsOnly_) public onlyOwner { allowedCreatorsOnly = allowedCreatorsOnly_; }
12,353,577
/** *Submitted for verification at Etherscan.io on 2021-07-13 */ //SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.6; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; } /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: Unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: Low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: Low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: Insufficient balance for call"); require(isContract(target), "Address: Call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: Low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: Static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: Low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: Delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; string internal _uri; // Mapping from token ID to owner address mapping (uint256 => address) private _owners; // Mapping owner address to token count mapping (address => uint256) private _balances; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: Balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: Owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory uri = _baseURI(); return bytes(uri).length > 0 ? string(abi.encodePacked(uri, _tokenId.toString(),".json")) : ""; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return _uri; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: Approval to current owner"); require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: Approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: Approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: Approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: Transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: Transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: Transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: Operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: Transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: Mint to the zero address"); require(!_exists(tokenId), "ERC721: Token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: Transfer of token that is not own"); require(to != address(0), "ERC721: Transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: Transfer to non ERC721Receiver implementer"); } else { // solhint-disable-next-line no-inline-assembly assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` cannot be the zero address. * - `to` cannot be the zero address. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { } } contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: Caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: New owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract BandRoyalty is Ownable(), ERC721("BAND Royalty","BD") { address saleAddress; mapping(uint256 => bool) internal notForSale; mapping(address => bool) internal administrators; event sale(address indexed _to, uint256 id); modifier onlyAdministrator() { require(administrators[msg.sender], "ERROR: You are not allowed"); _; } constructor() public { saleAddress = 0xCA9700EFf4b99f13727Ca0254F8633A84AA3770b; _uri = "https://ipfs.io/ipfs/QmPkpfqR2jy3C1nn44cSSocQk8ZUSm9AQH4knEzZ82kcwg/"; administrators[msg.sender] = true; } function buyBandRoyalyNft(uint256 _tokenId) payable public { require(!notForSale[_tokenId],"ERROR: This token has already purchased"); require(msg.value >= 1 ether && msg.value <= 25 ether, "ERROR: Wrong price range"); require(msg.value == choosePrice(_tokenId),"ERROR: You have provide wrong price against the tokenid"); require(_tokenId <= 3000,"ERROR: Only 3000 limit"); _mint(_msgSender(),_tokenId); notForSale[_tokenId] = true; payable(saleAddress).transfer(msg.value); emit sale(msg.sender,_tokenId); } function addPurchaseAndTreasuryItems(uint256[] memory _ids) onlyAdministrator public { for(uint256 i=0; i<_ids.length; i++){ notForSale[_ids[i]] = true; emit sale(address(0),_ids[i]); } } function preMintNftBatch(uint256[] memory _ids, address[] memory _to) onlyAdministrator public { require(_ids.length == _to.length,"ERROR: Wrong address or id"); for(uint256 i=0; i<_ids.length; i++){ _mint(_to[i],_ids[i]); } } function preMintNft(uint256 _id, address _to) onlyAdministrator public { _mint(_to,_id); } function addAdministrators(address _address) public onlyOwner { administrators[_address] = true; } function removeAdministrators(address _address) public onlyOwner { administrators[_address] = false; } function changeSaleAddress(address _newAddress) public onlyOwner { saleAddress = _newAddress; } function choosePrice(uint256 _tokenId) internal returns(uint256){ if (_tokenId == 1) { return 25 ether; } else if (_tokenId == 2) { return 20 ether; } else if (_tokenId == 3) { return 15 ether; } else if (_tokenId >= 4 && _tokenId <= 25) { return 10 ether; } else if (_tokenId >= 26 && _tokenId <= 250) { return 7 ether; } else if (_tokenId >= 251 && _tokenId <= 750) { return 5 ether; } else if (_tokenId >= 751 && _tokenId <= 1500) { return 3 ether; } else if (_tokenId >= 1500 && _tokenId <= 3000) { return 1 ether; } } }
See {IERC721-ownerOf}./
function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: Owner query for nonexistent token"); return owner; }
7,792,916
/* -------------------------------------------------------------------------------- The Bethereum [BETHER] Token Smart Contract Credit: Bethereum Limited ERC20: https://github.com/ethereum/EIPs/issues/20 ERC223: https://github.com/ethereum/EIPs/issues/223 MIT Licence -------------------------------------------------------------------------------- */ /* * Contract that is working with ERC223 tokens */ contract ContractReceiver { function tokenFallback(address _from, uint _value, bytes _data) { /* Fix for Mist warning */ _from; _value; _data; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract ERC223Interface { uint public totalSupply; function balanceOf(address who) constant returns (uint); event Transfer(address indexed from, address indexed to, uint value, bytes data); } contract BethereumERC223 is ERC223Interface { using SafeMath for uint256; /* Contract Constants */ string public constant _name = "Bethereum"; string public constant _symbol = "BETHER"; uint8 public constant _decimals = 18; /* Contract Variables */ address public owner; mapping(address => uint256) public balances; mapping(address => mapping (address => uint256)) public allowed; /* Constructor initializes the owner's balance and the supply */ function BethereumERC223() { totalSupply = 224181206832398351471266750; owner = msg.sender; } /* ERC20 Events */ event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from, address indexed to, uint256 value); /* ERC223 Events */ event Transfer(address indexed from, address indexed to, uint value, bytes data); /* Returns the balance of a particular account */ function balanceOf(address _address) constant returns (uint256 balance) { return balances[_address]; } /* Transfer the balance from the sender's address to the address _to */ function transfer(address _to, uint _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to]) { bytes memory empty; if(isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } else { return false; } } /* Withdraws to address _to form the address _from up to the amount _value */ function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to]) { balances[_from] -= _value; allowed[_from][msg.sender] -= _value; balances[_to] += _value; Transfer(_from, _to, _value); return true; } else { return false; } } /* Allows _spender to withdraw the _allowance amount form sender */ function approve(address _spender, uint256 _allowance) returns (bool success) { allowed[msg.sender][_spender] = _allowance; Approval(msg.sender, _spender, _allowance); return true; } /* Checks how much _spender can withdraw from _owner */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /* ERC223 Functions */ /* Get the contract constant _name */ function name() constant returns (string name) { return _name; } /* Get the contract constant _symbol */ function symbol() constant returns (string symbol) { return _symbol; } /* Get the contract constant _decimals */ function decimals() constant returns (uint8 decimals) { return _decimals; } /* Transfer the balance from the sender's address to the address _to with data _data */ function transfer(address _to, uint _value, bytes _data) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0 && balances[_to] + _value > balances[_to]) { if(isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } else { return false; } } /* Transfer function when _to represents a regular address */ function transferToAddress(address _to, uint _value, bytes _data) internal returns (bool success) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); Transfer(msg.sender, _to, _value, _data); return true; } /* Transfer function when _to represents a contract address, with the caveat that the contract needs to implement the tokenFallback function in order to receive tokens */ function transferToContract(address _to, uint _value, bytes _data) internal returns (bool success) { balances[msg.sender] -= _value; balances[_to] += _value; ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); Transfer(msg.sender, _to, _value); Transfer(msg.sender, _to, _value, _data); return true; } /* Infers if whether _address is a contract based on the presence of bytecode */ function isContract(address _address) internal returns (bool is_contract) { uint length; if (_address == 0) return false; assembly { length := extcodesize(_address) } if(length > 0) { return true; } else { return false; } } /* Stops any attempt to send Ether to this contract */ function () { throw; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title Pausable token * * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is BethereumERC223, Pausable { function transfer(address _to, uint256 _value, bytes _data) public whenNotPaused returns (bool) { return super.transfer(_to, _value, _data); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is BethereumERC223, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract BethereumToken is MintableToken, PausableToken { function BethereumToken(){ pause(); } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale { using SafeMath for uint256; // The token being sold MintableToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public startTime; uint256 public endTime; // address where funds are collected address public wallet; // amount of raised money in wei uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); function Crowdsale(uint256 _endTime, address _wallet) { require(_endTime >= now); require(_wallet != 0x0); token = createTokenContract(); endTime = _endTime; wallet = _wallet; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (BethereumToken) { return new BethereumToken(); } // fallback function can be used to buy tokens function () payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) public payable { } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool withinPeriod = now >= startTime && now <= endTime; bool nonZeroPurchase = msg.value != 0; return withinPeriod && nonZeroPurchase; } // @return true if crowdsale event has ended function hasEnded() public constant returns (bool) { return now > endTime; } } /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; bool public weiCapReached = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); finalization(); Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } contract BETHERTokenSale is FinalizableCrowdsale { using SafeMath for uint256; // Define sale uint public constant RATE = 17500; uint public constant TOKEN_SALE_LIMIT = 25000 * 1000000000000000000; uint256 public constant TOKENS_FOR_OPERATIONS = 400000000*(10**18); uint256 public constant TOKENS_FOR_SALE = 600000000*(10**18); uint public constant TOKENS_FOR_PRESALE = 315000000*(1 ether / 1 wei); uint public BONUS_PERCENTAGE; enum Phase { Created, CrowdsaleRunning, Paused } Phase public currentPhase = Phase.Created; event LogPhaseSwitch(Phase phase); // Constructor function BETHERTokenSale( uint256 _end, address _wallet ) FinalizableCrowdsale() Crowdsale(_end, _wallet) { } function setNewBonusScheme(uint _bonusPercentage) { BONUS_PERCENTAGE = _bonusPercentage; } function mintRawTokens(address _buyer, uint256 _newTokens) public onlyOwner { token.mint(_buyer, _newTokens); } /// @dev Lets buy you some tokens. function buyTokens(address _buyer) public payable { // Available only if presale or crowdsale is running. require(currentPhase == Phase.CrowdsaleRunning); require(_buyer != address(0)); require(msg.value > 0); require(validPurchase()); uint tokensWouldAddTo = 0; uint weiWouldAddTo = 0; uint256 weiAmount = msg.value; uint newTokens = msg.value.mul(RATE); weiWouldAddTo = weiRaised.add(weiAmount); require(weiWouldAddTo <= TOKEN_SALE_LIMIT); newTokens = addBonusTokens(token.totalSupply(), newTokens); tokensWouldAddTo = newTokens.add(token.totalSupply()); require(tokensWouldAddTo <= TOKENS_FOR_SALE); token.mint(_buyer, newTokens); TokenPurchase(msg.sender, _buyer, weiAmount, newTokens); weiRaised = weiWouldAddTo; forwardFunds(); if (weiRaised == TOKENS_FOR_SALE){ weiCapReached = true; } } // @dev Adds bonus tokens by token supply bought by user // @param _totalSupply total supply of token bought during pre-sale/crowdsale // @param _newTokens tokens currently bought by user function addBonusTokens(uint256 _totalSupply, uint256 _newTokens) internal view returns (uint256) { uint returnTokens; uint tokens = _newTokens; returnTokens = tokens.add(tokens.mul(BONUS_PERCENTAGE).div(100)); return returnTokens; } function setSalePhase(Phase _nextPhase) public onlyOwner { currentPhase = _nextPhase; LogPhaseSwitch(_nextPhase); } function transferTokenOwnership(address _newOwner) { token.transferOwnership(_newOwner); } // Finalize function finalization() internal { uint256 toMint = TOKENS_FOR_OPERATIONS; token.mint(wallet, toMint); token.finishMinting(); token.transferOwnership(wallet); } }
Checks how much _spender can withdraw from _owner /
function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; }
20,883
./full_match/42/0xE3fd40E658284bac18b42b15A8a7B6C8E2D3Dbb0/sources/contracts/BaseRewardPool.sol
Adds an extra reward only `rewardManager` can add extra rewards _reward token address of the reward
function addExtraReward(address _reward) external onlyAddress(rewardManager) { require(_reward != address(0), "!reward setting"); extraRewards.push(_reward); }
9,570,954
./full_match/1/0x3B1E4e5e307207978E2e52Ee92516bfE5De0f2E7/sources/contracts/protocol/vault/GeneralVault.sol
Convert an `_amount` of collateral internal asset to collateral external asset and send to caller on liquidation. - Caller is only LendingPool _asset The address of collateral external asset _asset = 0x0000000000000000000000000000000000000000 means to use ETH as collateral _amount The amount of collateral internal asset return The amount of collateral external asset/ Get yield based on strategy and re-deposit - Caller is anyone/ Get price per share based on yield strategy return The value of price per share/ Set treasury address and vault fee - Caller is only PoolAdmin which is set on LendingPoolAddressesProvider contract _treasury The treasury address _fee The vault fee which has more two decimals, ex: 100% = 100_00/
function withdrawOnLiquidation(address _asset, uint256 _amount) external virtual returns (uint256); function processYield() external virtual; function pricePerShare() external view virtual returns (uint256); function setTreasuryInfo(address _treasury, uint256 _fee) public payable virtual onlyAdmin { require(_treasury != address(0), Errors.VT_TREASURY_INVALID); require(_fee <= 30_00, Errors.VT_FEE_TOO_BIG); _treasuryAddress = _treasury; _vaultFee = _fee; emit SetTreasuryInfo(_treasury, _fee); }
16,422,562
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "./interfaces/IERC721Freezeble.sol"; import "./interfaces/IGatewayToken.sol"; import "./interfaces/IGatewayTokenController.sol"; import "./interfaces/IERC721Expirable.sol"; /** * @dev Gateway Token contract is responsible for managing Identity.com KYC gateway tokens * those tokens represent completed KYC with attached identity. * Gateway tokens using ERC721 standard with custom extentions. * * Contract handles multiple levels of access such as Network Authority (may represent a specific regulator body) * Gatekeepers (Identity.com network parties who can mint/burn/freeze gateway tokens) and overall system Admin who can add * new Gatekeepers and Network Authorities */ contract GatewayToken is ERC165, AccessControl, IERC721, IERC721Metadata, IERC721Freezeble, IERC721Expirable, IGatewayToken { using Address for address; using Strings for uint256; // Gateway Token name string public override name; // Gateway Token symbol string public override symbol; // Gateway Token controller contract address address public controller; address public deployer; // Gateway token transfer restrictions bool public isTransfersRestricted; // Off-chain DAO governance access control bool public override isDAOGoverned; address public override daoManager; // Access control roles bytes32 public constant DAO_MANAGER_ROLE = keccak256("DAO_MANAGER_ROLE"); bytes32 public constant GATEKEEPER_ROLE = keccak256("GATEKEEPER_ROLE"); bytes32 public constant NETWORK_AUTHORITY_ROLE = keccak256("NETWORK_AUTHORITY_ROLE"); // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; // Mapping from token ID to freeze param mapping(uint256 => bool) private _isFreezed; // Optional mapping for gateway token Identities (via TokenURI) mapping(uint256 => string) private _tokenURIs; // Optional Mapping from token ID to expiration date mapping(uint256 => uint256) private _expirations; // Optional Mapping from address to tokenID mapping(address => uint256) private _defaultTokens; // @dev Modifier to prevent calls from anyone except Identity.com Admin modifier onlyIdentityAdmin() { require(msg.sender == IGatewayTokenController(controller).identityAdmin() || msg.sender == controller, "NOT IDENTITY.COM ADMIN NOR TOKEN CONTROLLER"); _; } // @dev Modifier to prevent calls for blacklisted users modifier onlyNonBlacklistedUser(address user) { require(!_isBlacklisted(user), "BLACKLISTED USER"); _; } // @dev Modifier to make a function callable only when token transfers not restricted. modifier whenTransfersNotRestricted() { require(!transfersRestricted(), "TRANSFERS RESTRICTED"); _; } // @dev Modifier to make a function callable only when token transfers restricted. modifier whenTransfersRestricted() { require(transfersRestricted(), "TRANSFERS NOT RESTRICTED"); _; } /** * @dev Gateway Token constructor initializes the contract by * setting a `name` and a `symbol` to the gateway token. * * Initiates gateway token roles with main system admin `GATEWAY_TOKEN_CONTROLLER`, * `NETWORK_AUTHORITY_ROLE` responsible for adding/removing Gatekeepers and * `GATEKEEPER_ROLE` responsible for minting/burning/transfering tokens */ constructor(string memory _name, string memory _symbol, address _deployer, bool _isDAOGoverned, address _daoManager) public { name = _name; symbol = _symbol; controller = _msgSender(); isTransfersRestricted = true; deployer = _deployer; _setupRole(NETWORK_AUTHORITY_ROLE, _msgSender()); _setupRole(NETWORK_AUTHORITY_ROLE, deployer); _setupRole(GATEKEEPER_ROLE, deployer); if (_isDAOGoverned) { isDAOGoverned = _isDAOGoverned; require(_daoManager != address(0), "INCORRECT ADDRESS"); // require(_daoManager.isContract(), "NON CONTRACT EXECUTOR"); uncomment while testing with Gnosis Multisig daoManager = _daoManager; _setupRole(DAO_MANAGER_ROLE, _daoManager); _setupRole(DAO_MANAGER_ROLE, _msgSender()); _setupRole(NETWORK_AUTHORITY_ROLE, _daoManager); _setupRole(GATEKEEPER_ROLE, _daoManager); _setRoleAdmin(NETWORK_AUTHORITY_ROLE, DAO_MANAGER_ROLE); _setRoleAdmin(GATEKEEPER_ROLE, DAO_MANAGER_ROLE); } else { _setRoleAdmin(NETWORK_AUTHORITY_ROLE, NETWORK_AUTHORITY_ROLE); _setRoleAdmin(GATEKEEPER_ROLE, NETWORK_AUTHORITY_ROLE); } } /** * @dev Returns true if gateway token owner transfers reestricted, and false otherwise. */ function transfersRestricted() public view virtual returns (bool) { return isTransfersRestricted; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165, AccessControl) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Triggers to check total amount of gateway tokens hold by specific address. * @param owner Token owner address */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ZERO ADDRESS"); return _balances[owner]; } /** * @dev Triggers to get owner for specific gateway token * @param tokenId Gateway token id */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ZERO ADDRESS"); return owner; } /** * @dev Triggers to get identity attached to specific gateway token * @param tokenId Gateway token id */ function getIdentity(uint256 tokenId) public view virtual returns (string memory) { return tokenURI(tokenId); } /** * @dev Triggers to get tokenURI attached to specificied `tokenId` * @param tokenId Gateway token id */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "TOKEN DOESN'T EXIST OR FREEZED"); string memory _tokenURI = _tokenURIs[tokenId]; return _tokenURI; } /** * @dev Triggers to attach identity string to specific gateway token * @param tokenId Gateway token id * @param tokenURI Gateway token identity in a form of TokenURI * * @notice Only executable by gatekeepers */ function setTokenURI(uint256 tokenId, string memory tokenURI) public virtual { require(hasRole(GATEKEEPER_ROLE, _msgSender()), "MUST BE GATEKEEPER"); require(_existsAndActive(tokenId), "TOKEN DOESN'T EXIST OR FREEZED"); address tokenOwner = ownerOf(tokenId); require(!_isBlacklisted(tokenOwner), "BLACKLISTED USER"); _tokenURIs[tokenId] = tokenURI; } /** * @dev Triggered by external contract to verify if `tokenId` and token `owner` are correct. * * Checks if token exists in gateway token contract, `tokenId` still active, and not expired. * Performs additional checks to verify that `owner` is not blacklisted globally. */ function verifyToken(address owner, uint256 tokenId) external view virtual returns (bool) { if(!_existsAndActive(tokenId)) return false; address tokenOwner = ownerOf(tokenId); if (tokenOwner != owner) return false; bool _blacklisted = _isBlacklisted(owner); if(_blacklisted) return false; return true; } /** * @dev Triggered by external contract to verify the validity of the default token for `owner`. * * Checks owner has any token on gateway token contract, `tokenId` still active, and not expired. * Performs additional checks to verify that `owner` is not blacklisted globally. */ function verifyToken(address owner) external view virtual returns (bool) { uint256 tokenId = getTokenId(owner); if(!_existsAndActive(tokenId)) return false; address tokenOwner = ownerOf(tokenId); if (tokenOwner != owner) return false; bool _blacklisted = _isBlacklisted(owner); if(_blacklisted) return false; return true; } /** * @dev Triggers to get all information gateway token related to specified `tokenId` * @param tokenId Gateway token id */ function getToken(uint256 tokenId) public view virtual override returns ( address owner, bool isFreezed, string memory identity, uint256 expiration ) { owner = ownerOf(tokenId); isFreezed = _isFreezed[tokenId]; identity = _tokenURIs[tokenId]; expiration = _expirations[tokenId]; return (owner, isFreezed, identity, expiration); } /** * @dev Returns whether `tokenId` exists. * * Tokens start existing when they are minted (`_mint`), * pause when they are freezed (`_freeze`), and * stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `tokenId` exists and not freezed. */ function _existsAndActive(uint256 tokenId) internal view virtual returns (bool) { if (_expirations[tokenId] != 0) { return _owners[tokenId] != address(0) && !_isFreezed[tokenId] && block.timestamp <= _expirations[tokenId]; } else { return _owners[tokenId] != address(0) && !_isFreezed[tokenId]; } } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); if (spender == owner) { return !transfersRestricted(); } else { return (getApproved(tokenId) == spender || isApprovedForAll(owner, spender) || hasRole(GATEKEEPER_ROLE, spender)); } } /** * @dev Triggers to request token ownership transfer * @param to Address to transfer token ownership * @param tokenId Gateway token id * * @notice Only executable by token owner */ function approve(address to, uint256 tokenId) public virtual override { address owner = GatewayToken.ownerOf(tokenId); require(to != owner, "INCORRECT APPROVE DESTINATION"); require(_msgSender() == owner, "INCORRECT OWNER"); require(!_isBlacklisted(owner), "BLACKLISTED USER"); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_existsAndActive(tokenId), "TOKEN DOESN'T EXIST"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "INCORRECT APPROVE"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "MSG.SENDER NOT OWNER NOR GATEKEEPER"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "MSG.SENDER NOT OWNER NOR GATEKEEPER"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "TRANSFER TO NON ERC721Receiver IMPLEMENTER"); } /** * @dev Triggers to burn gateway token * @param tokenId Gateway token id */ function burn(uint256 tokenId) public virtual { //solhint-disable-next-line max-line-length require(hasRole(GATEKEEPER_ROLE, _msgSender()), "MUST BE GATEKEEPER"); _burn(tokenId); } /** * @dev Triggers to mint gateway token * @param to Gateway token owner * @param tokenId Gateway token id */ function mint(address to, uint256 tokenId) public virtual onlyNonBlacklistedUser(to) { //solhint-disable-next-line max-line-length require(hasRole(GATEKEEPER_ROLE, _msgSender()), "MUST BE GATEKEEPER"); _mint(to, tokenId); } /** * @dev Triggers to mint gateway token with specified expiration `timestamp` * @param to Gateway token owner * @param tokenId Gateway token id * @param timestamp Expiration timestamp */ function mintWithExpiration(address to, uint256 tokenId, uint256 timestamp) public virtual override onlyNonBlacklistedUser(to) { //solhint-disable-next-line max-line-length require(hasRole(GATEKEEPER_ROLE, _msgSender()), "MUST BE GATEKEEPER"); _mint(to, tokenId); _expirations[tokenId] = timestamp; } /** * @dev Triggers to freeze gateway token * @param tokenId Gateway token id */ function freeze(uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(hasRole(GATEKEEPER_ROLE, _msgSender()), "MUST BE GATEKEEPER"); address tokenOwner = ownerOf(tokenId); require(!_isBlacklisted(tokenOwner), "BLACKLISTED USER"); _freeze(tokenId); } /** * @dev Triggers to unfreeze gateway token * @param tokenId Gateway token id */ function unfreeze(uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(hasRole(GATEKEEPER_ROLE, _msgSender()), "MUST BE GATEKEEPER"); address tokenOwner = ownerOf(tokenId); require(!_isBlacklisted(tokenOwner), "BLACKLISTED USER"); _unfreeze(tokenId); } /** * @dev Triggers to get specificied `tokenId` expiration timestamp * @param tokenId Gateway token id */ function expiration(uint256 tokenId) public view virtual override returns (uint256) { require(_exists(tokenId), "TOKEN DOESN'T EXIST OR FREEZED"); uint256 _expiration = _expirations[tokenId]; return _expiration; } /** * @dev Triggers to set expiration for tokenId * @param tokenId Gateway token id */ function setExpiration(uint256 tokenId, uint256 timestamp) public virtual override { //solhint-disable-next-line max-line-length require(hasRole(GATEKEEPER_ROLE, _msgSender()), "MUST BE GATEKEEPER"); address tokenOwner = ownerOf(tokenId); require(!_isBlacklisted(tokenOwner), "BLACKLISTED USER"); _setExpiration(tokenId, timestamp); } /** * @dev Triggers to get default gateway token ID for `owner` * @param owner Token owner address */ function getTokenId(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ZERO ADDRESS"); return _defaultTokens[owner]; } /** * @dev Triggers to set token with specified `tokenId` as default for `owner` * @param owner Token owner address * @param tokenId Gateway token id */ function setDefaultTokenId(address owner, uint256 tokenId) public virtual override { require(_exists(tokenId), "TOKEN DOESN'T EXIST OR FREEZED"); require(hasRole(GATEKEEPER_ROLE, _msgSender()), "MUST BE GATEKEEPER"); address actualOwner = ownerOf(tokenId); require(actualOwner == owner, "INCORRECT OWNER"); _defaultTokens[owner] = tokenId; } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ZERO ADDRESS"); require(!_exists(tokenId), "TOKEN ALREADY EXISTS"); _balances[to] += 1; _owners[tokenId] = to; if (_defaultTokens[to] == 0) { _defaultTokens[to] = tokenId; } emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = GatewayToken.ownerOf(tokenId); // Clear all state associated with `tokenId` _approve(address(0), tokenId); delete _isFreezed[tokenId]; delete _expirations[tokenId]; if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } if (_defaultTokens[owner] == tokenId) { delete _defaultTokens[owner]; } _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Freezes `tokenId` and it's usage by gateway token owner. * * Emits a {Freeze} event. */ function _freeze(uint256 tokenId) internal virtual { require(_existsAndActive(tokenId), "TOKEN DOESN'T EXISTS OR NOT ACTIVE"); _isFreezed[tokenId] = true; emit Freeze(tokenId); } /** * @dev Unfreezes `tokenId` and it's usage by gateway token owner. * * Emits a {Unfreeze} event. */ function _unfreeze(uint256 tokenId) internal virtual { require(_exists(tokenId), "TOKEN DOESN'T EXISTS"); require(_isFreezed[tokenId], "TOKEN NOT FREEZED"); _isFreezed[tokenId] = false; emit Unfreeze(tokenId); } /** * @dev Sets expiration time for `tokenId`. */ function _setExpiration(uint256 tokenId, uint256 timestamp) internal virtual { require(_existsAndActive(tokenId), "TOKEN DOESN'T EXISTS OR ACTIVE"); _expirations[tokenId] = timestamp; emit Expiration(tokenId, timestamp); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ownerOf(tokenId) == from, "INCORRECT TOKEN OWNER"); require(to != address(0), "TRANSFER TO ZERO ADDRESS"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); if (_defaultTokens[from] == tokenId) { delete _defaultTokens[from]; _defaultTokens[to] = tokenId; } _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(GatewayToken.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _isBlacklisted(address user) private view returns (bool) { return IGatewayTokenController(controller).isBlacklisted(user); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} // =========== ACCESS CONTROLL SECTION ============ /** * @dev Triggers to add new gatekeeper into the system. * @param gatekeeper Gatekeeper address */ function addGatekeeper(address gatekeeper) public virtual { grantRole(GATEKEEPER_ROLE, gatekeeper); } /** * @dev Triggers to remove existing gatekeeper from gateway token. * @param gatekeeper Gatekeeper address */ function removeGatekeeper(address gatekeeper) public virtual { revokeRole(GATEKEEPER_ROLE, gatekeeper); } /** * @dev Triggers to add new network authority into the system. * @param authority Network Authority address * * @notice Can be triggered by Gateway Token Controller or any Network Authority */ function addNetworkAuthority(address authority) external virtual override { grantRole(NETWORK_AUTHORITY_ROLE, authority); } /** * @dev Triggers to remove existing network authority from gateway token. * @param authority Network Authority address * * @notice Can be triggered by Gateway Token Controller or any Network Authority */ function removeNetworkAuthority(address authority) external virtual override { revokeRole(NETWORK_AUTHORITY_ROLE, authority); } /** * @dev Triggers to verify if authority has a NETWORK_AUTHORITY_ROLE role. * @param authority Network Authority address */ function isNetworkAuthority(address authority) external virtual override returns (bool) { return hasRole(NETWORK_AUTHORITY_ROLE, authority); } // =========== ACCESS CONTROLL SECTION ============ /** * @dev Triggers to allow token transfers by token owners. * * @notice Only triggered by Identity.com Admin */ function allowTransfers() external virtual override whenTransfersRestricted onlyIdentityAdmin returns (bool) { isTransfersRestricted = false; emit TransfersAccepted(_msgSender()); return true; } /** * @dev Triggers to stop token transfers by token owners. * * @notice Only triggered by Identity.com Admin */ function stopTransfers() external virtual override whenTransfersNotRestricted onlyIdentityAdmin returns (bool) { isTransfersRestricted = true; emit TransfersRestricted(_msgSender()); return true; } /** * @dev Transfers Gateway Token DAO Manager access from daoManager to `newManager` * @param newManager Address to transfer DAO Manager role for. */ function transferDAOManager(address newManager) public override { require(msg.sender == daoManager, "NOT DAO MANAGER"); require(newManager != address(0), "ZERO ADDRESS"); grantRole(DAO_MANAGER_ROLE, newManager); grantRole(NETWORK_AUTHORITY_ROLE, newManager); grantRole(GATEKEEPER_ROLE, newManager); revokeRole(GATEKEEPER_ROLE, daoManager); revokeRole(NETWORK_AUTHORITY_ROLE, daoManager); revokeRole(DAO_MANAGER_ROLE, daoManager); daoManager = newManager; emit DAOManagerTransfered(msg.sender, newManager); } }
Transfers `tokenId` from `from` to `to`. As opposed to {transferFrom}, this imposes no restrictions on msg.sender. Requirements: - `to` cannot be the zero address. - `tokenId` token must be owned by `from`. Emits a {Transfer} event./ Clear approvals from the previous owner
function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ownerOf(tokenId) == from, "INCORRECT TOKEN OWNER"); require(to != address(0), "TRANSFER TO ZERO ADDRESS"); _beforeTokenTransfer(from, to, tokenId); _approve(address(0), tokenId); if (_defaultTokens[from] == tokenId) { delete _defaultTokens[from]; _defaultTokens[to] = tokenId; } _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); }
1,776,570
pragma solidity ^0.8.0; // Copyright 2020 Keyko GmbH. // SPDX-License-Identifier: (Apache-2.0 AND CC-BY-4.0) // Code is Apache-2.0 and docs are CC-BY-4.0 import '@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol'; /** * @title DID Registry Library * @author Keyko * * @dev All function calls are currently implemented without side effects */ library DIDRegistryLibrary { using SafeMathUpgradeable for uint256; // DIDRegistry Entity struct DIDRegister { // DIDRegistry entry owner address owner; // The percent of the sale that is going back to the original `creator` in the secondary market uint8 royalties; // Flag to control if NFTs config was already initialized bool nftInitialized; // Flag to control if NFTs config was already initialized (erc 721) bool nft721Initialized; // DIDRegistry original creator, this can't be modified after the asset is registered address creator; // Checksum associated to the DID bytes32 lastChecksum; // URL to the metadata associated to the DID string url; // Who was the last one updated the entry address lastUpdatedBy; // When was the last time was updated uint256 blockNumberUpdated; // Providers able to manage this entry address[] providers; // Delegates able to register provenance events on behalf of the owner or providers address[] delegates; // The NFTs supply associated to the DID uint256 nftSupply; // The max number of NFTs associated to the DID that can be minted uint256 mintCap; } // List of DID's registered in the system struct DIDRegisterList { mapping(bytes32 => DIDRegister) didRegisters; bytes32[] didRegisterIds; } /** * @notice update the DID store * @dev access modifiers and storage pointer should be implemented in DIDRegistry * @param _self refers to storage pointer * @param _did refers to decentralized identifier (a byte32 length ID) * @param _checksum includes a one-way HASH calculated using the DDO content * @param _url includes the url resolving to the DID Document (DDO) */ function update( DIDRegisterList storage _self, bytes32 _did, bytes32 _checksum, string calldata _url ) external returns (uint size) { address didOwner = _self.didRegisters[_did].owner; address creator = _self.didRegisters[_did].creator; if (didOwner == address(0)) { didOwner = msg.sender; _self.didRegisterIds.push(_did); creator = didOwner; } _self.didRegisters[_did] = DIDRegister({ owner: didOwner, creator: creator, lastChecksum: _checksum, url: _url, lastUpdatedBy: msg.sender, blockNumberUpdated: block.number, providers: new address[](0), delegates: new address[](0), nftSupply: 0, mintCap: 0, royalties: 0, nftInitialized: false, nft721Initialized: false }); return _self.didRegisterIds.length; } /** * @notice initializeNftConfig creates the initial setup of NFTs minting and royalties distribution. * After this initial setup, this data can't be changed anymore for the DID given, even for the owner of the DID. * The reason of this is to avoid minting additional NFTs after the initial agreement, what could affect the * valuation of NFTs of a DID already created. * @dev update the DID registry providers list by adding the mintCap and royalties configuration * @param _self refers to storage pointer * @param _did refers to decentralized identifier (a byte32 length ID) * @param _cap refers to the mint cap * @param _royalties refers to the royalties to reward to the DID creator in the secondary market * The royalties in secondary market for the creator should be between 0% >= x < 100% */ function initializeNftConfig( DIDRegisterList storage _self, bytes32 _did, uint256 _cap, uint8 _royalties ) internal { require(_self.didRegisters[_did].owner != address(0), 'DID not stored'); require(!_self.didRegisters[_did].nftInitialized, 'NFT already initialized'); require(_royalties < 100, 'Invalid royalties number'); require(_royalties >= _self.didRegisters[_did].royalties, 'Cannot decrease royalties'); _self.didRegisters[_did].mintCap = _cap; _self.didRegisters[_did].royalties = _royalties; _self.didRegisters[_did].nftInitialized = true; } function initializeNft721Config( DIDRegisterList storage _self, bytes32 _did, uint8 _royalties ) internal { require(_self.didRegisters[_did].owner != address(0), 'DID not stored'); require(!_self.didRegisters[_did].nft721Initialized, 'NFT already initialized'); require(_royalties < 100, 'Invalid royalties number'); require(_royalties >= _self.didRegisters[_did].royalties, 'Cannot decrease royalties'); _self.didRegisters[_did].royalties = _royalties; _self.didRegisters[_did].nft721Initialized = true; } /** * @notice areRoyaltiesValid checks if for a given DID and rewards distribution, this allocate the * original creator royalties properly * @param _self refers to storage pointer * @param _did refers to decentralized identifier (a byte32 length ID) * @param _amounts refers to the amounts to reward * @param _receivers refers to the receivers of rewards * @return true if the rewards distribution respect the original creator royalties */ function areRoyaltiesValid( DIDRegisterList storage _self, bytes32 _did, uint256[] memory _amounts, address[] memory _receivers ) internal view returns (bool) { // If (did.creator == did.owner) - It means the DID is still a first sale so no royalties needed // returns true; if (_self.didRegisters[_did].owner == _self.didRegisters[_did].creator) { return true; } // If there are no royalties everything is good if (_self.didRegisters[_did].royalties == 0) { return true; } // If (sum(_amounts) == 0) - It means there is no payment so everything is valid // returns true; uint256 _totalAmount = 0; for(uint i = 0; i < _amounts.length; i++) _totalAmount = _totalAmount.add(_amounts[i]); if (_totalAmount == 0) return true; // If (_did.creator is not in _receivers) - It means the original creator is not included as part of the payment // return false; bool found = false; uint256 index; for (index = 0; index < _receivers.length; index++) { if (_self.didRegisters[_did].creator == _receivers[index]) { found = true; break; } } if (!found) // The creator royalties are not part of the rewards return false; // If the amount to receive by the creator is lower than royalties the calculation is not valid // return false; uint256 _requiredRoyalties = ((_totalAmount.mul(_self.didRegisters[_did].royalties)) / 100); // Check if royalties are enough // Are we paying enough royalties in the secondary market to the original creator? return (_amounts[index] >= _requiredRoyalties); } /** * @notice addProvider add provider to DID registry * @dev update the DID registry providers list by adding a new provider * @param _self refers to storage pointer * @param _did refers to decentralized identifier (a byte32 length ID) * @param provider the provider's address */ function addProvider( DIDRegisterList storage _self, bytes32 _did, address provider ) internal { require( provider != address(0) && provider != address(this), 'Invalid provider' ); if (!isProvider(_self, _did, provider)) { _self.didRegisters[_did].providers.push(provider); } } /** * @notice removeProvider remove provider from DID registry * @dev update the DID registry providers list by removing an existing provider * @param _self refers to storage pointer * @param _did refers to decentralized identifier (a byte32 length ID) * @param _provider the provider's address */ function removeProvider( DIDRegisterList storage _self, bytes32 _did, address _provider ) internal returns(bool) { require( _provider != address(0), 'Invalid provider' ); int256 i = getProviderIndex(_self, _did, _provider); if (i == -1) { return false; } delete _self.didRegisters[_did].providers[uint256(i)]; return true; } /** * @notice updateDIDOwner transfer DID ownership to a new owner * @param _self refers to storage pointer * @param _did refers to decentralized identifier (a byte32 length ID) * @param _newOwner the new DID owner address */ function updateDIDOwner( DIDRegisterList storage _self, bytes32 _did, address _newOwner ) internal { require(_newOwner != address(0)); _self.didRegisters[_did].owner = _newOwner; } /** * @notice isProvider check whether DID provider exists * @param _self refers to storage pointer * @param _did refers to decentralized identifier (a byte32 length ID) * @param _provider the provider's address * @return true if the provider already exists */ function isProvider( DIDRegisterList storage _self, bytes32 _did, address _provider ) public view returns(bool) { if (getProviderIndex(_self, _did, _provider) == -1) return false; return true; } /** * @notice getProviderIndex get the index of a provider * @param _self refers to storage pointer * @param _did refers to decentralized identifier (a byte32 length ID) * @param provider the provider's address * @return the index if the provider exists otherwise return -1 */ function getProviderIndex( DIDRegisterList storage _self, bytes32 _did, address provider ) private view returns(int256 ) { for (uint256 i = 0; i < _self.didRegisters[_did].providers.length; i++) { if (provider == _self.didRegisters[_did].providers[i]) { return int(i); } } return - 1; } //////////// DELEGATE METHODS /** * @notice addDelegate add delegate to DID registry * @dev update the DID registry delegates list by adding a new delegate * @param _self refers to storage pointer * @param _did refers to decentralized identifier (a byte32 length ID) * @param delegate the delegate's address */ function addDelegate( DIDRegisterList storage _self, bytes32 _did, address delegate ) internal { require(delegate != address(0) && delegate != address(this)); if (!isDelegate(_self, _did, delegate)) { _self.didRegisters[_did].delegates.push(delegate); } } /** * @notice removeDelegate remove delegate from DID registry * @dev update the DID registry delegates list by removing an existing delegate * @param _self refers to storage pointer * @param _did refers to decentralized identifier (a byte32 length ID) * @param _delegate the delegate's address */ function removeDelegate( DIDRegisterList storage _self, bytes32 _did, address _delegate ) internal returns(bool) { require(_delegate != address(0)); int256 i = getDelegateIndex(_self, _did, _delegate); if (i == -1) { return false; } delete _self.didRegisters[_did].delegates[uint256(i)]; return true; } /** * @notice isDelegate check whether DID delegate exists * @param _self refers to storage pointer * @param _did refers to decentralized identifier (a byte32 length ID) * @param _delegate the delegate's address * @return true if the delegate already exists */ function isDelegate( DIDRegisterList storage _self, bytes32 _did, address _delegate ) public view returns(bool) { if (getDelegateIndex(_self, _did, _delegate) == -1) return false; return true; } /** * @notice getDelegateIndex get the index of a delegate * @param _self refers to storage pointer * @param _did refers to decentralized identifier (a byte32 length ID) * @param delegate the delegate's address * @return the index if the delegate exists otherwise return -1 */ function getDelegateIndex( DIDRegisterList storage _self, bytes32 _did, address delegate ) private view returns(int256) { for (uint256 i = 0; i < _self.didRegisters[_did].delegates.length; i++) { if (delegate == _self.didRegisters[_did].delegates[i]) { return int(i); } } return - 1; } }
updateDIDOwner transfer DID ownership to a new owner _self refers to storage pointer _did refers to decentralized identifier (a byte32 length ID) _newOwner the new DID owner address/
function updateDIDOwner( DIDRegisterList storage _self, bytes32 _did, address _newOwner ) internal { require(_newOwner != address(0)); _self.didRegisters[_did].owner = _newOwner; }
12,991,480
./full_match/4/0xf13e93A3dB4283FDAc71aA2Cb59f5FB84119Df2b/sources/browser/HALOTOKEN.sol
transform room initiation
function transformActivate(bool _isActive) public onlyAdmins { roundActive = _isActive; }
12,408,300
/** * (0x%x,2909) Solo une altro contratta che ho fatto. Nel codice ci fidiame. In crito e rifugio. Crito-difese à vita. * * Author: 2021 Crypto Fix Finance and Contributors. BSD 3-Clause Licensed. * Baseate ni Putanas. * Passed compliance checks by 0xFF4 marked XFC. * Final version: need to change router and wallet_xxx only. * v0.4 flex tax, moved Best Common Practice functions to inc/OZBCP.sol to somewhere else. * v0.4.3 brought some initial cryptopanarchy elements, fixed bugs and run unit tests. * v0.4.4 starting to incorporate some properties from my crypto-panarchy model: (f0.1) health, natural disaster, commercial * engagements with particular contract signature, fine, trust chain and finally private arbitration. * v0.5.1 implemented several crypto-panarchy elements into this contract, fully tested so far. * v0.5.2 coded private court arbitration under policentric law model inspired by Tracanelli-Bell prov arbitration model * v0.5.3 added hash based signature to private agreements * v0.5.4 wdAgreement implemented, however EVM contract size is too large, reduced optimizations run as low as 50 * v0.5.5 refactored contract due to size limit (added a library, merged functions, converted public, shortened err messages, etc) * v0.5.6 VolNI & DAO as external contracts interacting with main contract due to contract size and proper architecture * * XXXTODO (Feature List F#): * - {DONE} (f1) taxationMechanisms: HOA-like, convenant community (Hoppe), Tax=Theft (Rothbard), Voluntary Taxation (Objectivism) * - {DONE} (f2) reflection mechanism * - {DONE} (f3) Burn/LP/Reward mechanisms comon to tokens on the surface * - {DONE} (f4) contract management: ownership transfer, resignation; contract lock/unlock, routerUpdate * - (f5) DAO: contractUpgrade, transfer ownership to DAO contract for management * - {DONE} (f6) criar um mecanismo que cobra taxa apenas de transacoes na pool, taxa sobre servico nao circulacao. * - {DONE} (f7) v5.1 add auto health wallet (wallet_health) and private SailBoat insurance (wallet_sailboat||wallet_health) * - {DONE} (f8) account individual contributors to health wallet. * - {DONE} (f9) arbitrated contract mechanism setAgreement(hashDoc,multa,arbitragemScheme,tribunalPrivado,wallet_juiz,assinatura,etc) * - (f10) mechanism for NI (negative income) (maybe import from Seasteading Bahamas Denizens (SeaBSD) * - {DONE} (f11) v5.1 [trustChain] implement 0xff4 trust chain model (DEFCON-like): trust ontology cardinality 1:N:M * - {DONE} (f12) v5.1 [trustChain] firstTrustee, trustPoints[avg,qty], whoYouTrust, whoTrustYou, contractsViolated, optOutArbitrations(max:1) * - {DONE} (f13) v5.1 [trustChain] nickName, pgpPubK, sshPubK, x509pubK, Gecos field, Role field * - {DONE} (f14) v5.1 [trustChain] if you send 0,57721566 tokens to someone and nobody trusted this person before, you become their spFirstTrusteer * - {DONE} (f15) add mechanism to pool negotiation with trustedPersona only * - {DONE} (f16) add generic escrow mechanism allowing the private arbitration (admin) on the trust chain [trustChain] * * Before you deploy: * - Change CONFIG:hardcoded definitions according to this crypto-panarchy immutable terms. * - Change wallet_health initial address. * - Security Audit is done everywhere its noted **/ pragma solidity ^0.8.7; // SPDX-License-Identifier: BSD 3-Clause Licensed. //Author: (0x%x,2909) Crypto Fix Finance // Declara interfaces do ERC20/BEP20/SEP20 importa BCP do OZ e tbm interfaces e metodos da DeFi import "inc/OZBCP.sol"; import "inc/DEFI.sol"; import "inc/LIBXFFA.sol"; contract XFFAv5 is Context, IERC20, Ownable { using SafeMath for uint256; // no reason to keep using SafeMath on solic >= 0.8.x using Address for address; // Algumas propriedades particulares ao self=(msg.sender) e selfPersona (how self is seem or presents himself) struct selfProperties { string sNickname; // name yourself if/how you want: avatar, nick, alias, PGP key, x-persona uint256 sTaxFee; uint256 sLiquidityFee; uint256 sHealthFee; // health insurance fee (f0.1) // finger string sPgpPubK; string sSshPubK; string sX509PubK; string sGecos; // Unix generic commentaries field // trustChain address spFirstTrustee; address[] sYouTrust; address[] spTrustYou; uint256[2] spTrustPoints; // count,points uint256 spContractsViolated; // only the contract will set this uint256 spOptOutArbitrations; // only arbitrators should set this address[] ostracizedBy; // court or judge uint256 sRole; // 0=user, 1=judge/court/arbitrator // private agreements uint256[] spYouAgreementsSigned; } struct subContractProperties { string hash; string gecos; // generic comments describing the contract string url; // ipfs, https, etc uint256 fine; uint256 deposit; // uint instead of bool to save gwei, 1 = required address creator; uint256 createdOn; address arbitrator; // private court or selected judge uint256 arbitratorFee; // in tokens mapping (address => uint256) signedOn; // signees and timestamp mapping (address => string) signedHash; mapping (address => string) signComment; mapping (address => bytes32) signature; mapping (address => uint256) signatureNonce; mapping (address => uint256) finePaid; // bool->uint to save gas mapping (address => uint256) state; // 1=active/signed, 2=want_friendly_terminate, 3=want_dispute, 4=won_dispute, 5=lost_dispute, 21=friendly_withdrawaled, 41=disputed_wdled, 91=arbitrator_wdled 99=disputed_outside(ostracized) address[] signees; // list of who signed this contract } mapping (address => selfProperties) private _selfDetermined; mapping (uint256 => subContractProperties) private _privLawAgreement; uint256[] public _privLawAgreementIDs; //OLD version mapping (address => mapping (address => uint256)) private _selfDeterminedFees;// = [_taxFee, _liquidityFee, _healthFee]; // _rOwned e _tOwned melhores praticas do SM (conformidade com OpenZeppelin tbm) mapping (address => uint256) private _rOwned; mapping (address => uint256) private _tOwned; mapping (address => mapping (address => uint256)) private _allowances; mapping (address => bool) private _isExcludedF; // marca essa flag na wallet que nao paga fee mapping (address => bool) private _isExcludedR; // marca essa flag na wallet que nao recebe dividendos address[] private _excluded; address private wallet_health = 0x8c348A2a5Fd4a98EaFD017a66930f36385F3263A; //owner(); // Mudar para wallet health mapping (address => uint256) public healthDepositTracker; // (f8) track who deposits to bealth uint8 private constant _decimals = 8; // Auditoria XFC-05: constante uint256 private constant MAX = ~uint256(0); uint256 private constant _tTotal = 29092909 * 10**_decimals; // 2909 2909 milhoes Auditoria XFC-05: constante + decimals precisao cientifica pq das matematicas zoadas do sol uint256 private _rTotal = (MAX - (MAX % _tTotal)); uint256 private _tFeeTotal; string private constant _name = "Coin 0xFF4"; // Auditoria XFC-05: constante string private constant _symbol = "XFFA"; //Auditoria XFC-05: constante uint256 private _maxTassazione = 8; // tassazione massima, hello Trieste Friulane (CONFIG:hardcoded) uint256 private _taxFee = 1; // taxa pra dividendos uint256 private _previousTaxFee = _taxFee; // inicializa uint256 private _liquidityFee = 1; // taxa pra LP uint256 private _previousLiquidityFee = _liquidityFee; // inicializa uint256 private _burnFee = 1; // taxa de burn (deflacao) por operacao estrategia de deflacao continua (f3) uint256 private _previousBurnFee = _burnFee; // inicializa (f3) uint256 private _healthFee = 1; // Em porcentagem, fee direto pra health uint256 private _prevHealthFee = _healthFee; // Em porcentagem, fee direto pra health IUniswapV2Router02 public uniswapV2Router; address public uniswapV2Pair; bool inSwapAndLiquify; // liga e desliga o mecanismo de liquidez bool private swapAndLiquifyEnabled = false; // inicializa uint256 private _maxTxAmount = 290900 * 10**_decimals; // mandei 290.9k max transfer que da 1% do supply inicial (nao do circulante, logo isso muda com o tempo) uint256 private numTokensSellToAddToLiquidity = 2909 * 10**_decimals; // 2909 minimo de tokens pra adicionar na LP se estiver abaixo event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap); event SwapAndLiquifyEnabledUpdated(bool enabled); // liga event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity); event AuthZ(uint256 _reason); modifier travaSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } /** * spOptOutArbitrations means a private law Court or selected arbitrator associated to a secondary * contract was ruled out because the party opted out exterritorial private crypto-panarchy society * going back to nation-state rule of law which is an explicity opt-out from our crypto-panarchy. * Maybe the ostracized x-persona invoked other arbitration mechanism outside this main contract * or outside the secondary contract terms. Usually it's less radical, therefore the ruling courts * should be asked. Court/judge address() is identifiable when it happens. This persona shall be * ostracized, boycotted or even physically removed from all states of affair related to this * contract. If by any means he is accepted back, should be another address as this operation is * not reversible. * **/ modifier notPhysicallyRemoved() { _notPhysicallyRemoved(); _; } function _notPhysicallyRemoved() internal view { require(_selfDetermined[_msgSender()].spOptOutArbitrations < 1, "A2: ostracized"); // ostracized } constructor () { _rOwned[_msgSender()] = _rTotal; //IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E); // PRD //IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x928Add24A9dd3E76e72aD608c91C2E3b65907cdD); // Address for DeFi at Kooderit (FIX) //IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0xD99D1c33F9fC3444f8101754aBC46c52416550D1); // BSC Testnet IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7186Fe885Db3402102250bD3d79b7914c61414b1); // CryptoFIX Finance (FreeBSD) // Cria o parzinho Token/COIN pra swap e recebe endereco uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); //uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), address(0x465e07d6028830124BE2E4aA551fBe12805dB0f5)); // Wrapped XMR (Monero) // recebe as outras variaveis do contrato via IUniswapV2Router02 uniswapV2Router = _uniswapV2Router; //owner e o proprio contrato nao pagam fee inicialmente _isExcludedF[owner()] = true; _isExcludedF[address(this)] = true; // _isExcludedF[wallet_health] = true; emit Transfer(address(0), _msgSender(), _tTotal); } // Auditoria XFC-05: view->pure nos 4 function name() public pure returns (string memory) { return _name; } function symbol() public pure returns (string memory) { return _symbol; } function decimals() public pure returns (uint256) { return _decimals; } function totalSupply() public pure override returns (uint256) { return _tTotal; } // Checa saldo dividendos da conta function balanceOf(address account) public view override returns(uint256) { if (_isExcludedR[account]) return _tOwned[account]; return tokenFromReflection(_rOwned[account]); // (f2) } function transfer(address recipient, uint256 amount) public override notPhysicallyRemoved() returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override notPhysicallyRemoved() returns(uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override notPhysicallyRemoved() returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override notPhysicallyRemoved() returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual notPhysicallyRemoved() returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual notPhysicallyRemoved() returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function isExcludedFromReward(address account) public view returns (bool) { return _isExcludedR[account]; } function totalFees() public view returns (uint256) { return _tFeeTotal; } // XFC-04 Compliance: documentando funcao de saque. used2b reflect() no token reflect // Implementar na Web3 um mecanismo pra facilitar uso. (f2) function wdSaque(uint256 tQuantia) public notPhysicallyRemoved() { address remetente = _msgSender(); require(!_isExcludedR[remetente], "A2: ur excluded"); // Excluded address can not call this function (uint256 rAmount,,,,,) = _getValues(tQuantia); _rOwned[remetente] = _rOwned[remetente].sub(rAmount); _rTotal = _rTotal.sub(rAmount); _tFeeTotal = _tFeeTotal.add(tQuantia); } // To calculate the token count much more precisely, you convert the token amount into another unit. // This is done in this helper function: "reflectionFromToken()". Code came from Reflect Finance project. (f2) function reflectionFromToken(uint256 tQuantia, bool deductTransferFee) public view returns(uint256) { require(tQuantia <= _tTotal, "E:Amount > supply"); // Amount must be less than supply" if (!deductTransferFee) { (uint256 rAmount,,,,,) = _getValues(tQuantia); return rAmount; } else { (,uint256 rTransferAmount,,,,) = _getValues(tQuantia); return rTransferAmount; } } // Inverse operation. (f2) function tokenFromReflection(uint256 rAmount) public view returns(uint256) { require(rAmount <= _rTotal, "E:Amount > reflections total"); // Amount must be less than total reflections uint256 currentRate = _getRate(); return rAmount.div(currentRate); } function excluiReward(address account) public onlyOwner() { require(!_isExcludedR[account], "Already excluded"); if(_rOwned[account] > 0) { _tOwned[account] = tokenFromReflection(_rOwned[account]); // (f2) } _isExcludedR[account] = true; _excluded.push(account); } function incluiReward(address account) external onlyOwner() { require(_isExcludedR[account], "Not excluded"); // Auditoria XFC-06 Account is not excluded for (uint256 i = 0; i < _excluded.length; i++) { if (_excluded[i] == account) { _excluded[i] = _excluded[_excluded.length - 1]; _tOwned[account] = 0; _isExcludedR[account] = false; _excluded.pop(); break; } } } function _transferBothExcluded(address sender, address recipient, uint256 tQuantia) private { (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tQuantia); _tOwned[sender] = _tOwned[sender].sub(tQuantia); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); // (f2) emit Transfer(sender, recipient, tTransferAmount); } function excludeFromFee(address account) public onlyOwner { _isExcludedF[account] = true; } function includeInFee(address account) public onlyOwner { _isExcludedF[account] = false; } // Permite redefinir taxa maxima de transfer, assume compromisso hardcoded de sempre ser menor que 8% (convenant community rules) function setBurnFeePercent(uint256 burnFee) external onlyOwner() { _burnFee = burnFee; } // burn nao e tax (f3) function setTaxFeePercent(uint256 taxFee) external onlyOwner() { require((taxFee+_liquidityFee+_healthFee)<=_maxTassazione,"Taxation is Theft"); // Taxation without representation is Theft _taxFee = taxFee; } function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() { require((liquidityFee+_taxFee+_healthFee)<=_maxTassazione,"Taxation is Theft"); _liquidityFee = liquidityFee; } function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() { require(maxTxPercent <= 8,"Taxation wo representation is Theft"); _maxTxAmount = _tTotal.mul(maxTxPercent).div( 10**2 ); // Regra de 3 pra porcentagem } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } //recebe XMR/ETH/BNB/BCH do uniswapV2Router quando fizer swap - Auditoria: XFC-07 receive() external payable {} // subtrai rTotal e soma fee no fee tFeeTotal (f2) function _reflectFee(uint256 rFee, uint256 tFee) private { _rTotal = _rTotal.sub(rFee); _tFeeTotal = _tFeeTotal.add(tFee); } // From SM/OZ function _getValues(uint256 tQuantia) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) { (uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tQuantia); (uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tQuantia, tFee, tLiquidity, _getRate()); return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity); } // From SM/OZ function _getTValues(uint256 tQuantia) private view returns (uint256, uint256, uint256) { uint256 tFee = calculateTaxFee(tQuantia); uint256 tLiquidity = calculateLiquidityFee(tQuantia); uint256 tTransferAmount = tQuantia.sub(tFee).sub(tLiquidity); return (tTransferAmount, tFee, tLiquidity); } // From SM/OZ function _getRValues(uint256 tQuantia, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) { uint256 rAmount = tQuantia.mul(currentRate); uint256 rFee = tFee.mul(currentRate); uint256 rLiquidity = tLiquidity.mul(currentRate); uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity); return (rAmount, rTransferAmount, rFee); } // From SM/OpenZeppelin function _getRate() private view returns(uint256) { (uint256 rSupply, uint256 tSupply) = _getCurrentSupply(); return rSupply.div(tSupply); } // From SM/OpenZeppelin function _getCurrentSupply() private view returns(uint256, uint256) { uint256 rSupply = _rTotal; uint256 tSupply = _tTotal; for (uint256 i = 0; i < _excluded.length; i++) { if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal); rSupply = rSupply.sub(_rOwned[_excluded[i]]); tSupply = tSupply.sub(_tOwned[_excluded[i]]); } if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal); return (rSupply, tSupply); } // Recebe liquidity function _takeLiquidity(uint256 tLiquidity) private { uint256 currentRate = _getRate(); uint256 rLiquidity = tLiquidity.mul(currentRate); _rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity); if(_isExcludedR[address(this)]) _tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity); } function calculateTaxFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_taxFee).div(10**2); // regra de 3 pra achar porcentagem } function calculateLiquidityFee(uint256 _amount) private view returns (uint256) { return _amount.mul(_liquidityFee).div(10**2); // regra de 3 pra achar porcentagem } function removeAllFee() private { if(_taxFee == 0 && _liquidityFee == 0 && _burnFee == 0) return; //(f3) _previousTaxFee = _taxFee; _previousLiquidityFee = _liquidityFee; _previousBurnFee = _burnFee; _prevHealthFee = _healthFee; _taxFee = 0; _liquidityFee = 0; _burnFee = 0; _healthFee = 0; } function restoreAllFee() private { _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; _burnFee = _previousBurnFee; // (f3) _healthFee = _prevHealthFee; } function isExcludedFromFee(address account) public view returns(bool) { return _isExcludedF[account]; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "E: addr zero?"); // ERC20: approve from the zero address require(spender != address(0), "E: addr zero?"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer( address from, address to, uint256 amount) private { require(from != address(0), "E: addr zero?"); // ERC20: transfer from the zero address require(amount > 0, "Amount too low"); // Transfer amount must be greater than zero if(from == uniswapV2Pair || to == uniswapV2Pair) // if DeFi, must be trusted (f15), owner is no exception T:OK (CONFIG:hardcoded) require(_selfDetermined[to].spFirstTrustee!=address(0)||_selfDetermined[from].spFirstTrustee!=address(0),"A2: DeFi limited to trusted. Use p2p"); // (f15) T:OK DeFi service limited to trusted x-persona. Use p2p. if(from != owner() && to != owner()) require(amount <= _maxTxAmount, "Amount too high"); // Transfer amount exceeds the maxTxAmount. uint256 contractTokenBalance = balanceOf(address(this)); if(contractTokenBalance >= _maxTxAmount) { contractTokenBalance = _maxTxAmount; } // Se a liquidez do pool estiver muito baixa (numTokensSellToAddToLiquidity) vamos vender // pra colocar na LP. bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity; if (overMinTokenBalance && !inSwapAndLiquify && from != uniswapV2Pair && swapAndLiquifyEnabled) { contractTokenBalance = numTokensSellToAddToLiquidity; //add liquidity swapAndLiquify(contractTokenBalance); } //indicates if fee should be deducted from transfer bool takeFee = true; // default true // (f6) dont charge fees on p2p transactions. comment out (CONFIG:hardcoded) if this crypto-panarchy wants different if (from != uniswapV2Pair && to!= uniswapV2Pair) { takeFee = false; } // maybe make it configurable? if (to == wallet_health) { healthDepositTracker[from].add(amount); } // (f8,f7) keep track of who contributes more to health funds //if any account belongs to _isExcludedF account then remove the fee if(_isExcludedF[from] || _isExcludedF[to]){ takeFee = false; } //transfer amount, it will take tax, burn, liquidity fee _tokenTransfer(from,to,amount,takeFee); } function swapAndLiquify(uint256 contractTokenBalance) private travaSwap { // split the contract balance into halves - Auditoria XFC-08: points a bug and a need to a withdraw function to get leftovers uint256 half = contractTokenBalance.div(2); uint256 otherHalf = contractTokenBalance.sub(half); // computa apenas os XMR/ETH/BNB/BCH da transacao, excetuando o que eventualmente ja houver no contrato uint256 initialBalance = address(this).balance; // metade do saldo em crypto swapTokensForEth(half); // <- this breaks the ETH -> TOKEN swap when swap+liquify is triggered // saldo atual em crypto uint256 newBalance = address(this).balance.sub(initialBalance); // segunda metade em token - Auditoria XFC-08: points a bug and a need to a withdraw function to get leftovers addLiquidity(otherHalf, newBalance); emit SwapAndLiquify(half, newBalance, otherHalf); // Referencia: event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiqudity); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // faz o swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(tokenAmount, 0, // aceita qualquer valor de ETH sem minimo path, address(this), block.timestamp); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity - Auditoria: XFC-09 unhandled uniswapV2Router.addLiquidityETH{value: ethAmount}(address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable address(this), // owner(), Auditoria XFC-02 block.timestamp); } //metodo das taxas se takeFee for true function _tokenTransfer(address sender, address recipient, uint256 amount,bool takeFee) private { if(!takeFee) removeAllFee(); //_healthFee = 1; // Em porcentagem // modifica o health na origem individualmente if (_selfDetermined[sender].sHealthFee >= _healthFee || _selfDetermined[sender].sHealthFee == 999 ) { _healthFee = _selfDetermined[sender].sHealthFee; if (_selfDetermined[sender].sHealthFee == 999) { _healthFee = 0; } // 999 na blockchain eh 0 para nos } uint256 burnAmt = amount.mul(_burnFee).div(100); uint256 healthAmt = amount.mul(_healthFee).div(100); // N% direto pra health? discutir ou por hora manter 0 uint256 discountAmt=(burnAmt+healthAmt); // sera descontado do total a transferir /** (note que a unica tx real eh a da health, o resto reverte pra todos e pra saude da pool) **/ // Respeitar fees individuais, precedencia de quem paga (origem): dividendos if (_selfDetermined[sender].sTaxFee >= _taxFee || _selfDetermined[recipient].sTaxFee >= _taxFee || _selfDetermined[sender].sTaxFee == 999 || _selfDetermined[recipient].sTaxFee == 999) { if (_selfDetermined[sender].sTaxFee > _selfDetermined[recipient].sTaxFee) { _taxFee = _selfDetermined[sender].sTaxFee; if (_selfDetermined[sender].sTaxFee == 999) { _taxFee = 0; } } else { _taxFee = _selfDetermined[recipient].sTaxFee; if (_selfDetermined[recipient].sTaxFee == 999) { _taxFee = 0; } } } // Respeitar fees individuais, precedencia de quem paga (origem): liquidez if (_selfDetermined[sender].sLiquidityFee >= _liquidityFee || _selfDetermined[recipient].sLiquidityFee >= _liquidityFee || _selfDetermined[sender].sLiquidityFee == 999 || _selfDetermined[recipient].sLiquidityFee == 999) { if (_selfDetermined[sender].sLiquidityFee > _selfDetermined[recipient].sLiquidityFee) { _liquidityFee = _selfDetermined[sender].sLiquidityFee; if (_selfDetermined[sender].sLiquidityFee == 999) { _liquidityFee = 0; } } else { _liquidityFee = _selfDetermined[recipient].sLiquidityFee; if (_selfDetermined[recipient].sLiquidityFee == 999) { _liquidityFee = 0; } } } // Taxas considerando exclusao de recompensa if (_isExcludedR[sender] && !_isExcludedR[recipient]) { _transferFromExcluded(sender, recipient, amount.sub(discountAmt)); } else if (!_isExcludedR[sender] && _isExcludedR[recipient]) { _transferToExcluded(sender, recipient, amount.sub(discountAmt)); // XFC-10 excluded } else if (!_isExcludedR[sender] && !_isExcludedR[recipient]) { // XFC-10 excluded _transferStandard(sender, recipient, amount); } else if (_isExcludedR[sender] && _isExcludedR[recipient]) { _transferBothExcluded(sender, recipient, amount.sub(discountAmt)); } else if (!_isExcludedR[sender] && !_isExcludedR[recipient]) { _transferStandard(sender, recipient, amount.sub(discountAmt)); // XFC-10 condition above added } // Depois de feitas as transferencias entre os pares, o proprio contrato nao paga taxas _taxFee = 0; _liquidityFee = 0; _healthFee = 0; // sobrou discountAmt precisamos enviar pras carteiras de direito, burn e health _transferStandard(sender, address(0x000000000000000000000000000000000000dEaD), burnAmt); // envia pro burn 0x0::dEaD a fee configurada sem gambi de burn holder _transferStandard(sender, address(wallet_health), healthAmt); // (f7) pay fee to health wallet, debate it widely with this panarchy healthDepositTracker[sender].add(healthAmt); // (f8) keep track of who contributes more to health funds // Restaura as taxas _taxFee = _previousTaxFee; _liquidityFee = _previousLiquidityFee; _healthFee = _prevHealthFee; if(!takeFee) restoreAllFee(); } function _transferStandard(address sender, address recipient, uint256 tQuantia) private { if ( (tQuantia==57721566) && (_selfDetermined[recipient].spFirstTrustee == address(0)) ) { _selfDetermined[recipient].spFirstTrustee = sender; _selfDetermined[sender].sYouTrust.push(recipient); _selfDetermined[recipient].spTrustYou.push(sender); } // again, first trustee: know what you are doing. send 0,57721566 its our magic number (Euler constant) T:OK:f14 (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tQuantia); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); // (f2) emit Transfer(sender, recipient, tTransferAmount); } function _transferToExcluded(address sender, address recipient, uint256 tQuantia) private { if ( (tQuantia==57721566) && (_selfDetermined[recipient].spFirstTrustee == address(0)) ) { _selfDetermined[recipient].spFirstTrustee = sender; _selfDetermined[sender].sYouTrust.push(recipient); _selfDetermined[recipient].spTrustYou.push(sender); } // again, first trustee: know what you are doing. send 0,57721566 its our magic number (Euler constant) (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tQuantia); _rOwned[sender] = _rOwned[sender].sub(rAmount); _tOwned[recipient] = _tOwned[recipient].add(tTransferAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); // (f2) emit Transfer(sender, recipient, tTransferAmount); } function setRouterAddress(address novoRouter) public onlyOwner() { //Ideia boa do FreezyEx, permite mudar o router da Pancake pra upgrade. Atende tambem compliace XFC-03 controle de. external & 3rd party IUniswapV2Router02 _newPancakeRouter = IUniswapV2Router02(novoRouter); uniswapV2Pair = IUniswapV2Factory(_newPancakeRouter.factory()).createPair(address(this), _newPancakeRouter.WETH()); uniswapV2Router = _newPancakeRouter; } function _transferFromExcluded(address sender, address recipient, uint256 tQuantia) private { if ( (tQuantia==57721566) && (_selfDetermined[recipient].spFirstTrustee == address(0)) ) { _selfDetermined[recipient].spFirstTrustee = sender; _selfDetermined[sender].sYouTrust.push(recipient); _selfDetermined[recipient].spTrustYou.push(sender); } // again, first trustee: know what you are doing. send 0,57721566 its our magic number (Euler constant) (uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tQuantia); _tOwned[sender] = _tOwned[sender].sub(tQuantia); _rOwned[sender] = _rOwned[sender].sub(rAmount); _rOwned[recipient] = _rOwned[recipient].add(rTransferAmount); _takeLiquidity(tLiquidity); _reflectFee(rFee, tFee); // (f2) emit Transfer(sender, recipient, tTransferAmount); } /** * "In a fully free society, taxation—or, to be exact, payment for governmental services—would be voluntary. * Since the proper services of a government—the police, the armed forces, the law courts—are demonstrably needed * by individual citizens and affect their interests directly, the citizens would (and should) be willing to pay * for such services, as they pay for insurance.", Virtue of Selfishness (1964) Chapter 15 * * Verifichiamo allora nella pratica questa irragionevole ipotesi teorica di tassazione volontaria. Chiamiamo la funzione aynRand, * per consentire al singolo chiamante di sospendere le proprie quote, accettare la quota associativa o impostare la propria * proprio canone. Bene che metta alla prova anche la benevolenza contro l'altruismo (Auguste Comte 1798-1857) e il consenso su * Termini del consenso della allianza privata - convenant community (Hans H. Hoppe, diversi scritti). * // T:OK:(f1) */ function aynRandTaxation(uint256 TaxationIsTheft, uint256 convernantCommunityTaxes, uint256 indTaxFee, uint256 indLiquidFee, uint256 indHealthFee) public { // booleans are expensive, save gas. pass 1 as true to TaxationIsTheft if (TaxationIsTheft==1) { excludeFromFee(msg.sender); excluiReward(msg.sender); // sem tax sem dividendos } else if ((TaxationIsTheft!=1) && (convernantCommunityTaxes==1)) { // restoreAllFee() se imposto nao e roubo e Hoppe estava certo (sobre acerto da alianca privada) _selfDetermined[msg.sender].sHealthFee = _healthFee; _selfDetermined[msg.sender].sLiquidityFee = _liquidityFee; _selfDetermined[msg.sender].sTaxFee = _taxFee; //_individualFee = [_taxFee, _liquidityFee, _healthFee]; } else { // define os 'impostos voluntarios' auto determinados if (indHealthFee==0) indHealthFee=999; if (indLiquidFee==0) indLiquidFee=999; if (indTaxFee==0) indTaxFee=999; // pra economizar gas nao vamos testar booleano se variavel foi inicializada entao consideraremos 0% com o valor especial 999 _selfDetermined[msg.sender].sHealthFee = indHealthFee; _selfDetermined[msg.sender].sLiquidityFee = indLiquidFee; _selfDetermined[msg.sender].sTaxFee = indTaxFee; //_individualFee = [indTaxFee, indLiquidFee, indHealthFee]; } } // T:OK:(f0.1) function setHealthWallet(address newHealthAddr) public onlyOwner() returns(bool) { wallet_health = newHealthAddr; return true; } // T:OK:(f1):default fees and caller fees function getFees() public view returns(uint256,uint256,uint256,uint256,uint256,uint256) { return (_healthFee,_liquidityFee,_taxFee,_selfDetermined[msg.sender].sHealthFee,_selfDetermined[msg.sender].sLiquidityFee,_selfDetermined[msg.sender].sTaxFee); } // T:OK (f13): nickname handling merged to finger to save gas and contract size // T:OK (f13): refactorado per l'uso require() if (bytes(_selfDetermined[endereco].sNickname).length == 0) return _selfDetermined[endereco].sNickname; // XXX_Todo: implementar modificador onlyPrivLawCourt caso torne essa funcao publica // testar notPhysicallyRemoved() (DONE) e setViolations unitariamente // T:PEND (f12):Dropped this function. Included in setArbitration() /* function setViolations(uint256 _violationType, address _who) internal notPhysicallyRemoved() returns(uint256 _spContractsViolated) { require(_violationType>=0&&_violationType<=2,"A2 bad type"); // AuthZ: violation types: 0 (contracts) or 1 (arbitration) if (_violationType==1) { // worse case scenario: kicked out out crypto-panarchy _selfDetermined[_who].spOptOutArbitrations.add(1); _selfDetermined[_who].ostracizedBy.push(_msgSender()); } else _selfDetermined[_who].spContractsViolated.add(1); return(_selfDetermined[_who].spContractsViolated); }*/ // T:OK (f12) function setTrustPoints(address _who, uint256 _points) public notPhysicallyRemoved() { require((_points >= 0 && _points <= 5),"E: points 0-5"); // AuthZ: points must be 0-5 require(_who!=_msgSender(),"A2: points to self"); // AuthZ: you can't set points to yourself. _selfDetermined[_who].spTrustPoints = [ _selfDetermined[_who].spTrustPoints[0].add(1), // count++ _selfDetermined[_who].spTrustPoints[1].add(_points) // give points // Save gas, let the client find the average _selfDetermined[_who].spTrustPoints[2]=_selfDetermined[_who].spTrustPoints[1].div(_selfDetermined[_who].spTrustPoints[0]) // calculates new avg ]; _selfDetermined[_who].spTrustPoints = [ _selfDetermined[_msgSender()].spTrustPoints[0].add(1), // count++ _selfDetermined[_msgSender()].spTrustPoints[1].sub(_points) // subtracts points from giver ]; } // T:OK (f12):merged to trustchain function getTrustPoints(address _who) /* function getTrustPoints(address _who) public view returns(uint256[2] memory _currPoints) { return(_selfDetermined[_who].spTrustPoints); }*/ /* XXX_Lembrar_de_Remover XXX_implement point system upon contracts or make setTrustPoints public (f12) function vai(address _who) public { setTrustPoints(_who,1); setTrustPoints(_who,2); setTrustPoints(_who,3); } */ //T:OK (f13) function setFinger(string memory _sPgpPubK,string memory _sSshPubK,string memory _sX509PubK,string memory _sGecos,uint256 _sRole, string memory _sNickname) public notPhysicallyRemoved() { _selfDetermined[_msgSender()].sPgpPubK=_sPgpPubK; _selfDetermined[_msgSender()].sSshPubK=_sSshPubK; _selfDetermined[_msgSender()].sX509PubK=_sX509PubK; _selfDetermined[_msgSender()].sGecos=_sGecos; _selfDetermined[_msgSender()].sRole=_sRole; _selfDetermined[_msgSender()].sNickname=_sNickname; } // T:OK (f11) function setWhoUtrust(uint256 mode,address _youTrust) public notPhysicallyRemoved() returns(uint256 _len) { require(_selfDetermined[_msgSender()].sYouTrust.length < 150,"A2: trustChain too big"); // convenant size limit = (Dunbar's number: 150, Bernard–Killworth median: 231); if (owner()!=_msgSender()) { require(_msgSender()!=_youTrust,"A2: no trust self"); // AuthZ: you can't trust yourself require(_youTrust!=uniswapV2Pair,"A2: no trust pair"); // AuthZ: you can't trust special contracts } // mode 1 is to delete from your trust list (you are not a trustee), bool->int to save gwei if (mode==1) { // Delete from your Trustee array for (uint256 i = 0; i < _selfDetermined[_msgSender()].sYouTrust.length; i++) { if (_selfDetermined[_msgSender()].sYouTrust[i] == _youTrust) { _selfDetermined[_msgSender()].sYouTrust[i] = _selfDetermined[_msgSender()].sYouTrust[_selfDetermined[_msgSender()].sYouTrust.length - 1]; _selfDetermined[_msgSender()].sYouTrust.pop(); break; } } // Delete from their Trustee array for (uint256 i = 0; i < _selfDetermined[_youTrust].spTrustYou.length; i++) { if (_selfDetermined[_youTrust].spTrustYou[i] == _msgSender()) { _selfDetermined[_youTrust].spTrustYou[i] = _selfDetermined[_youTrust].spTrustYou[_selfDetermined[_youTrust].spTrustYou.length - 1]; _selfDetermined[_youTrust].spTrustYou.pop(); break; } } } else { _selfDetermined[_msgSender()].sYouTrust.push(_youTrust); // control who you trust if (_selfDetermined[_youTrust].spFirstTrustee == address(0)) // you are the first x-persona to trust him, hope you know what you are doing _selfDetermined[_youTrust].spFirstTrustee = _msgSender(); // it's not reversible _selfDetermined[_youTrust].spTrustYou.push(_msgSender()); // inform the party you trust him } return(_selfDetermined[_msgSender()].sYouTrust.length); // extra useful info } // T:OK (f13) function Finger(address _who) public view returns(string memory _sPgpPubK,string memory _sSshPubK,string memory _sX509PubK,string memory _sGecos,uint256 _sRole, string memory _sNickname) { return (_selfDetermined[_who].sPgpPubK,_selfDetermined[_who].sSshPubK,_selfDetermined[_who].sX509PubK,_selfDetermined[_who].sGecos,_selfDetermined[_who].sRole,_selfDetermined[_who].sNickname); } // T:OK (f11) function getTrustChain(address _who) public view returns( address _firstTrustee, address[] memory _youTrust, uint256 _youTrustCount, address[] memory _theyTrustU, uint256 _theyTrustUcount, uint256[] memory _youAgreementsSigned, uint256[2] memory _yourTrustPoints ) { return ( _selfDetermined[_who].spFirstTrustee, _selfDetermined[_who].sYouTrust, _selfDetermined[_who].sYouTrust.length, _selfDetermined[_who].spTrustYou, _selfDetermined[_who].spTrustYou.length, _selfDetermined[_who].spYouAgreementsSigned, _selfDetermined[_who].spTrustPoints ); } /** * In una società di diritto privato gli individui acconsentono volontariamente ai servizi e agli scambi appaltati * e quindi, devono concordare le clausole di uscita ammende, se applicabili, se il deposito deve essere versato in * anticipo o le parti concorderanno di pagare alla risoluzione del contratto. Un tribunale di diritto privato o selezionato * il giudice deve essere scelto come arbitri da tutte le parti di comune accordo. Una controversia deve essere * avviato dalle parti che hanno firmato il contratto. Viene avviata una controversia, solo l'arbitro deve * decidere sui motivi. I trasgressori illeciti pagheranno la multa a tutte le altre parti e contrarranno * la violazione sarà incrementata dall'arbitro. Non viene avviata alcuna controversia, le parti sono d'accordo * in caso di scioglimento dell'accordo. L'accordo viene sciolto, tutti i firmatari vengono rimborsati delle multe. * In una società cripto-panarchica, l'arbitrato del tribunale privato deve essere codificato. I Cypherpunk scrivono codice. * * T:OK (f9) **/ // T:OK:(f9) function setAgreement(uint256 _aid, string memory _hash, string memory _gecos, string memory _url, string memory _signedHash, uint256 _fine, address _arbitrator, uint256 _arbitratorFee, uint256 _deposit, string memory _signComment,uint256 _sign) notPhysicallyRemoved public { require(_aid>0,"A2: bad id"); // AuthZ: ivalid id for private agreement require(_selfDetermined[_arbitrator].sRole==1,"A2: court must be Role=1"); // A2: arbitrator or court must set himself Role=1 if(_privLawAgreement[_aid].creator==address(0)) { // doesnt exist, create it _privLawAgreement[_aid].hash=_hash; _privLawAgreement[_aid].gecos=_gecos; _privLawAgreement[_aid].url=_url; _privLawAgreement[_aid].fine=_fine; _privLawAgreement[_aid].deposit=_deposit; // 1 = required _privLawAgreement[_aid].creator=msg.sender; _privLawAgreement[_aid].arbitrator=_arbitrator; _privLawAgreement[_aid].arbitratorFee=_arbitratorFee; _privLawAgreement[_aid].createdOn=block.timestamp; _privLawAgreementIDs.push(_aid); } else { // exists, sign it _setAgreementSign(_aid, _hash, _signedHash, _fine, _arbitrator, _signComment, _sign); } } //T:PEND:(f9):Sign existing agreement. Separated non-public functions to save gas function _setAgreementSign(uint256 _aid, string memory _hash, string memory _signedHash, uint256 _fine, address _arbitrator, string memory _signComment, uint256 _sign) internal { require(_fine==_privLawAgreement[_aid].fine,"A2: bad fine"); // AuthZ: fine value mismatch require(keccak256(abi.encode(_hash))==keccak256(abi.encode(_privLawAgreement[_aid].hash)),"A2: bad hash"); // AuthZ: must reaffirm hash acceptance require(msg.sender!=_arbitrator,"A2: court can't be party"); // AuthZ: arbitrator can not take part of the agreement require(_sign==1,"A2: sign it! (aid)"); // AuthZ: agreement ID exists, explicitly consent to sign it _privLawAgreement[_aid].fine=_fine; _privLawAgreement[_aid].signedOn[msg.sender]=block.timestamp; _privLawAgreement[_aid].signedHash[msg.sender]=_signedHash; _privLawAgreement[_aid].signComment[msg.sender]=_signComment; if (_privLawAgreement[_aid].finePaid[msg.sender]==0 && _privLawAgreement[_aid].deposit==1) { // must deposit fine in advance in this contract require(balanceOf(_msgSender()) >= _fine,"E: balance is below fine"); // ERC20: balance below required fine amount, cant sign agreement transfer(address(this), _fine); // transfer fine deposit to contract T:BUG //_transfer(_msgSender(), recipient, amount); _privLawAgreement[_aid].finePaid[msg.sender]=1; } (_privLawAgreement[_aid].signature[msg.sender], _privLawAgreement[_aid].signatureNonce[msg.sender]) = xffa.simpleSignSaltedHash("I hereby consent aid"); _selfDetermined[msg.sender].spYouAgreementsSigned.push(_aid); _privLawAgreement[_aid].signees.push(msg.sender); _privLawAgreement[_aid].state[msg.sender]=1; // mark active } // T:PEND(MERGE):(f9):Allows one to get agreement data and someone's termos to agreement aid function getAgreementData(uint256 _aid, address _who) public view returns (string memory, string memory, string memory) { require(_privLawAgreement[_aid].creator!=address(0),"A2: bad aid"); // AuthZ: agreement ID is nonexistant //require(_privLawAgreement[_aid].signedOn[_who]!=0,"AuthZ: this x-persona did not sign this agreement ID"); bool _validSign = xffa.verifySimpleSignSaltedHash(_privLawAgreement[_aid].signature[_who],_who,"I hereby consent aid",_privLawAgreement[_aid].signatureNonce[_who]); string memory _vLabel = "false"; if (_validSign==true) _vLabel = "true"; return( // specifics for signee (_who) string(abi.encodePacked( " _signedHash ",_privLawAgreement[_aid].signedHash[_who], " _signComment ",_privLawAgreement[_aid].signComment[_who], " _signatureValid ",_vLabel," _signedOn ",xffa.uint2str(_privLawAgreement[_aid].signedOn[_who]), " _finePaid ",xffa.uint2str(_privLawAgreement[_aid].finePaid[_who]), " _state ",xffa.uint2str(_privLawAgreement[_aid].state[_who]) )), // agreement generics (everyone) string(abi.encodePacked(" _creator ",xffa.anyToStr(_privLawAgreement[_aid].creator), " _hash ",_privLawAgreement[_aid].hash," _arbitrator ",xffa.anyToStr(_privLawAgreement[_aid].arbitrator), " _arbitratorFee ", xffa.anyToStr(_privLawAgreement[_aid].arbitratorFee), " _fine ",xffa.uint2str(_privLawAgreement[_aid].fine)," _gecos ",_privLawAgreement[_aid].gecos, " _url ",_privLawAgreement[_aid].url )), // stack too deep (after merge) string(abi.encodePacked(" _deposit ",xffa.uint2str(_privLawAgreement[_aid].deposit) )) ); } // XXX_Pend: continuar daqui // T:PEND function _vai(uint256 _aid) public { _privLawAgreement[_aid].signees.push(0xD1E1aF95A1Fb9000c0fEe549cD533903DaB8f715); _privLawAgreement[_aid].signees.push(0x37bB9cC8bf230f5bB11eDC20894d091943f3FdCE); _privLawAgreement[_aid].signees.push(0x3644B986B3F5Ba3cb8D5627A22465942f8E06d09); _privLawAgreement[_aid].signees.push(0x000000000000000000000000000000000000dEaD); _privLawAgreement[_aid].state[0xD1E1aF95A1Fb9000c0fEe549cD533903DaB8f715]=2; _privLawAgreement[_aid].state[0x37bB9cC8bf230f5bB11eDC20894d091943f3FdCE]=2; _privLawAgreement[_aid].state[0x3644B986B3F5Ba3cb8D5627A22465942f8E06d09]=_aid; _privLawAgreement[_aid].state[0x000000000000000000000000000000000000dEaD]=2; } //T:OK:(f9):Allows one to get all signees to a given agreement id function getAgreementSignees(uint256 _aid) public view returns(address[] memory _signees) { return (_privLawAgreement[_aid].signees); } //T:OK:(f9):Allow to test if agreement is settled peacefully (state=2) or not. Returns the first who did not agree if not settled. function isSettledAgreement(uint256 _aid) public view returns(bool, address _who) { address _whod; for (uint256 n=0; n<_privLawAgreement[_aid].signees.length;n++) { _whod = _privLawAgreement[_aid].signees[n]; if (_privLawAgreement[_aid].state[_whod]!=2) return (false,_whod); } return (true,address(0)); } //T:OK:(f9):A non public version of the previous function, for testing and not informational function _isSettledAgreement(uint256 _aid) private view returns(bool) { address _whod; for (uint256 n=0; n<_privLawAgreement[_aid].signees.length;n++) { _whod = _privLawAgreement[_aid].signees[n]; if (_privLawAgreement[_aid].state[_whod]!=2) return (false); } return (true); } //T:PEND:Allows withdrawal of deposit if agreement is settled or has been arbitrated function wdAgreement(uint256 _aid) public { require(_privLawAgreement[_aid].deposit==1 && _privLawAgreement[_aid].finePaid[_msgSender()]==1,"E: not paid"); // Withdrawal: you never paid deposit for this agreement id require(_privLawAgreement[_aid].fine>0,"E: nothing to wd"); // Withdrawal: nothing to withdrawal, agreement charged no fine" require(balanceOf(address(this))>=_privLawAgreement[_aid].fine,"E: contract balance too low"); // Withdrawal: contract balance is too low, arbitrator or crypto-panarchy administration should fund it require((_privLawAgreement[_aid].state[_msgSender()]==4 || _isSettledAgreement(_aid)),"E: wd not ready"); // Withdrawal: sorry, agreement is neither settled or arbitrated to your favor /** Precisamos definir o valor. Possibile logica aziendale: * - se for settlement amigavel, devolve o que pagou, paga fee, mark state 21 * - se for disputa arbitrada mark state 41 * - saca o dobro se for um acordo com apenas duas partes, desconta taxa de arbitragem * - descobre os perdedores P, descobre o total de perdedores tP divide pelo total de signatararios s, desconta arbitragem e paga a divisao * - saque = (D*s) - f / (s-tP) * onde * tp = total de perdedores da disputa (ie 2) * s = total de signees (ie 10) * D = fine depositada per s (ie 60) * f = tazza de arbittrage (ie 2) * - ∴ saque = ( (60*10)-3/(10-2) ) ∴ 59962500000 wei * - arbitragem define outro valor? melhor nao. nel codice, ci fidiamo. * - pagamento da fee de arbitragem apenas sobre saques individuais, mark state 91 * - fee de arbittrage: max fee absolute hardcoded no contrato (imutavel), * custom fee absolute, or percentage fee hardcoded no contratto * therefore we have custom (free market), default in percentage * and max arbitration fee, which the reason to exist was discussed * between Tom W Bell & 0xFF4, and is an optional upper limit by the crypto-panarchy. **/ uint256 tP; uint256 s=_privLawAgreement[_aid].signees.length; uint256 D=_privLawAgreement[_aid].fine; // uint256 fmax=3 * 10**_decimals; // max arbitration fee (in Tokens) (CONFIG:hardcoded) uint256 fpc=2; // default arbitration fee in percentage (CONFIG:hardcoded) uint256 f=(D.mul(s)).mul(fpc).div( (10**2)); // default arbitration fee value in tokens uint256 wdValue; if (_isSettledAgreement(_aid)) { // its all good, agreement is friendly settled require(_msgSender()!=_privLawAgreement[_aid].arbitrator,"E:fee not due"); // Withdrawal: friendly settled aid, no arbitration fee is due" // if (_msgSender()!=_privLawAgreement[_aid].arbitrator) { return false; } // cheaper wdValue=_privLawAgreement[_aid].fine; // get back what you paid _privLawAgreement[_aid].state[msg.sender]=21; // mark 21 } if (_privLawAgreement[_aid].arbitratorFee>0) { f=_privLawAgreement[_aid].arbitratorFee; } // arbitrator has set a custom fee if (f > fmax) { f=fmax; } // arbitration fee never above fmax for this panarchy. for (uint256 n=0; n<s; n++) { tP.add(1); } // tP++ if (msg.sender==_privLawAgreement[_aid].arbitrator) { // arbitrator withdrawal require(_privLawAgreement[_aid].state[_msgSender()]!=91,"E: already paid"); // Withdrawal: arbitrator fee already claimed wdValue=f; _privLawAgreement[_aid].state[msg.sender]=91; // mark 91 } else { // signee withdrawal require(_privLawAgreement[_aid].state[_msgSender()]!=41,"E: already paid"); // "Withdrawal: signee disputed fine already claimed" wdValue=( (D*s) - f / (s-tP) ); // Der formulae für diesen Panarchy debattiert _privLawAgreement[_aid].state[msg.sender]=41; // mark 41 } _approve(address(this), msg.sender, wdValue); _transfer(address(this), msg.sender, wdValue); } // 1=active/signed, 2=want_friendly_terminate, 3=want_dispute, 4=won_dispute, 5=lost_dispute // 21=friendly_withdrawaled, 41=disputed_wdled, 91=arbitrator_wdled 99=disputed_outside(ostracized) // T:PEND:(f16):Allows signee to enter dispute, enter friendly agreement and allows court to arbitrate disputes function setArbitration(uint256 _aid, uint256 _state, address _signee) public returns(bool) { require((_privLawAgreement[_aid].state[msg.sender]!=1||_privLawAgreement[_aid].arbitrator!=_msgSender()),"A2: not signee/court"); // never signed and is not arbitrator, do nothing /*if (_privLawAgreement[_aid].state[msg.sender]!=1||_privLawAgreement[_aid].arbitrator!=_msgSender()) { return false; // never signed and is not arbitrator, do nothing } else { */ if (_privLawAgreement[_aid].arbitrator==_msgSender() && _state==99) { // worst scenario, arbitrator informs disputed outside _privLawAgreement[_aid].state[_signee]=99; // set state to 99 _selfDetermined[_signee].spContractsViolated++; // violated contract _selfDetermined[_signee].spOptOutArbitrations=1; // disputed outside this panarchy rules: ostracized _selfDetermined[_signee].ostracizedBy.push(_msgSender()); // ostracized by this court setTrustPoints(_signee, 0); // worsen average } if (_privLawAgreement[_aid].arbitrator!=_msgSender() && (_state==2||_state==3||_state==1)) { // signer may set those states _privLawAgreement[_aid].state[msg.sender]=_state; } else if (_privLawAgreement[_aid].arbitrator==_msgSender() && (_privLawAgreement[_aid].state[_signee]==3) && (_state==4||_state==5)) { // arbitrator may set those states to signee if he wants dispute arbitration _privLawAgreement[_aid].state[msg.sender]=_state; if (_state==4) { setTrustPoints(_signee, 2); // receives 1 point from contract } else { _selfDetermined[_signee].spContractsViolated++; // violated contract setTrustPoints(_signee, 0); // worsen average } } //} return true; } } //EST FINITO /* * Due to contract size restrictions I am continuing the implementation in a second contract called VolNI which continues * using all the public interfaces from the original Crypto-Panarchy contract. It's a weird design decision which I was * mostly forced due to Solidity's actual limitations. Luckily all relevant calls were made public to export to Web3js front. * I am not fully implementing Hayek's idea because I disagree (and Mises does too, you bunch of socialists), therefore * volNiAddFunds() is still voluntary, one must donate! Belevolence! And members of the trust chain who need money may claim * a share every 15 days. */ contract VolNI is Ownable { using SafeMath for uint256; using Address for address; string public name = "Voluntary Negative Income"; address public panarchyAdmin; address public panaddr; mapping (address => uint256) donatesum; struct volNiSubjProperties { uint256 lastClaimedDate; uint256 donateSum; } mapping (address => volNiSubjProperties) private _volniSubject; uint256[3] public benevolSubjStats; // [ epoch, numSubj, totalValue ] event Deposit(address indexed who, uint amount); constructor (address _panarchy_addr) { panaddr = _panarchy_addr; //panarchy = new XFFAv5(); } /*receive() external payable { deposit(); } function deposit() public payable { p.balanceOf[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value); _volniSubject[msg.sender].donateSum.add(_amount); }*/ XFFAv5 p = XFFAv5(payable(panaddr)); function mygetAgreementSignees(uint256 _aid) public view returns(address[] memory) { return(p.getAgreementSignees(_aid)); } function myPrintParentAddr() public view returns(address) { return (panaddr); } function Finger(address _who) public view returns(string memory _sPgpPubK,string memory _sSshPubK,string memory _sX509PubK,string memory _sGecos,uint256 _sRole, string memory _sNickname) { return (p.Finger (_who)); } function volNiAddFunds(uint256 _amount) public { require (p.balanceOf(msg.sender)>=_amount,"ERC20: Insufficient balance to donate funds to Voluntary NI"); p.approve(msg.sender, _amount); // _approve(_msgSender(), spender, amount); p.transfer(address(this), _amount); _volniSubject[msg.sender].donateSum.add(_amount); } function volNiBalance() public view returns(uint256) { return (p.balanceOf(address(this))); } function volNiClaim() public { require(_volniSubject[msg.sender].lastClaimedDate<=(block.timestamp+1296580),"A2: already claimed within last 15 days"); // 1296580 = 15d 8h uint256 wdValue=100; //uint256 wdValue=(p.balanceOf[address(this)].div(benevolSubjStats[1])); // predict monthly NI based on num of beneficiaries from last period require(p.balanceOf(address(this))>=wdValue/2,"A2: insuficient funds, invite convenant members to donate"); p.approve(address(this), wdValue.div(2)); // divided by two for splitting claims every 15days p.transfer(msg.sender, wdValue.div(2)); if (benevolSubjStats[0] <= (block.timestamp-2593160)) benevolSubjStats = [ 0, 0, 0 ]; // reset statistics after 1 month benevolSubjStats = [ block.timestamp, benevolSubjStats[1].add(1), benevolSubjStats[2].add(wdValue.div(2))]; // monthly statistics _volniSubject[msg.sender].lastClaimedDate=block.timestamp; } } */ * TODO: so far wdValue is static, I should make it make it a DAO decision. Also test for min balance of claimer and * track it because low time preference individuals should be detected and are not welcome to get money from this pool. */
T:PEND(MERGE):(f9):Allows one to get agreement data and someone's termos to agreement aidrequire(_privLawAgreement[_aid].signedOn[_who]!=0,"AuthZ: this x-persona did not sign this agreement ID"); specifics for signee (_who) agreement generics (everyone) stack too deep (after merge)
function getAgreementData(uint256 _aid, address _who) public view returns (string memory, string memory, string memory) { bool _validSign = xffa.verifySimpleSignSaltedHash(_privLawAgreement[_aid].signature[_who],_who,"I hereby consent aid",_privLawAgreement[_aid].signatureNonce[_who]); string memory _vLabel = "false"; if (_validSign==true) _vLabel = "true"; return( string(abi.encodePacked( " _signedHash ",_privLawAgreement[_aid].signedHash[_who], " _signComment ",_privLawAgreement[_aid].signComment[_who], " _signatureValid ",_vLabel," _signedOn ",xffa.uint2str(_privLawAgreement[_aid].signedOn[_who]), " _finePaid ",xffa.uint2str(_privLawAgreement[_aid].finePaid[_who]), " _state ",xffa.uint2str(_privLawAgreement[_aid].state[_who]) )), string(abi.encodePacked(" _creator ",xffa.anyToStr(_privLawAgreement[_aid].creator), " _hash ",_privLawAgreement[_aid].hash," _arbitrator ",xffa.anyToStr(_privLawAgreement[_aid].arbitrator), " _arbitratorFee ", xffa.anyToStr(_privLawAgreement[_aid].arbitratorFee), " _fine ",xffa.uint2str(_privLawAgreement[_aid].fine)," _gecos ",_privLawAgreement[_aid].gecos, " _url ",_privLawAgreement[_aid].url )), string(abi.encodePacked(" _deposit ",xffa.uint2str(_privLawAgreement[_aid].deposit) )) ); }
12,876,851
./full_match/1/0x069c8eA3d0Bd677009b8620182457859caD11Ed5/sources/contracts/LilDeadFellaz.sol
Prizes mints by owner Prize mints must mint first, and cannot be minted after the maximum has been reached
function mintPrizes(uint amount) public onlyOwner { uint currentTotalSupply = totalSupply(); require(currentTotalSupply < MAX_PRIZE_MINTS, "LilDeadFellaz: Max prize mint limit reached"); if (currentTotalSupply + amount > MAX_PRIZE_MINTS){ amount = MAX_PRIZE_MINTS - currentTotalSupply; } _mintAmountTo(msg.sender, amount, currentTotalSupply); }
2,904,476
// Sources flattened with hardhat v2.0.5 https://hardhat.org // File deps/@openzeppelin/contracts-upgradeable/proxy/Initializable.sol // SPDX-License-Identifier: MIT pragma solidity >=0.4.24 <0.7.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function _isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; // solhint-disable-next-line no-inline-assembly assembly { cs := extcodesize(self) } return cs == 0; } } // File deps/@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol pragma solidity ^0.6.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // File deps/@openzeppelin/contracts-upgradeable/GSN/ContextUpgradeable.sol pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // File deps/@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol pragma solidity ^0.6.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // File deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathUpgradeable { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File interfaces/digg/IDigg.sol pragma solidity >=0.5.0 <0.8.0; interface IDigg { // Used for authentication function monetaryPolicy() external view returns (address); function rebaseStartTime() external view returns (uint256); /** * @param monetaryPolicy_ The address of the monetary policy contract to use for authentication. */ function setMonetaryPolicy(address monetaryPolicy_) external; /** * @dev Notifies Fragments contract about a new rebase cycle. * @param supplyDelta The number of new fragment tokens to add into circulation via expansion. * @return The total number of fragments after the supply adjustment. */ function rebase(uint256 epoch, int256 supplyDelta) external returns (uint256); /** * @return The total number of fragments. */ function totalSupply() external view returns (uint256); /** * @return The total number of underlying shares. */ function totalShares() external view returns (uint256); /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) external view returns (uint256); /** * @param who The address to query. * @return The underlying shares of the specified address. */ function sharesOf(address who) external view returns (uint256); function _sharesPerFragment() external view returns (uint256); function _initialSharesPerFragment() external view returns (uint256); /** * @param fragments Fragment value to convert. * @return The underlying share value of the specified fragment amount. */ function fragmentsToShares(uint256 fragments) external view returns (uint256); /** * @param shares Share value to convert. * @return The current fragment value of the specified underlying share amount. */ function sharesToFragments(uint256 shares) external view returns (uint256); function scaledSharesToShares(uint256 fragments) external view returns (uint256); function sharesToScaledShares(uint256 shares) external view returns (uint256); /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) external returns (bool); /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) external view returns (uint256); /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom( address from, address to, uint256 value ) external returns (bool); /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) external returns (bool); /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) external returns (bool); /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); } // File contracts/badger-timelock/vesting/SingleTokenVestingNonRevocableDigg.sol pragma solidity ^0.6.0; /** * @title SingleTokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. Only tracks vesting for a single token, rather than all ERC20s. */ contract SingleTokenVestingNonRevocableDigg is OwnableUpgradeable { // The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is // therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore, // it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a // cliff period of a year and a duration of four years, are safe to use. // solhint-disable not-rely-on-time using SafeMathUpgradeable for uint256; event TokensReleased(address token, uint256 amount); IDigg internal _digg; // beneficiary of tokens after they are released address internal _beneficiary; // Durations and timestamps are expressed in UNIX time, the same units as block.timestamp. uint256 internal _cliff; uint256 internal _start; uint256 internal _duration; uint256 internal _released; /** * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * beneficiary, gradually in a linear fashion until start + duration. By then all * of the balance will have vested. * @param token address of the token to vest * @param beneficiary address of the beneficiary to whom vested tokens are transferred * @param cliffDuration duration in seconds of the cliff in which tokens will begin to vest * @param start the time (as Unix time) at which point vesting starts * @param duration duration in seconds of the period in which the tokens will vest */ function __SingleTokenVestingNonRevocable_init( IDigg token, address beneficiary, uint256 start, uint256 cliffDuration, uint256 duration ) public initializer { require(address(token) != address(0), "TokenVesting: token is the zero address"); require(beneficiary != address(0), "TokenVesting: beneficiary is the zero address"); // solhint-disable-next-line max-line-length require(cliffDuration <= duration, "TokenVesting: cliff is longer than duration"); require(duration > 0, "TokenVesting: duration is 0"); // solhint-disable-next-line max-line-length require(start.add(duration) > block.timestamp, "TokenVesting: final time is before current time"); _digg = token; _beneficiary = beneficiary; _duration = duration; _cliff = start.add(cliffDuration); _start = start; } /** * @return the token being held. */ function token() public view returns (IDigg) { return _digg; } /** * @return the beneficiary of the tokens. */ function beneficiary() public view returns (address) { return _beneficiary; } /** * @return the cliff time of the token vesting. */ function cliff() public view returns (uint256) { return _cliff; } /** * @return the start time of the token vesting. */ function start() public view returns (uint256) { return _start; } /** * @return the duration of the token vesting. */ function duration() public view returns (uint256) { return _duration; } /** * @return the amount of the token released. */ function released() public view returns (uint256) { return _released; } /** * @notice Transfers vested tokens to beneficiary. */ function release() public virtual { uint256 unreleased = _releasableAmount(); require(unreleased > 0, "TokenVesting: no tokens are due"); _released = _released.add(unreleased); require(_digg.transfer(_beneficiary, _digg.sharesToFragments(unreleased)), "token transfer failed"); emit TokensReleased(address(_digg), unreleased); } function initializeReleasedAsShares() external { require(_released == 26796612042, "already initialized to shares"); _released = 903638732631997846815093457587811581689457319978569725740871638998310548320; } function releasableAmount() public view returns (uint256) { return _releasableAmount(); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. */ function _releasableAmount() internal view returns (uint256) { return _vestedAmount().sub(_released); } /** * @dev Calculates the amount that has already vested. */ function _vestedAmount() internal view returns (uint256) { uint256 currentBalance = _digg.sharesOf(address(this)); uint256 totalBalance = currentBalance.add(_released); if (block.timestamp < _cliff) { return 0; } else if (block.timestamp >= _start.add(_duration)) { return totalBalance; } else { uint256 secondsSinceStart = block.timestamp.sub(_start); return totalBalance.div(_duration).mul(secondsSinceStart); } } } // File contracts/badger-timelock/ExecutorOnlyCall.sol pragma solidity >=0.5.0 <0.7.0; /* Gnosis Safe Executor - library wrapping low level calls https://github.com/gnosis/safe-contracts/blob/development/contracts/base/Executor.sol Ability to execute delegateCall has been removed for security */ /// @title Executor - A contract that can execute transactions /// @author Richard Meissner - <richard@gnosis.pm> contract ExecutorOnlyCall { function execute( address to, uint256 value, bytes memory data, uint256 txGas ) internal returns (bool success) { success = executeCall(to, value, data, txGas); } function executeCall( address to, uint256 value, bytes memory data, uint256 txGas ) internal returns (bool success) { // solium-disable-next-line security/no-inline-assembly assembly { success := call(txGas, to, value, add(data, 0x20), mload(data), 0, 0) } } } // File contracts/badger-timelock/SmartVestingDigg.sol pragma solidity ^0.6.8; /* A token vesting contract that is capable of interacting with other smart contracts. This allows the beneficiary to participate in on-chain goverance processes, despite having locked tokens. The beneficiary can withdraw the appropriate vested amount at any time. Features safety functions to allow beneficiary to claim ETH & ERC20-compliant tokens sent to the timelock contract, accidentially or otherwise. An optional 'governor' address has the ability to allow the vesting to send it's tokens to approved destinations. This is intended to allow the token holder to stake their tokens in approved mechanisms. */ contract SmartVestingDigg is SingleTokenVestingNonRevocableDigg, ExecutorOnlyCall, ReentrancyGuardUpgradeable { address internal _governor; mapping(address => bool) internal _transferAllowed; // address beneficiary, uint256 start, uint256 cliffDuration, uint256 duration, bool revocable function initialize( IDigg token, address beneficiary, address governor, uint256 start, uint256 cliffDuration, uint256 duration ) public initializer { __SingleTokenVestingNonRevocable_init(token, beneficiary, start, cliffDuration, duration); __ReentrancyGuard_init_unchained(); _governor = governor; } event Call(address to, uint256 value, bytes data, bool transfersAllowed); event ApproveTransfer(address to); event RevokeTransfer(address to); event ClaimToken(IDigg token, uint256 amount); event ClaimEther(uint256 amount); modifier onlyBeneficiary() { require(msg.sender == beneficiary(), "smart-timelock/only-beneficiary"); _; } modifier onlyGovernor() { require(msg.sender == _governor, "smart-timelock/only-governor"); _; } /** * @notice Allows the timelock to call arbitrary contracts, as long as it does not reduce it's locked token balance * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @param to Contract address to call * @param value ETH value to send, if any * @param data Encoded data to send */ function call( address to, uint256 value, bytes calldata data ) external payable onlyBeneficiary() nonReentrant() returns (bool success) { uint256 preAmount = token().balanceOf(address(this)); success = execute(to, value, data, gasleft()); if (!_transferAllowed[to]) { uint256 postAmount = token().balanceOf(address(this)); require(postAmount >= preAmount, "smart-vesting/locked-balance-check"); } emit Call(to, value, data, _transferAllowed[to]); } function approveTransfer(address to) external onlyGovernor() { _transferAllowed[to] = true; emit ApproveTransfer(to); } function revokeTransfer(address to) external onlyGovernor() { _transferAllowed[to] = false; emit RevokeTransfer(to); } /** * @notice Claim ERC20-compliant tokens other than locked token. * @param tokenToClaim Token to claim balance of. */ function claimToken(IDigg tokenToClaim) external onlyBeneficiary() nonReentrant() { require(address(tokenToClaim) != address(token()), "smart-timelock/no-locked-token-claim"); uint256 preAmount = token().balanceOf(address(this)); uint256 claimableTokenAmount = tokenToClaim.balanceOf(address(this)); require(claimableTokenAmount > 0, "smart-timelock/no-token-balance-to-claim"); tokenToClaim.transfer(beneficiary(), claimableTokenAmount); uint256 postAmount = token().balanceOf(address(this)); require(postAmount >= preAmount, "smart-timelock/locked-balance-check"); emit ClaimToken(tokenToClaim, claimableTokenAmount); } /** * @notice Claim Ether in contract. */ function claimEther() external onlyBeneficiary() nonReentrant() { uint256 preAmount = token().balanceOf(address(this)); uint256 etherToTransfer = address(this).balance; require(etherToTransfer > 0, "smart-timelock/no-ether-balance-to-claim"); payable(beneficiary()).transfer(etherToTransfer); uint256 postAmount = token().balanceOf(address(this)); require(postAmount >= preAmount, "smart-timelock/locked-balance-check"); emit ClaimEther(etherToTransfer); } /** * @notice Governor address */ function governor() external view returns (address) { return _governor; } /** * @notice Allow timelock to receive Ether */ receive() external payable {} }
return the token being held./
function token() public view returns (IDigg) { return _digg; }
1,677,852
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "../library/StringLibrary.sol"; import "../interfaces/IPortfolio.sol"; /** * @title TokenVesting * @dev A token holder contract that can release its token balance gradually like a * typical vesting scheme, with a cliff and vesting period. Optionally revocable by the * owner. */ contract TokenVesting is Ownable, ReentrancyGuard { using SafeERC20 for IERC20Metadata; using StringLibrary for string; // The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is // therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore, // it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a // cliff period of a year and a duration of four years, are safe to use. // version bytes32 constant public VERSION = bytes32("1.0.1"); event TokensReleased(address token, uint256 amount); event TokenVestingRevoked(address token); // beneficiary of tokens after they are released address private _beneficiary; // Durations and timestamps are expressed in UNIX time, the same units as block.timestamp. uint256 private _cliff; uint256 private _start; uint256 private _duration; uint256 private _startPortfolioDeposits; bool private _revocable; IPortfolio private _portfolio; uint256 private _totalSupplyBeforeRevoke; uint256 private _firstReleasePercentage; mapping(address => uint256) private _releasedPercentage; mapping(address => uint256) private _released; mapping(address => bool) private _revoked; /* * @dev Creates a vesting contract that vests its balance of any ERC20 token to the * beneficiary, gradually in a linear fashion until start + duration. By then all * of the balance will have vested. * @param __beneficiary address of the beneficiary to whom vested tokens are transferred * @param __cliffDuration duration in seconds of the cliff in which tokens will begin to vest * @param __start the time (as Unix time) at which point vesting starts * @param __duration duration in seconds of the period in which the tokens will vest * @oaran __startPortfolioDeposits * @param __revocable whether the vesting is revocable or not * @param __firstReleasePercentage * @param __portfolio */ constructor( address __beneficiary, uint256 __start, uint256 __cliffDuration, uint256 __duration, uint256 __startPortfolioDeposits, bool __revocable, uint256 __firstReleasePercentage, IPortfolio __portfolio ) { require(__beneficiary != address(0), "TokenVesting: beneficiary is the zero address"); require(__cliffDuration <= __duration, "TokenVesting: cliff is longer than duration"); require(__duration > 0, "TokenVesting: duration is 0"); require(__start + __duration > block.timestamp, "TokenVesting: final time is before current time"); require(__startPortfolioDeposits < __start, "TokenVesting: portfolio deposits begins after start"); require(__firstReleasePercentage > 0, "TokenVesting: percentage is 0"); require(address(__portfolio) != address(0), "TokenVesting: portfolio is the zero address"); _beneficiary = __beneficiary; _revocable = __revocable; _duration = __duration; _cliff = __start + __cliffDuration; _start = __start; _startPortfolioDeposits = __startPortfolioDeposits; _firstReleasePercentage = __firstReleasePercentage; _portfolio = __portfolio; } /** * @return the beneficiary of the tokens. */ function beneficiary() external view returns (address) { return _beneficiary; } /** * @return the cliff time of the token vesting. */ function cliff() external view returns (uint256) { return _cliff; } /** * @return the start time of the token vesting. */ function start() external view returns (uint256) { return _start; } /** * @return the duration of the token vesting. */ function duration() external view returns (uint256) { return _duration; } /** * @return the start time for depositing to portfolio. */ function startPortfolioDeposits() external view returns (uint256) { return _startPortfolioDeposits; } /** * @return true if the vesting is revocable. */ function revocable() external view returns (bool) { return _revocable; } /** * @return the amount of the token released. */ function released(address token) external view returns (uint256) { return _released[token]; } /** * @return true if the token is revoked. */ function revoked(address token) external view returns (bool) { return _revoked[token]; } /* * get value of the percentage */ function getPercentage() external view returns (uint256) { return _firstReleasePercentage; } /* * set value of the percentage */ function setPercentage(uint256 percentage) external onlyOwner { _firstReleasePercentage = percentage; } /* * set starting time for depositing to portfolio */ function setStartPortfolioDeposits(uint256 time) external onlyOwner { _startPortfolioDeposits = time; } /* * @return true if the vesting is funded to the portfolio. * beneficiary check is not for access control, it is just for convenience in frontend */ function canFundWallet(IERC20Metadata token, address __beneficiary) public view returns (bool) { return __beneficiary == _beneficiary && block.timestamp > _start && (_vestedByPercentage(token) > _releasedPercentage[address(token)] || block.timestamp > _cliff); } /* * @return true if the vesting is funded to the portfolio. * beneficiary check is not for access control, it is just for convenience in frontend */ function canFundPortfolio(address __beneficiary) public view returns (bool) { return __beneficiary == _beneficiary && block.timestamp > _startPortfolioDeposits && block.timestamp < _start; } /** * @return the portfolio address for funding */ function getPortfolio() external view returns (address) { return address(_portfolio); } /* * set address for the portfolio. */ function setPortfolio(IPortfolio portfolio) external onlyOwner { require(address(portfolio) != address(0), "TokenVesting: portfolio is the zero address"); _portfolio = portfolio; } /** * @notice Transfers vested tokens to beneficiary. * @param token ERC20 token which is being vested */ function release(IERC20Metadata token) external nonReentrant { require(token.balanceOf(address(this)) > 0, "TokenVesting: no balance on the contract"); require(block.timestamp > _start, "TokenVesting: too early"); uint256 unreleased = _releasableAmount(token); require(unreleased > 0, "TokenVesting: no tokens are due"); if (_releasedPercentage[address(token)] == 0) { _releasedPercentage[address(token)] = _vestedByPercentage(token); } _released[address(token)] = _released[address(token)] + unreleased; emit TokensReleased(address(token), unreleased); token.safeTransfer(_beneficiary, unreleased); } /** * @notice Transfers vested tokens to Portfolio. * @param token ERC20 token which is being vested */ function releaseToPortfolio(IERC20Metadata token) external nonReentrant { require(canFundPortfolio(_beneficiary), "TokenVesting: only possible during auction"); uint256 unreleased = _releasableAmount(token); require(unreleased > 0, "TokenVesting: no tokens are due"); if (_releasedPercentage[address(token)] == 0) { string memory symbolStr = IERC20Metadata(token).symbol(); bytes32 symbol = stringToBytes32(symbolStr); _releasedPercentage[address(token)] = _vestedByPercentage(token); _released[address(token)] = _released[address(token)] + unreleased; emit TokensReleased(address(token), unreleased); token.safeTransfer(_beneficiary, unreleased); _portfolio.depositTokenFromContract( _beneficiary, symbol, unreleased ); } } /** * @notice Allows the owner to revoke the vesting. Tokens already vested * remain in the contract, the rest are returned to the owner. * @param token ERC20 token which is being vested */ function revoke(IERC20Metadata token) external onlyOwner { require(_revocable, "TokenVesting: cannot revoke"); require(!_revoked[address(token)], "TokenVesting: token already revoked"); uint256 balance = token.balanceOf(address(this)); _totalSupplyBeforeRevoke = balance + _released[address(token)]; uint256 unreleased = _releasableAmount(token); uint256 refund = balance - unreleased; _revoked[address(token)] = true; emit TokenVestingRevoked(address(token)); token.safeTransfer(owner(), refund); } /** * @dev Calculates the amount that has already vested but hasn't been released yet. * @param token ERC20 token which is being vested */ function _releasableAmount(IERC20Metadata token) private view returns (uint256) { return (_vestedAmount(token) + _vestedByPercentage(token)) - _released[address(token)]; } /** * @dev Returns the amount for the amount remaining after the initial percentage vested at TGE. * @param token ERC20 token which is being vested */ function vestedAmount(IERC20Metadata token) external view returns (uint256) { return _vestedAmount(token); } /** * @dev Returns the amount that has been released based on the initial percentage vested at TGE. * @param token ERC20 token which is being vested */ function releasedPercentageAmount(IERC20Metadata token) external view returns (uint256) { return _releasedPercentage[address(token)]; } /** * @dev Returns the amount that is releaseable based on the initial percentage vested at TGE. * @param token ERC20 token which is being vested */ function vestedPercentageAmount(IERC20Metadata token) external view returns (uint256) { return _vestedByPercentage(token); } /** * @dev Calculates the amount that has already vested. * Subtracts the amount calculated by percentage. * Starts calculating of vested amount after the time of cliff. * @param token ERC20 token which is being vested */ function _vestedAmount(IERC20Metadata token) private view returns (uint256) { uint256 currentBalance = token.balanceOf(address(this)); uint256 totalBalance = (currentBalance + _released[address(token)]) - _vestedByPercentage(token); if (block.timestamp < _cliff) { return 0; } else if ( block.timestamp >= _start + _duration || _revoked[address(token)] ) { return totalBalance; } else { uint256 fromCliff = block.timestamp - _cliff; uint256 cliffDuration = _cliff - _start; uint256 durationAfterCliff = _duration - cliffDuration; uint256 vesting = (totalBalance * (fromCliff)) / (durationAfterCliff); return vesting; } } /** * @dev Calculates the amount vested at TGE. * @param token ERC20 token which is being vested */ function _vestedByPercentage(IERC20Metadata token) private view returns (uint256) { if (block.timestamp < _startPortfolioDeposits) { return 0; } else { uint256 currentBalance = token.balanceOf(address(this)); uint256 totalBalance = _revoked[address(token)] ? _totalSupplyBeforeRevoke : currentBalance + _released[address(token)]; uint256 percentage = (totalBalance * _firstReleasePercentage) / 100; return percentage; } } // utility function to convert string to bytes32 function stringToBytes32(string memory _string) public pure returns (bytes32 result) { return _string.stringToBytes32(); } }
return the start time for depositing to portfolio./
function startPortfolioDeposits() external view returns (uint256) { return _startPortfolioDeposits; }
1,064,660
./full_match/80001/0x0C3D02B43f5e892FdA061C41d2F90d8e5673BB0D/sources/contracts/GotMinted.sol
Initializes the contract in unpaused state./
function Pausable_init() internal onlyOwner onlyInitializing { __Pausable_init_unchained(); }
873,358
./full_match/80001/0x65778600A4F7e79B469f679280B1193f5e44A72f/sources/contracts/RetirementCertificates.sol
Mint new Retirement Certificate NFT that shows how many TCO2s have been retired. retiringEntity The entity that has retired TCO2 and is eligible to mint an NFT. params Retirement params retirementEventIds An array of event ids to associate with the NFT. return The token id of the newly minted NFT. The function can either be called by a valid TCO2 contract or by someone who owns retirement events.
function mintCertificateWithExtraData( address retiringEntity, CreateRetirementRequestParams calldata params, uint256[] calldata retirementEventIds ) external virtual nonReentrant returns (uint256) { return _mintCertificate(retiringEntity, params, retirementEventIds); }
9,520,812
./partial_match/1/0x5C0Fe44391ee35856A5De861dFd340197D252624/sources/src/SeaDrop.sol
get public mint price nftContract The nft contract address./
function getPublicMintPrice(address nftContract) external view override returns (uint256) { return _publicMintPrices[nftContract]; }
3,579,968
/** *Submitted for verification at Etherscan.io on 2021-10-26 */ // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: AggregatorInterface interface AggregatorInterface { function latestAnswer() external view returns (int256); function latestTimestamp() external view returns (uint256); function latestRound() external view returns (uint256); function getAnswer(uint256 roundId) external view returns (int256); function getTimestamp(uint256 roundId) external view returns (uint256); event AnswerUpdated( int256 indexed current, uint256 indexed roundId, uint256 updatedAt ); event NewRound( uint256 indexed roundId, address indexed startedBy, uint256 startedAt ); } // Part: DssAutoLine interface DssAutoLine { function exec(bytes32 _ilk) external returns (uint256); } // Part: GemLike interface GemLike { function approve(address, uint256) external; function transfer(address, uint256) external; function transferFrom( address, address, uint256 ) external; function deposit() external payable; function withdraw(uint256) external; } // Part: IBaseFee interface IBaseFee { function basefee_global() external view returns (uint256); } // Part: IOSMedianizer interface IOSMedianizer { function foresight() external view returns (uint256 price, bool osm); function read() external view returns (uint256 price, bool osm); } // Part: ISwap interface ISwap { function swapExactTokensForTokens( uint256, uint256, address[] calldata, address, uint256 ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256, uint256, address[] calldata, address, uint256 ) external returns (uint256[] memory amounts); function getAmountsOut(uint256 amountIn, address[] memory path) external view returns (uint256[] memory amounts); } // Part: JugLike interface JugLike { function drip(bytes32) external returns (uint256); } // Part: ManagerLike interface ManagerLike { function cdpCan( address, uint256, address ) external view returns (uint256); function ilks(uint256) external view returns (bytes32); function owns(uint256) external view returns (address); function urns(uint256) external view returns (address); function vat() external view returns (address); function open(bytes32, address) external returns (uint256); function give(uint256, address) external; function cdpAllow( uint256, address, uint256 ) external; function urnAllow(address, uint256) external; function frob( uint256, int256, int256 ) external; function flux( uint256, address, uint256 ) external; function move( uint256, address, uint256 ) external; function exit( address, uint256, address, uint256 ) external; function quit(uint256, address) external; function enter(address, uint256) external; function shift(uint256, uint256) external; } // Part: OpenZeppelin/openzeppelin-contracts@3.1.0/Address /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // Part: OpenZeppelin/openzeppelin-contracts@3.1.0/IERC20 /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Part: OpenZeppelin/openzeppelin-contracts@3.1.0/Math /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // Part: OpenZeppelin/openzeppelin-contracts@3.1.0/SafeMath /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Part: SpotLike interface SpotLike { function live() external view returns (uint256); function par() external view returns (uint256); function vat() external view returns (address); function ilks(bytes32) external view returns (address, uint256); } // Part: VatLike interface VatLike { function can(address, address) external view returns (uint256); function ilks(bytes32) external view returns ( uint256, uint256, uint256, uint256, uint256 ); function dai(address) external view returns (uint256); function urns(bytes32, address) external view returns (uint256, uint256); function frob( bytes32, address, address, address, int256, int256 ) external; function hope(address) external; function move( address, address, uint256 ) external; } // Part: yearn/yearn-vaults@0.4.3/HealthCheck interface HealthCheck { function check( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding, uint256 totalDebt ) external view returns (bool); } // Part: DaiJoinLike interface DaiJoinLike { function vat() external returns (VatLike); function dai() external returns (GemLike); function join(address, uint256) external payable; function exit(address, uint256) external; } // Part: GemJoinLike interface GemJoinLike { function dec() external returns (uint256); function gem() external returns (GemLike); function join(address, uint256) external payable; function exit(address, uint256) external; } // Part: IVault interface IVault is IERC20 { function token() external view returns (address); function decimals() external view returns (uint256); function deposit() external; function pricePerShare() external view returns (uint256); function withdraw() external returns (uint256); function withdraw(uint256 amount) external returns (uint256); function withdraw( uint256 amount, address account, uint256 maxLoss ) external returns (uint256); function availableDepositLimit() external view returns (uint256); } // Part: OpenZeppelin/openzeppelin-contracts@3.1.0/SafeERC20 /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // Part: yearn/yearn-vaults@0.4.3/VaultAPI interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } // Part: MakerDaiDelegateLib library MakerDaiDelegateLib { using SafeMath for uint256; // Units used in Maker contracts uint256 internal constant WAD = 10**18; uint256 internal constant RAY = 10**27; // Do not attempt to mint DAI if there are less than MIN_MINTABLE available uint256 internal constant MIN_MINTABLE = 500000 * WAD; // Maker vaults manager ManagerLike internal constant manager = ManagerLike(0x5ef30b9986345249bc32d8928B7ee64DE9435E39); // Token Adapter Module for collateral DaiJoinLike internal constant daiJoin = DaiJoinLike(0x9759A6Ac90977b93B58547b4A71c78317f391A28); // Liaison between oracles and core Maker contracts SpotLike internal constant spotter = SpotLike(0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3); // Part of the Maker Rates Module in charge of accumulating stability fees JugLike internal constant jug = JugLike(0x19c0976f590D67707E62397C87829d896Dc0f1F1); // Debt Ceiling Instant Access Module DssAutoLine internal constant autoLine = DssAutoLine(0xC7Bdd1F2B16447dcf3dE045C4a039A60EC2f0ba3); // ----------------- PUBLIC FUNCTIONS ----------------- // Creates an UrnHandler (cdp) for a specific ilk and allows to manage it via the internal // registry of the manager. function openCdp(bytes32 ilk) public returns (uint256) { return manager.open(ilk, address(this)); } // Moves cdpId collateral balance and debt to newCdpId. function shiftCdp(uint256 cdpId, uint256 newCdpId) public { manager.shift(cdpId, newCdpId); } // Transfers the ownership of cdp to recipient address in the manager registry. function transferCdp(uint256 cdpId, address recipient) public { manager.give(cdpId, recipient); } // Allow/revoke manager access to a cdp function allowManagingCdp( uint256 cdpId, address user, bool isAccessGranted ) public { manager.cdpAllow(cdpId, user, isAccessGranted ? 1 : 0); } // Deposits collateral (gem) and mints DAI // Adapted from https://github.com/makerdao/dss-proxy-actions/blob/master/src/DssProxyActions.sol#L639 function lockGemAndDraw( address gemJoin, uint256 cdpId, uint256 collateralAmount, uint256 daiToMint, uint256 totalDebt ) public { address urn = manager.urns(cdpId); VatLike vat = VatLike(manager.vat()); bytes32 ilk = manager.ilks(cdpId); if (daiToMint > 0) { daiToMint = _forceMintWithinLimits(vat, ilk, daiToMint, totalDebt); } // Takes token amount from the strategy and joins into the vat if (collateralAmount > 0) { GemJoinLike(gemJoin).join(urn, collateralAmount); } // Locks token amount into the CDP and generates debt manager.frob( cdpId, int256(convertTo18(gemJoin, collateralAmount)), _getDrawDart(vat, urn, ilk, daiToMint) ); // Moves the DAI amount to the strategy. Need to convert dai from [wad] to [rad] manager.move(cdpId, address(this), daiToMint.mul(1e27)); // Allow access to DAI balance in the vat vat.hope(address(daiJoin)); // Exits DAI to the user's wallet as a token daiJoin.exit(address(this), daiToMint); } // Returns DAI to decrease debt and attempts to unlock any amount of collateral // Adapted from https://github.com/makerdao/dss-proxy-actions/blob/master/src/DssProxyActions.sol#L758 function wipeAndFreeGem( address gemJoin, uint256 cdpId, uint256 collateralAmount, uint256 daiToRepay ) public { address urn = manager.urns(cdpId); // Joins DAI amount into the vat if (daiToRepay > 0) { daiJoin.join(urn, daiToRepay); } uint256 wadC = convertTo18(gemJoin, collateralAmount); // Paybacks debt to the CDP and unlocks token amount from it manager.frob( cdpId, -int256(wadC), _getWipeDart( VatLike(manager.vat()), VatLike(manager.vat()).dai(urn), urn, manager.ilks(cdpId) ) ); // Moves the amount from the CDP urn to proxy's address manager.flux(cdpId, address(this), collateralAmount); // Exits token amount to the strategy as a token GemJoinLike(gemJoin).exit(address(this), collateralAmount); } function debtFloor(bytes32 ilk) public view returns (uint256) { // uint256 Art; // Total Normalised Debt [wad] // uint256 rate; // Accumulated Rates [ray] // uint256 spot; // Price with Safety Margin [ray] // uint256 line; // Debt Ceiling [rad] // uint256 dust; // Urn Debt Floor [rad] (, , , , uint256 dust) = VatLike(manager.vat()).ilks(ilk); return dust.div(RAY); } function debtForCdp(uint256 cdpId, bytes32 ilk) public view returns (uint256) { address urn = manager.urns(cdpId); VatLike vat = VatLike(manager.vat()); // Normalized outstanding stablecoin debt [wad] (, uint256 art) = vat.urns(ilk, urn); // Gets actual rate from the vat [ray] (, uint256 rate, , , ) = vat.ilks(ilk); // Return the present value of the debt with accrued fees return art.mul(rate).div(RAY); } function balanceOfCdp(uint256 cdpId, bytes32 ilk) public view returns (uint256) { address urn = manager.urns(cdpId); VatLike vat = VatLike(manager.vat()); (uint256 ink, ) = vat.urns(ilk, urn); return ink; } // Returns value of DAI in the reference asset (e.g. $1 per DAI) function getDaiPar() public view returns (uint256) { // Value is returned in ray (10**27) return spotter.par(); } // Liquidation ratio for the given ilk returned in [ray] // https://github.com/makerdao/dss/blob/master/src/spot.sol#L45 function getLiquidationRatio(bytes32 ilk) public view returns (uint256) { (, uint256 liquidationRatio) = spotter.ilks(ilk); return liquidationRatio; } function getSpotPrice(bytes32 ilk) public view returns (uint256) { VatLike vat = VatLike(manager.vat()); // spot: collateral price with safety margin returned in [ray] (, , uint256 spot, , ) = vat.ilks(ilk); uint256 liquidationRatio = getLiquidationRatio(ilk); // convert ray*ray to wad return spot.mul(liquidationRatio).div(RAY * 1e9); } function getPessimisticRatioOfCdpWithExternalPrice( uint256 cdpId, bytes32 ilk, uint256 externalPrice, uint256 collateralizationRatioPrecision ) public view returns (uint256) { // Use pessimistic price to determine the worst ratio possible uint256 price = Math.min(getSpotPrice(ilk), externalPrice); require(price > 0); // dev: invalid price uint256 totalCollateralValue = balanceOfCdp(cdpId, ilk).mul(price).div(WAD); uint256 totalDebt = debtForCdp(cdpId, ilk); // If for some reason we do not have debt (e.g: deposits under dust) // make sure the operation does not revert if (totalDebt == 0) { totalDebt = 1; } return totalCollateralValue.mul(collateralizationRatioPrecision).div( totalDebt ); } // Make sure we update some key content in Maker contracts // These can be updated by anyone without authenticating function keepBasicMakerHygiene(bytes32 ilk) public { // Update accumulated stability fees jug.drip(ilk); // Update the debt ceiling using DSS Auto Line autoLine.exec(ilk); } function daiJoinAddress() public view returns (address) { return address(daiJoin); } // Checks if there is at least MIN_MINTABLE dai available to be minted function isDaiAvailableToMint(bytes32 ilk) public view returns (bool) { VatLike vat = VatLike(manager.vat()); (uint256 Art, uint256 rate, , uint256 line, ) = vat.ilks(ilk); // Total debt in [rad] (wad * ray) uint256 vatDebt = Art.mul(rate); if (vatDebt >= line || line.sub(vatDebt).div(RAY) < MIN_MINTABLE) { return false; } return true; } // ----------------- INTERNAL FUNCTIONS ----------------- // This function repeats some code from daiAvailableToMint because it needs // to handle special cases such as not leaving debt under dust function _forceMintWithinLimits( VatLike vat, bytes32 ilk, uint256 desiredAmount, uint256 debtBalance ) internal view returns (uint256) { // uint256 Art; // Total Normalised Debt [wad] // uint256 rate; // Accumulated Rates [ray] // uint256 spot; // Price with Safety Margin [ray] // uint256 line; // Debt Ceiling [rad] // uint256 dust; // Urn Debt Floor [rad] (uint256 Art, uint256 rate, , uint256 line, uint256 dust) = vat.ilks(ilk); // Total debt in [rad] (wad * ray) uint256 vatDebt = Art.mul(rate); // Make sure we are not over debt ceiling (line) or under debt floor (dust) if ( vatDebt >= line || (desiredAmount.add(debtBalance) <= dust.div(RAY)) ) { return 0; } uint256 maxMintableDAI = line.sub(vatDebt).div(RAY); // Avoid edge cases with low amounts of available debt if (maxMintableDAI < MIN_MINTABLE) { return 0; } // Prevent rounding errors if (maxMintableDAI > WAD) { maxMintableDAI = maxMintableDAI - WAD; } return Math.min(maxMintableDAI, desiredAmount); } // Adapted from https://github.com/makerdao/dss-proxy-actions/blob/master/src/DssProxyActions.sol#L161 function _getDrawDart( VatLike vat, address urn, bytes32 ilk, uint256 wad ) internal returns (int256 dart) { // Updates stability fee rate uint256 rate = jug.drip(ilk); // Gets DAI balance of the urn in the vat uint256 dai = vat.dai(urn); // If there was already enough DAI in the vat balance, just exits it without adding more debt if (dai < wad.mul(RAY)) { // Calculates the needed dart so together with the existing dai in the vat is enough to exit wad amount of DAI tokens dart = int256(wad.mul(RAY).sub(dai).div(rate)); // This is neeeded due to lack of precision. It might need to sum an extra dart wei (for the given DAI wad amount) dart = uint256(dart).mul(rate) < wad.mul(RAY) ? dart + 1 : dart; } } // Adapted from https://github.com/makerdao/dss-proxy-actions/blob/master/src/DssProxyActions.sol#L183 function _getWipeDart( VatLike vat, uint256 dai, address urn, bytes32 ilk ) internal view returns (int256 dart) { // Gets actual rate from the vat (, uint256 rate, , , ) = vat.ilks(ilk); // Gets actual art value of the urn (, uint256 art) = vat.urns(ilk, urn); // Uses the whole dai balance in the vat to reduce the debt dart = int256(dai / rate); // Checks the calculated dart is not higher than urn.art (total debt), otherwise uses its value dart = uint256(dart) <= art ? -dart : -int256(art); } function convertTo18(address gemJoin, uint256 amt) internal returns (uint256 wad) { // For those collaterals that have less than 18 decimals precision we need to do the conversion before // passing to frob function // Adapters will automatically handle the difference of precision wad = amt.mul(10**(18 - GemJoinLike(gemJoin).dec())); } } // Part: yearn/yearn-vaults@0.4.3/BaseStrategy /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; // health checks bool public doHealthCheck; address public healthCheck; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.4.3"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external view virtual returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external view virtual returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyEmergencyAuthorized() { require( msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyVaultManagers() { require(msg.sender == vault.management() || msg.sender == governance(), "!authorized"); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. * @param _strategist The address to assign as `strategist`. * The strategist is able to change the reward address * @param _rewards The address to use for pulling rewards. * @param _keeper The adddress of the _keeper. _keeper * can harvest and tend a strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } function setHealthCheck(address _healthCheck) external onlyVaultManagers { healthCheck = _healthCheck; } function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers { doHealthCheck = _doHealthCheck; } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual returns (uint256); /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public view virtual returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * Liquidate everything and returns the amount that got freed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. */ function liquidateAllPositions() internal virtual returns (uint256 _amountFreed); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei). * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. // If your implementation uses the cost of the call in want, you can // use uint256 callCost = ethToWant(callCostInWei); return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/main/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei). * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) { uint256 callCost = ethToWant(callCostInWei); StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 amountFreed = liquidateAllPositions(); if (amountFreed < debtOutstanding) { loss = debtOutstanding.sub(amountFreed); } else if (amountFreed > debtOutstanding) { profit = amountFreed.sub(debtOutstanding); } debtPayment = debtOutstanding.sub(loss); } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. uint256 totalDebt = vault.strategies(address(this)).totalDebt; debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); // call healthCheck contract if (doHealthCheck && healthCheck != address(0)) { require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck"); } else { doHealthCheck = true; } emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * The migration process should be carefully performed to make sure all * the assets are migrated to the new address, which should have never * interacted with the vault before. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault)); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyEmergencyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * ``` * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } * ``` */ function protectedTokens() internal view virtual returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } // Part: Strategy contract Strategy is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; // Units used in Maker contracts uint256 internal constant WAD = 10**18; uint256 internal constant RAY = 10**27; // DAI token IERC20 internal constant investmentToken = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); // 100% uint256 internal constant MAX_BPS = WAD; // Maximum loss on withdrawal from yVault uint256 internal constant MAX_LOSS_BPS = 10000; // Wrapped Ether - Used for swaps routing address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // SushiSwap router ISwap internal constant sushiswapRouter = ISwap(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // Uniswap router ISwap internal constant uniswapRouter = ISwap(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // Provider to read current block's base fee IBaseFee internal constant baseFeeProvider = IBaseFee(0xf8d0Ec04e94296773cE20eFbeeA82e76220cD549); // Token Adapter Module for collateral address public gemJoinAdapter; // Maker Oracle Security Module IOSMedianizer public wantToUSDOSMProxy; // Use Chainlink oracle to obtain latest want/ETH price AggregatorInterface public chainlinkWantToETHPriceFeed; // DAI yVault IVault public yVault; // Router used for swaps ISwap public router; // Collateral type bytes32 public ilk; // Our vault identifier uint256 public cdpId; // Our desired collaterization ratio uint256 public collateralizationRatio; // Allow the collateralization ratio to drift a bit in order to avoid cycles uint256 public rebalanceTolerance; // Max acceptable base fee to take more debt or harvest uint256 public maxAcceptableBaseFee; // Maximum acceptable loss on withdrawal. Default to 0.01%. uint256 public maxLoss; // If set to true the strategy will never try to repay debt by selling want bool public leaveDebtBehind; // Name of the strategy string internal strategyName; // ----------------- INIT FUNCTIONS TO SUPPORT CLONING ----------------- constructor( address _vault, address _yVault, string memory _strategyName, bytes32 _ilk, address _gemJoin, address _wantToUSDOSMProxy, address _chainlinkWantToETHPriceFeed ) public BaseStrategy(_vault) { _initializeThis( _yVault, _strategyName, _ilk, _gemJoin, _wantToUSDOSMProxy, _chainlinkWantToETHPriceFeed ); } function initialize( address _vault, address _yVault, string memory _strategyName, bytes32 _ilk, address _gemJoin, address _wantToUSDOSMProxy, address _chainlinkWantToETHPriceFeed ) public { // Make sure we only initialize one time require(address(yVault) == address(0)); // dev: strategy already initialized address sender = msg.sender; // Initialize BaseStrategy _initialize(_vault, sender, sender, sender); // Initialize cloned instance _initializeThis( _yVault, _strategyName, _ilk, _gemJoin, _wantToUSDOSMProxy, _chainlinkWantToETHPriceFeed ); } function _initializeThis( address _yVault, string memory _strategyName, bytes32 _ilk, address _gemJoin, address _wantToUSDOSMProxy, address _chainlinkWantToETHPriceFeed ) internal { yVault = IVault(_yVault); strategyName = _strategyName; ilk = _ilk; gemJoinAdapter = _gemJoin; wantToUSDOSMProxy = IOSMedianizer(_wantToUSDOSMProxy); chainlinkWantToETHPriceFeed = AggregatorInterface( _chainlinkWantToETHPriceFeed ); // Set default router to SushiSwap router = sushiswapRouter; // Set health check to health.ychad.eth healthCheck = 0xDDCea799fF1699e98EDF118e0629A974Df7DF012; cdpId = MakerDaiDelegateLib.openCdp(ilk); require(cdpId > 0); // dev: error opening cdp // Current ratio can drift (collateralizationRatio - rebalanceTolerance, collateralizationRatio + rebalanceTolerance) // Allow additional 15% in any direction (210, 240) by default rebalanceTolerance = (15 * MAX_BPS) / 100; // Minimum collaterization ratio on YFI-A is 175% // Use 225% as target collateralizationRatio = (225 * MAX_BPS) / 100; // If we lose money in yvDAI then we are not OK selling want to repay it leaveDebtBehind = true; // Define maximum acceptable loss on withdrawal to be 0.01%. maxLoss = 1; // Set max acceptable base fee to take on more debt to 60 gwei maxAcceptableBaseFee = 60 * 1e9; } // ----------------- SETTERS & MIGRATION ----------------- // Maximum acceptable base fee of current block to take on more debt function setMaxAcceptableBaseFee(uint256 _maxAcceptableBaseFee) external onlyEmergencyAuthorized { maxAcceptableBaseFee = _maxAcceptableBaseFee; } // Target collateralization ratio to maintain within bounds function setCollateralizationRatio(uint256 _collateralizationRatio) external onlyEmergencyAuthorized { require( _collateralizationRatio.sub(rebalanceTolerance) > MakerDaiDelegateLib.getLiquidationRatio(ilk).mul(MAX_BPS).div( RAY ) ); // dev: desired collateralization ratio is too low collateralizationRatio = _collateralizationRatio; } // Rebalancing bands (collat ratio - tolerance, collat_ratio + tolerance) function setRebalanceTolerance(uint256 _rebalanceTolerance) external onlyEmergencyAuthorized { require( collateralizationRatio.sub(_rebalanceTolerance) > MakerDaiDelegateLib.getLiquidationRatio(ilk).mul(MAX_BPS).div( RAY ) ); // dev: desired rebalance tolerance makes allowed ratio too low rebalanceTolerance = _rebalanceTolerance; } // Max slippage to accept when withdrawing from yVault function setMaxLoss(uint256 _maxLoss) external onlyVaultManagers { require(_maxLoss <= MAX_LOSS_BPS); // dev: invalid value for max loss maxLoss = _maxLoss; } // If set to true the strategy will never sell want to repay debts function setLeaveDebtBehind(bool _leaveDebtBehind) external onlyEmergencyAuthorized { leaveDebtBehind = _leaveDebtBehind; } // Required to move funds to a new cdp and use a different cdpId after migration // Should only be called by governance as it will move funds function shiftToCdp(uint256 newCdpId) external onlyGovernance { MakerDaiDelegateLib.shiftCdp(cdpId, newCdpId); cdpId = newCdpId; } // Move yvDAI funds to a new yVault function migrateToNewDaiYVault(IVault newYVault) external onlyGovernance { uint256 balanceOfYVault = yVault.balanceOf(address(this)); if (balanceOfYVault > 0) { yVault.withdraw(balanceOfYVault, address(this), maxLoss); } investmentToken.safeApprove(address(yVault), 0); yVault = newYVault; _depositInvestmentTokenInYVault(); } // Allow address to manage Maker's CDP function grantCdpManagingRightsToUser(address user, bool allow) external onlyGovernance { MakerDaiDelegateLib.allowManagingCdp(cdpId, user, allow); } // Allow switching between Uniswap and SushiSwap function switchDex(bool isUniswap) external onlyVaultManagers { if (isUniswap) { router = uniswapRouter; } else { router = sushiswapRouter; } } // Allow external debt repayment // Attempt to take currentRatio to target c-ratio // Passing zero will repay all debt if possible function emergencyDebtRepayment(uint256 currentRatio) external onlyVaultManagers { _repayDebt(currentRatio); } // Allow repayment of an arbitrary amount of Dai without having to // grant access to the CDP in case of an emergency // Difference with `emergencyDebtRepayment` function above is that here we // are short-circuiting all strategy logic and repaying Dai at once // This could be helpful if for example yvDAI withdrawals are failing and // we want to do a Dai airdrop and direct debt repayment instead function repayDebtWithDaiBalance(uint256 amount) external onlyVaultManagers { _repayInvestmentTokenDebt(amount); } // ******** OVERRIDEN METHODS FROM BASE CONTRACT ************ function name() external view override returns (string memory) { return strategyName; } function delegatedAssets() external view override returns (uint256) { return _convertInvestmentTokenToWant(_valueOfInvestment()); } function estimatedTotalAssets() public view override returns (uint256) { return balanceOfWant() .add(balanceOfMakerVault()) .add(_convertInvestmentTokenToWant(balanceOfInvestmentToken())) .add(_convertInvestmentTokenToWant(_valueOfInvestment())) .sub(_convertInvestmentTokenToWant(balanceOfDebt())); } function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { uint256 totalDebt = vault.strategies(address(this)).totalDebt; // Claim rewards from yVault _takeYVaultProfit(); uint256 totalAssetsAfterProfit = estimatedTotalAssets(); _profit = totalAssetsAfterProfit > totalDebt ? totalAssetsAfterProfit.sub(totalDebt) : 0; uint256 _amountFreed; (_amountFreed, _loss) = liquidatePosition( _debtOutstanding.add(_profit) ); _debtPayment = Math.min(_debtOutstanding, _amountFreed); if (_loss > _profit) { // Example: // debtOutstanding 100, profit 50, _amountFreed 100, _loss 50 // loss should be 0, (50-50) // profit should endup in 0 _loss = _loss.sub(_profit); _profit = 0; } else { // Example: // debtOutstanding 100, profit 50, _amountFreed 140, _loss 10 // _profit should be 40, (50 profit - 10 loss) // loss should end up in be 0 _profit = _profit.sub(_loss); _loss = 0; } } function adjustPosition(uint256 _debtOutstanding) internal override { MakerDaiDelegateLib.keepBasicMakerHygiene(ilk); // If we have enough want to deposit more into the maker vault, we do it // Do not skip the rest of the function as it may need to repay or take on more debt uint256 wantBalance = balanceOfWant(); if (wantBalance > _debtOutstanding) { uint256 amountToDeposit = wantBalance.sub(_debtOutstanding); _depositToMakerVault(amountToDeposit); } // Allow the ratio to move a bit in either direction to avoid cycles uint256 currentRatio = getCurrentMakerVaultRatio(); if (currentRatio < collateralizationRatio.sub(rebalanceTolerance)) { _repayDebt(currentRatio); } else if ( currentRatio > collateralizationRatio.add(rebalanceTolerance) ) { _mintMoreInvestmentToken(); } // If we have anything left to invest then deposit into the yVault _depositInvestmentTokenInYVault(); } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 balance = balanceOfWant(); // Check if we can handle it without freeing collateral if (balance >= _amountNeeded) { return (_amountNeeded, 0); } // We only need to free the amount of want not readily available uint256 amountToFree = _amountNeeded.sub(balance); uint256 price = _getWantTokenPrice(); uint256 collateralBalance = balanceOfMakerVault(); // We cannot free more than what we have locked amountToFree = Math.min(amountToFree, collateralBalance); uint256 totalDebt = balanceOfDebt(); // If for some reason we do not have debt, make sure the operation does not revert if (totalDebt == 0) { totalDebt = 1; } uint256 toFreeIT = amountToFree.mul(price).div(WAD); uint256 collateralIT = collateralBalance.mul(price).div(WAD); uint256 newRatio = collateralIT.sub(toFreeIT).mul(MAX_BPS).div(totalDebt); // Attempt to repay necessary debt to restore the target collateralization ratio _repayDebt(newRatio); // Unlock as much collateral as possible while keeping the target ratio amountToFree = Math.min(amountToFree, _maxWithdrawal()); _freeCollateralAndRepayDai(amountToFree, 0); // If we still need more want to repay, we may need to unlock some collateral to sell if ( !leaveDebtBehind && balanceOfWant() < _amountNeeded && balanceOfDebt() > 0 ) { _sellCollateralToRepayRemainingDebtIfNeeded(); } uint256 looseWant = balanceOfWant(); if (_amountNeeded > looseWant) { _liquidatedAmount = looseWant; _loss = _amountNeeded.sub(looseWant); } else { _liquidatedAmount = _amountNeeded; _loss = 0; } } function liquidateAllPositions() internal override returns (uint256 _amountFreed) { (_amountFreed, ) = liquidatePosition(estimatedTotalAssets()); } function harvestTrigger(uint256 callCost) public view override returns (bool) { return isCurrentBaseFeeAcceptable() && super.harvestTrigger(callCost); } function tendTrigger(uint256 callCostInWei) public view override returns (bool) { // Nothing to adjust if there is no collateral locked if (balanceOfMakerVault() == 0) { return false; } uint256 currentRatio = getCurrentMakerVaultRatio(); // If we need to repay debt and are outside the tolerance bands, // we do it regardless of the call cost if (currentRatio < collateralizationRatio.sub(rebalanceTolerance)) { return true; } // Mint more DAI if possible return currentRatio > collateralizationRatio.add(rebalanceTolerance) && balanceOfDebt() > 0 && isCurrentBaseFeeAcceptable() && MakerDaiDelegateLib.isDaiAvailableToMint(ilk); } function prepareMigration(address _newStrategy) internal override { // Transfer Maker Vault ownership to the new startegy MakerDaiDelegateLib.transferCdp(cdpId, _newStrategy); // Move yvDAI balance to the new strategy IERC20(yVault).safeTransfer( _newStrategy, yVault.balanceOf(address(this)) ); } function protectedTokens() internal view override returns (address[] memory) {} function ethToWant(uint256 _amtInWei) public view virtual override returns (uint256) { if (address(want) == address(WETH)) { return _amtInWei; } uint256 price = uint256(chainlinkWantToETHPriceFeed.latestAnswer()); return _amtInWei.mul(WAD).div(price); } // ----------------- INTERNAL FUNCTIONS SUPPORT ----------------- function _repayDebt(uint256 currentRatio) internal { uint256 currentDebt = balanceOfDebt(); // Nothing to repay if we are over the collateralization ratio // or there is no debt if (currentRatio > collateralizationRatio || currentDebt == 0) { return; } // ratio = collateral / debt // collateral = current_ratio * current_debt // collateral amount is invariant here so we want to find new_debt // so that new_debt * desired_ratio = current_debt * current_ratio // new_debt = current_debt * current_ratio / desired_ratio // and the amount to repay is the difference between current_debt and new_debt uint256 newDebt = currentDebt.mul(currentRatio).div(collateralizationRatio); uint256 amountToRepay; // Maker will revert if the outstanding debt is less than a debt floor // called 'dust'. If we are there we need to either pay the debt in full // or leave at least 'dust' balance (10,000 DAI for YFI-A) uint256 debtFloor = MakerDaiDelegateLib.debtFloor(ilk); if (newDebt <= debtFloor) { // If we sold want to repay debt we will have DAI readily available in the strategy // This means we need to count both yvDAI shares and current DAI balance uint256 totalInvestmentAvailableToRepay = _valueOfInvestment().add(balanceOfInvestmentToken()); if (totalInvestmentAvailableToRepay >= currentDebt) { // Pay the entire debt if we have enough investment token amountToRepay = currentDebt; } else { // Pay just 0.1 cent above debtFloor (best effort without liquidating want) amountToRepay = currentDebt.sub(debtFloor).sub(1e15); } } else { // If we are not near the debt floor then just pay the exact amount // needed to obtain a healthy collateralization ratio amountToRepay = currentDebt.sub(newDebt); } uint256 balanceIT = balanceOfInvestmentToken(); if (amountToRepay > balanceIT) { _withdrawFromYVault(amountToRepay.sub(balanceIT)); } _repayInvestmentTokenDebt(amountToRepay); } function _sellCollateralToRepayRemainingDebtIfNeeded() internal { uint256 currentInvestmentValue = _valueOfInvestment(); uint256 investmentLeftToAcquire = balanceOfDebt().sub(currentInvestmentValue); uint256 investmentLeftToAcquireInWant = _convertInvestmentTokenToWant(investmentLeftToAcquire); if (investmentLeftToAcquireInWant <= balanceOfWant()) { _buyInvestmentTokenWithWant(investmentLeftToAcquire); _repayDebt(0); _freeCollateralAndRepayDai(balanceOfMakerVault(), 0); } } // Mint the maximum DAI possible for the locked collateral function _mintMoreInvestmentToken() internal { uint256 price = _getWantTokenPrice(); uint256 amount = balanceOfMakerVault(); uint256 daiToMint = amount.mul(price).mul(MAX_BPS).div(collateralizationRatio).div(WAD); daiToMint = daiToMint.sub(balanceOfDebt()); _lockCollateralAndMintDai(0, daiToMint); } function _withdrawFromYVault(uint256 _amountIT) internal returns (uint256) { if (_amountIT == 0) { return 0; } // No need to check allowance because the contract == token uint256 balancePrior = balanceOfInvestmentToken(); uint256 sharesToWithdraw = Math.min( _investmentTokenToYShares(_amountIT), yVault.balanceOf(address(this)) ); if (sharesToWithdraw == 0) { return 0; } yVault.withdraw(sharesToWithdraw, address(this), maxLoss); return balanceOfInvestmentToken().sub(balancePrior); } function _depositInvestmentTokenInYVault() internal { uint256 balanceIT = balanceOfInvestmentToken(); if (balanceIT > 0) { _checkAllowance( address(yVault), address(investmentToken), balanceIT ); yVault.deposit(); } } function _repayInvestmentTokenDebt(uint256 amount) internal { if (amount == 0) { return; } uint256 debt = balanceOfDebt(); uint256 balanceIT = balanceOfInvestmentToken(); // We cannot pay more than loose balance amount = Math.min(amount, balanceIT); // We cannot pay more than we owe amount = Math.min(amount, debt); _checkAllowance( MakerDaiDelegateLib.daiJoinAddress(), address(investmentToken), amount ); if (amount > 0) { // When repaying the full debt it is very common to experience Vat/dust // reverts due to the debt being non-zero and less than the debt floor. // This can happen due to rounding when _wipeAndFreeGem() divides // the DAI amount by the accumulated stability fee rate. // To circumvent this issue we will add 1 Wei to the amount to be paid // if there is enough investment token balance (DAI) to do it. if (debt.sub(amount) == 0 && balanceIT.sub(amount) >= 1) { amount = amount.add(1); } // Repay debt amount without unlocking collateral _freeCollateralAndRepayDai(0, amount); } } function _checkAllowance( address _contract, address _token, uint256 _amount ) internal { if (IERC20(_token).allowance(address(this), _contract) < _amount) { IERC20(_token).safeApprove(_contract, 0); IERC20(_token).safeApprove(_contract, type(uint256).max); } } function _takeYVaultProfit() internal { uint256 _debt = balanceOfDebt(); uint256 _valueInVault = _valueOfInvestment(); if (_debt >= _valueInVault) { return; } uint256 profit = _valueInVault.sub(_debt); uint256 ySharesToWithdraw = _investmentTokenToYShares(profit); if (ySharesToWithdraw > 0) { yVault.withdraw(ySharesToWithdraw, address(this), maxLoss); _sellAForB( balanceOfInvestmentToken(), address(investmentToken), address(want) ); } } function _depositToMakerVault(uint256 amount) internal { if (amount == 0) { return; } _checkAllowance(gemJoinAdapter, address(want), amount); uint256 price = _getWantTokenPrice(); uint256 daiToMint = amount.mul(price).mul(MAX_BPS).div(collateralizationRatio).div(WAD); _lockCollateralAndMintDai(amount, daiToMint); } // Returns maximum collateral to withdraw while maintaining the target collateralization ratio function _maxWithdrawal() internal view returns (uint256) { // Denominated in want uint256 totalCollateral = balanceOfMakerVault(); // Denominated in investment token uint256 totalDebt = balanceOfDebt(); // If there is no debt to repay we can withdraw all the locked collateral if (totalDebt == 0) { return totalCollateral; } uint256 price = _getWantTokenPrice(); // Min collateral in want that needs to be locked with the outstanding debt // Allow going to the lower rebalancing band uint256 minCollateral = collateralizationRatio .sub(rebalanceTolerance) .mul(totalDebt) .mul(WAD) .div(price) .div(MAX_BPS); // If we are under collateralized then it is not safe for us to withdraw anything if (minCollateral > totalCollateral) { return 0; } return totalCollateral.sub(minCollateral); } // ----------------- PUBLIC BALANCES AND CALCS ----------------- function balanceOfWant() public view returns (uint256) { return want.balanceOf(address(this)); } function balanceOfInvestmentToken() public view returns (uint256) { return investmentToken.balanceOf(address(this)); } function balanceOfDebt() public view returns (uint256) { return MakerDaiDelegateLib.debtForCdp(cdpId, ilk); } // Returns collateral balance in the vault function balanceOfMakerVault() public view returns (uint256) { return MakerDaiDelegateLib.balanceOfCdp(cdpId, ilk); } // Effective collateralization ratio of the vault function getCurrentMakerVaultRatio() public view returns (uint256) { return MakerDaiDelegateLib.getPessimisticRatioOfCdpWithExternalPrice( cdpId, ilk, _getWantTokenPrice(), MAX_BPS ); } // Check if current block's base fee is under max allowed base fee function isCurrentBaseFeeAcceptable() public view returns (bool) { uint256 baseFee; try baseFeeProvider.basefee_global() returns (uint256 currentBaseFee) { baseFee = currentBaseFee; } catch { // Useful for testing until ganache supports london fork // Hard-code current base fee to 1000 gwei // This should also help keepers that run in a fork without // baseFee() to avoid reverting and potentially abandoning the job baseFee = 1000 * 1e9; } return baseFee <= maxAcceptableBaseFee; } // ----------------- INTERNAL CALCS ----------------- // Returns the minimum price available function _getWantTokenPrice() internal view returns (uint256) { // Use price from spotter as base uint256 minPrice = MakerDaiDelegateLib.getSpotPrice(ilk); // Peek the OSM to get current price try wantToUSDOSMProxy.read() returns ( uint256 current, bool currentIsValid ) { if (currentIsValid && current > 0) { minPrice = Math.min(minPrice, current); } } catch { // Ignore price peek()'d from OSM. Maybe we are no longer authorized. } // Peep the OSM to get future price try wantToUSDOSMProxy.foresight() returns ( uint256 future, bool futureIsValid ) { if (futureIsValid && future > 0) { minPrice = Math.min(minPrice, future); } } catch { // Ignore price peep()'d from OSM. Maybe we are no longer authorized. } // If price is set to 0 then we hope no liquidations are taking place // Emergency scenarios can be handled via manual debt repayment or by // granting governance access to the CDP require(minPrice > 0); // dev: invalid spot price // par is crucial to this calculation as it defines the relationship between DAI and // 1 unit of value in the price return minPrice.mul(RAY).div(MakerDaiDelegateLib.getDaiPar()); } function _valueOfInvestment() internal view returns (uint256) { return yVault.balanceOf(address(this)).mul(yVault.pricePerShare()).div( 10**yVault.decimals() ); } function _investmentTokenToYShares(uint256 amount) internal view returns (uint256) { return amount.mul(10**yVault.decimals()).div(yVault.pricePerShare()); } function _lockCollateralAndMintDai( uint256 collateralAmount, uint256 daiToMint ) internal { MakerDaiDelegateLib.lockGemAndDraw( gemJoinAdapter, cdpId, collateralAmount, daiToMint, balanceOfDebt() ); } function _freeCollateralAndRepayDai( uint256 collateralAmount, uint256 daiToRepay ) internal { MakerDaiDelegateLib.wipeAndFreeGem( gemJoinAdapter, cdpId, collateralAmount, daiToRepay ); } // ----------------- TOKEN CONVERSIONS ----------------- function _convertInvestmentTokenToWant(uint256 amount) internal view returns (uint256) { return amount.mul(WAD).div(_getWantTokenPrice()); } function _getTokenOutPath(address _token_in, address _token_out) internal pure returns (address[] memory _path) { bool is_weth = _token_in == address(WETH) || _token_out == address(WETH); _path = new address[](is_weth ? 2 : 3); _path[0] = _token_in; if (is_weth) { _path[1] = _token_out; } else { _path[1] = address(WETH); _path[2] = _token_out; } } function _sellAForB( uint256 _amount, address tokenA, address tokenB ) internal { if (_amount == 0 || tokenA == tokenB) { return; } _checkAllowance(address(router), tokenA, _amount); router.swapExactTokensForTokens( _amount, 0, _getTokenOutPath(tokenA, tokenB), address(this), now ); } function _buyInvestmentTokenWithWant(uint256 _amount) internal { if (_amount == 0 || address(investmentToken) == address(want)) { return; } _checkAllowance(address(router), address(want), _amount); router.swapTokensForExactTokens( _amount, type(uint256).max, _getTokenOutPath(address(want), address(investmentToken)), address(this), now ); } } // File: MakerDaiDelegateCloner.sol contract MakerDaiDelegateCloner { address public immutable original; event Cloned(address indexed clone); event Deployed(address indexed original); constructor( address _vault, address _yVault, string memory _strategyName, bytes32 _ilk, address _gemJoin, address _wantToUSDOSMProxy, address _chainlinkWantToETHPriceFeed ) public { Strategy _original = new Strategy( _vault, _yVault, _strategyName, _ilk, _gemJoin, _wantToUSDOSMProxy, _chainlinkWantToETHPriceFeed ); emit Deployed(address(_original)); original = address(_original); Strategy(_original).setRewards( 0xc491599b9A20c3A2F0A85697Ee6D9434EFa9f503 ); Strategy(_original).setKeeper( 0x736D7e3c5a6CB2CE3B764300140ABF476F6CFCCF ); Strategy(_original).setStrategist( 0x16388463d60FFE0661Cf7F1f31a7D658aC790ff7 ); } function cloneMakerDaiDelegate( address _vault, address _strategist, address _rewards, address _keeper, address _yVault, string memory _strategyName, bytes32 _ilk, address _gemJoin, address _wantToUSDOSMProxy, address _chainlinkWantToETHPriceFeed ) external returns (address newStrategy) { // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol bytes20 addressBytes = bytes20(original); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore( clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone_code, 0x14), addressBytes) mstore( add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) newStrategy := create(0, clone_code, 0x37) } Strategy(newStrategy).initialize( _vault, _yVault, _strategyName, _ilk, _gemJoin, _wantToUSDOSMProxy, _chainlinkWantToETHPriceFeed ); Strategy(newStrategy).setKeeper(_keeper); Strategy(newStrategy).setRewards(_rewards); Strategy(newStrategy).setStrategist(_strategist); emit Cloned(newStrategy); } function name() external pure returns (string memory) { return "Yearn-MakerDaiDelegateCloner@0.4.3"; } }
Check if current block's base fee is under max allowed base fee Useful for testing until ganache supports london fork Hard-code current base fee to 1000 gwei This should also help keepers that run in a fork without baseFee() to avoid reverting and potentially abandoning the job
function isCurrentBaseFeeAcceptable() public view returns (bool) { uint256 baseFee; try baseFeeProvider.basefee_global() returns (uint256 currentBaseFee) { baseFee = currentBaseFee; baseFee = 1000 * 1e9; } return baseFee <= maxAcceptableBaseFee; }
508,438
/** *Submitted for verification at Etherscan.io on 2020-02-11 */ // File: @aragon/os/contracts/common/EtherTokenConstant.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; // aragonOS and aragon-apps rely on address(0) to denote native ETH, in // contracts where both tokens and ETH are accepted contract EtherTokenConstant { address internal constant ETH = address(0); } // File: @aragon/apps-agent/contracts/standards/ERC1271.sol pragma solidity 0.4.24; // ERC1271 on Feb 12th, 2019: https://github.com/ethereum/EIPs/blob/a97dc434930d0ccc4461c97d8c7a920dc585adf2/EIPS/eip-1271.md // Using `isValidSignature(bytes32,bytes)` even though the standard still hasn't been modified // Rationale: https://github.com/ethereum/EIPs/issues/1271#issuecomment-462719728 contract ERC1271 { bytes4 constant public ERC1271_INTERFACE_ID = 0xfb855dc9; // this.isValidSignature.selector bytes4 constant public ERC1271_RETURN_VALID_SIGNATURE = 0x20c13b0b; // TODO: Likely needs to be updated bytes4 constant public ERC1271_RETURN_INVALID_SIGNATURE = 0x00000000; /** * @dev Function must be implemented by deriving contract * @param _hash Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * @return A bytes4 magic value 0x20c13b0b if the signature check passes, 0x00000000 if not * * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature(bytes32 _hash, bytes memory _signature) public view returns (bytes4); function returnIsValidSignatureMagicNumber(bool isValid) internal pure returns (bytes4) { return isValid ? ERC1271_RETURN_VALID_SIGNATURE : ERC1271_RETURN_INVALID_SIGNATURE; } } contract ERC1271Bytes is ERC1271 { /** * @dev Default behavior of `isValidSignature(bytes,bytes)`, can be overloaded for custom validation * @param _data Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * @return A bytes4 magic value 0x20c13b0b if the signature check passes, 0x00000000 if not * * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature(bytes _data, bytes _signature) public view returns (bytes4) { return isValidSignature(keccak256(_data), _signature); } } // File: @aragon/apps-agent/contracts/SignatureValidator.sol pragma solidity 0.4.24; // Inspired by https://github.com/horizon-games/multi-token-standard/blob/319740cf2a78b8816269ae49a09c537b3fd7303b/contracts/utils/SignatureValidator.sol // This should probably be moved into aOS: https://github.com/aragon/aragonOS/pull/442 library SignatureValidator { enum SignatureMode { Invalid, // 0x00 EIP712, // 0x01 EthSign, // 0x02 ERC1271, // 0x03 NMode // 0x04, to check if mode is specified, leave at the end } // bytes4(keccak256("isValidSignature(bytes,bytes)") bytes4 public constant ERC1271_RETURN_VALID_SIGNATURE = 0x20c13b0b; uint256 internal constant ERC1271_ISVALIDSIG_MAX_GAS = 250000; string private constant ERROR_INVALID_LENGTH_POP_BYTE = "SIGVAL_INVALID_LENGTH_POP_BYTE"; /// @dev Validates that a hash was signed by a specified signer. /// @param hash Hash which was signed. /// @param signer Address of the signer. /// @param signature ECDSA signature along with the mode (0 = Invalid, 1 = EIP712, 2 = EthSign, 3 = ERC1271) {mode}{r}{s}{v}. /// @return Returns whether signature is from a specified user. function isValidSignature(bytes32 hash, address signer, bytes signature) internal view returns (bool) { if (signature.length == 0) { return false; } uint8 modeByte = uint8(signature[0]); if (modeByte >= uint8(SignatureMode.NMode)) { return false; } SignatureMode mode = SignatureMode(modeByte); if (mode == SignatureMode.EIP712) { return ecVerify(hash, signer, signature); } else if (mode == SignatureMode.EthSign) { return ecVerify( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), signer, signature ); } else if (mode == SignatureMode.ERC1271) { // Pop the mode byte before sending it down the validation chain return safeIsValidSignature(signer, hash, popFirstByte(signature)); } else { return false; } } function ecVerify(bytes32 hash, address signer, bytes memory signature) private pure returns (bool) { (bool badSig, bytes32 r, bytes32 s, uint8 v) = unpackEcSig(signature); if (badSig) { return false; } return signer == ecrecover(hash, v, r, s); } function unpackEcSig(bytes memory signature) private pure returns (bool badSig, bytes32 r, bytes32 s, uint8 v) { if (signature.length != 66) { badSig = true; return; } v = uint8(signature[65]); assembly { r := mload(add(signature, 33)) s := mload(add(signature, 65)) } // Allow signature version to be 0 or 1 if (v < 27) { v += 27; } if (v != 27 && v != 28) { badSig = true; } } function popFirstByte(bytes memory input) private pure returns (bytes memory output) { uint256 inputLength = input.length; require(inputLength > 0, ERROR_INVALID_LENGTH_POP_BYTE); output = new bytes(inputLength - 1); if (output.length == 0) { return output; } uint256 inputPointer; uint256 outputPointer; assembly { inputPointer := add(input, 0x21) outputPointer := add(output, 0x20) } memcpy(outputPointer, inputPointer, output.length); } function safeIsValidSignature(address validator, bytes32 hash, bytes memory signature) private view returns (bool) { bytes memory data = abi.encodeWithSelector(ERC1271(validator).isValidSignature.selector, hash, signature); bytes4 erc1271Return = safeBytes4StaticCall(validator, data, ERC1271_ISVALIDSIG_MAX_GAS); return erc1271Return == ERC1271_RETURN_VALID_SIGNATURE; } function safeBytes4StaticCall(address target, bytes data, uint256 maxGas) private view returns (bytes4 ret) { uint256 gasLeft = gasleft(); uint256 callGas = gasLeft > maxGas ? maxGas : gasLeft; bool ok; assembly { ok := staticcall(callGas, target, add(data, 0x20), mload(data), 0, 0) } if (!ok) { return; } uint256 size; assembly { size := returndatasize } if (size != 32) { return; } assembly { let ptr := mload(0x40) // get next free memory ptr returndatacopy(ptr, 0, size) // copy return from above `staticcall` ret := mload(ptr) // read data at ptr and set it to be returned } return ret; } // From: https://github.com/Arachnid/solidity-stringutils/blob/01e955c1d6/src/strings.sol function memcpy(uint256 dest, uint256 src, uint256 len) private pure { // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } } // File: @aragon/apps-agent/contracts/standards/IERC165.sol pragma solidity 0.4.24; interface IERC165 { function supportsInterface(bytes4 interfaceId) external pure returns (bool); } // File: @aragon/os/contracts/common/UnstructuredStorage.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; library UnstructuredStorage { function getStorageBool(bytes32 position) internal view returns (bool data) { assembly { data := sload(position) } } function getStorageAddress(bytes32 position) internal view returns (address data) { assembly { data := sload(position) } } function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) { assembly { data := sload(position) } } function getStorageUint256(bytes32 position) internal view returns (uint256 data) { assembly { data := sload(position) } } function setStorageBool(bytes32 position, bool data) internal { assembly { sstore(position, data) } } function setStorageAddress(bytes32 position, address data) internal { assembly { sstore(position, data) } } function setStorageBytes32(bytes32 position, bytes32 data) internal { assembly { sstore(position, data) } } function setStorageUint256(bytes32 position, uint256 data) internal { assembly { sstore(position, data) } } } // File: @aragon/os/contracts/acl/IACL.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IACL { function initialize(address permissionsCreator) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); } // File: @aragon/os/contracts/common/IVaultRecoverable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IVaultRecoverable { event RecoverToVault(address indexed vault, address indexed token, uint256 amount); function transferToVault(address token) external; function allowRecoverability(address token) external view returns (bool); function getRecoveryVault() external view returns (address); } // File: @aragon/os/contracts/kernel/IKernel.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IKernelEvents { event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app); } // This should be an interface, but interfaces can't inherit yet :( contract IKernel is IKernelEvents, IVaultRecoverable { function acl() public view returns (IACL); function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); function setApp(bytes32 namespace, bytes32 appId, address app) public; function getApp(bytes32 namespace, bytes32 appId) public view returns (address); } // File: @aragon/os/contracts/apps/AppStorage.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract AppStorage { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel"); bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId"); */ bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b; bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b; function kernel() public view returns (IKernel) { return IKernel(KERNEL_POSITION.getStorageAddress()); } function appId() public view returns (bytes32) { return APP_ID_POSITION.getStorageBytes32(); } function setKernel(IKernel _kernel) internal { KERNEL_POSITION.setStorageAddress(address(_kernel)); } function setAppId(bytes32 _appId) internal { APP_ID_POSITION.setStorageBytes32(_appId); } } // File: @aragon/os/contracts/acl/ACLSyntaxSugar.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ACLSyntaxSugar { function arr() internal pure returns (uint256[]) { return new uint256[](0); } function arr(bytes32 _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(address _a, address _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c); } function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c, _d); } function arr(address _a, uint256 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), _c, _d, _e); } function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(uint256 _a) internal pure returns (uint256[] r) { r = new uint256[](1); r[0] = _a; } function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) { r = new uint256[](2); r[0] = _a; r[1] = _b; } function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { r = new uint256[](3); r[0] = _a; r[1] = _b; r[2] = _c; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { r = new uint256[](4); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { r = new uint256[](5); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; r[4] = _e; } } contract ACLHelpers { function decodeParamOp(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 30)); } function decodeParamId(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 31)); } function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) { a = uint32(_x); b = uint32(_x >> (8 * 4)); c = uint32(_x >> (8 * 8)); } } // File: @aragon/os/contracts/common/Uint256Helpers.sol pragma solidity ^0.4.24; library Uint256Helpers { uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG); return uint64(a); } } // File: @aragon/os/contracts/common/TimeHelpers.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract TimeHelpers { using Uint256Helpers for uint256; /** * @dev Returns the current block number. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @dev Returns the current block number, converted to uint64. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); } /** * @dev Returns the current timestamp. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp() internal view returns (uint256) { return block.timestamp; // solium-disable-line security/no-block-members } /** * @dev Returns the current timestamp, converted to uint64. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp64() internal view returns (uint64) { return getTimestamp().toUint64(); } } // File: @aragon/os/contracts/common/Initializable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Initializable is TimeHelpers { using UnstructuredStorage for bytes32; // keccak256("aragonOS.initializable.initializationBlock") bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e; string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED"; string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED"; modifier onlyInit { require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED); _; } modifier isInitialized { require(hasInitialized(), ERROR_NOT_INITIALIZED); _; } /** * @return Block number in which the contract was initialized */ function getInitializationBlock() public view returns (uint256) { return INITIALIZATION_BLOCK_POSITION.getStorageUint256(); } /** * @return Whether the contract has been initialized by the time of the current block */ function hasInitialized() public view returns (bool) { uint256 initializationBlock = getInitializationBlock(); return initializationBlock != 0 && getBlockNumber() >= initializationBlock; } /** * @dev Function to be called by top level contract after initialization has finished. */ function initialized() internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber()); } /** * @dev Function to be called by top level contract after initialization to enable the contract * at a future block number rather than immediately. */ function initializedAt(uint256 _blockNumber) internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber); } } // File: @aragon/os/contracts/common/Petrifiable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Petrifiable is Initializable { // Use block UINT256_MAX (which should be never) as the initializable date uint256 internal constant PETRIFIED_BLOCK = uint256(-1); function isPetrified() public view returns (bool) { return getInitializationBlock() == PETRIFIED_BLOCK; } /** * @dev Function to be called by top level contract to prevent being initialized. * Useful for freezing base contracts when they're used behind proxies. */ function petrify() internal onlyInit { initializedAt(PETRIFIED_BLOCK); } } // File: @aragon/os/contracts/common/Autopetrified.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Autopetrified is Petrifiable { constructor() public { // Immediately petrify base (non-proxy) instances of inherited contracts on deploy. // This renders them uninitializable (and unusable without a proxy). petrify(); } } // File: @aragon/os/contracts/common/ConversionHelpers.sol pragma solidity ^0.4.24; library ConversionHelpers { string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH"; function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) { // Force cast the uint256[] into a bytes array, by overwriting its length // Note that the bytes array doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 byteLength = _input.length * 32; assembly { output := _input mstore(output, byteLength) } } function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) { // Force cast the bytes array into a uint256[], by overwriting its length // Note that the uint256[] doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 intsLength = _input.length / 32; require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH); assembly { output := _input mstore(output, intsLength) } } } // File: @aragon/os/contracts/common/ReentrancyGuard.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ReentrancyGuard { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex"); */ bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb; string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL"; modifier nonReentrant() { // Ensure mutex is unlocked require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT); // Lock mutex before function call REENTRANCY_MUTEX_POSITION.setStorageBool(true); // Perform function call _; // Unlock mutex after function call REENTRANCY_MUTEX_POSITION.setStorageBool(false); } } // File: @aragon/os/contracts/lib/token/ERC20.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: @aragon/os/contracts/common/IsContract.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } // File: @aragon/os/contracts/common/SafeERC20.sol // Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol) // and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143) pragma solidity ^0.4.24; library SafeERC20 { // Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`: // https://github.com/ethereum/solidity/issues/3544 bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb; string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED"; string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED"; function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) { bool ret; assembly { let ptr := mload(0x40) // free memory pointer let success := call( gas, // forward all gas _addr, // address 0, // no value add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { // Check number of bytes returned from last function call switch returndatasize // No bytes returned: assume success case 0 { ret := 1 } // 32 bytes returned: check if non-zero case 0x20 { // Only return success if returned data was true // Already have output in ptr ret := eq(mload(ptr), 1) } // Not sure what was returned: don't mark as success default { } } } return ret; } function staticInvoke(address _addr, bytes memory _calldata) private view returns (bool, uint256) { bool success; uint256 ret; assembly { let ptr := mload(0x40) // free memory pointer success := staticcall( gas, // forward all gas _addr, // address add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { ret := mload(ptr) } } return (success, ret); } /** * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) { bytes memory transferCallData = abi.encodeWithSelector( TRANSFER_SELECTOR, _to, _amount ); return invokeAndCheckSuccess(_token, transferCallData); } /** * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { bytes memory transferFromCallData = abi.encodeWithSelector( _token.transferFrom.selector, _from, _to, _amount ); return invokeAndCheckSuccess(_token, transferFromCallData); } /** * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) { bytes memory approveCallData = abi.encodeWithSelector( _token.approve.selector, _spender, _amount ); return invokeAndCheckSuccess(_token, approveCallData); } /** * @dev Static call into ERC20.balanceOf(). * Reverts if the call fails for some reason (should never fail). */ function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) { bytes memory balanceOfCallData = abi.encodeWithSelector( _token.balanceOf.selector, _owner ); (bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData); require(success, ERROR_TOKEN_BALANCE_REVERTED); return tokenBalance; } /** * @dev Static call into ERC20.allowance(). * Reverts if the call fails for some reason (should never fail). */ function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) { bytes memory allowanceCallData = abi.encodeWithSelector( _token.allowance.selector, _owner, _spender ); (bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData); require(success, ERROR_TOKEN_ALLOWANCE_REVERTED); return allowance; } } // File: @aragon/os/contracts/common/VaultRecoverable.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract { using SafeERC20 for ERC20; string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED"; string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT"; string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED"; /** * @notice Send funds to recovery Vault. This contract should never receive funds, * but in case it does, this function allows one to recover them. * @param _token Token balance to be sent to recovery vault. */ function transferToVault(address _token) external { require(allowRecoverability(_token), ERROR_DISALLOWED); address vault = getRecoveryVault(); require(isContract(vault), ERROR_VAULT_NOT_CONTRACT); uint256 balance; if (_token == ETH) { balance = address(this).balance; vault.transfer(balance); } else { ERC20 token = ERC20(_token); balance = token.staticBalanceOf(this); require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED); } emit RecoverToVault(vault, _token, balance); } /** * @dev By default deriving from AragonApp makes it recoverable * @param token Token address that would be recovered * @return bool whether the app allows the recovery */ function allowRecoverability(address token) public view returns (bool) { return true; } // Cast non-implemented interface to be public so we can use it internally function getRecoveryVault() public view returns (address); } // File: @aragon/os/contracts/evmscript/IEVMScriptExecutor.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IEVMScriptExecutor { function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes); function executorType() external pure returns (bytes32); } // File: @aragon/os/contracts/evmscript/IEVMScriptRegistry.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract EVMScriptRegistryConstants { /* Hardcoded constants to save gas bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg"); */ bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61; } interface IEVMScriptRegistry { function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id); function disableScriptExecutor(uint256 executorId) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor); } // File: @aragon/os/contracts/kernel/KernelConstants.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract KernelAppIds { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel"); bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl"); bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault"); */ bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c; bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a; bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; } contract KernelNamespaceConstants { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core"); bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base"); bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app"); */ bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8; bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f; bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb; } // File: @aragon/os/contracts/evmscript/EVMScriptRunner.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants { string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE"; string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED"; /* This is manually crafted in assembly string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN"; */ event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData); function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script)); } function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) { address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID); return IEVMScriptRegistry(registryAddr); } function runScript(bytes _script, bytes _input, address[] _blacklist) internal isInitialized protectState returns (bytes) { IEVMScriptExecutor executor = getEVMScriptExecutor(_script); require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE); bytes4 sig = executor.execScript.selector; bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist); bytes memory output; assembly { let success := delegatecall( gas, // forward all gas executor, // address add(data, 0x20), // calldata start mload(data), // calldata length 0, // don't write output (we'll handle this ourselves) 0 // don't write output ) output := mload(0x40) // free mem ptr get switch success case 0 { // If the call errored, forward its full error data returndatacopy(output, 0, returndatasize) revert(output, returndatasize) } default { switch gt(returndatasize, 0x3f) case 0 { // Need at least 0x40 bytes returned for properly ABI-encoded bytes values, // revert with "EVMRUN_EXECUTOR_INVALID_RETURN" // See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in // this memory layout mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Copy result // // Needs to perform an ABI decode for the expected `bytes` return type of // `executor.execScript()` as solidity will automatically ABI encode the returned bytes as: // [ position of the first dynamic length return value = 0x20 (32 bytes) ] // [ output length (32 bytes) ] // [ output content (N bytes) ] // // Perform the ABI decode by ignoring the first 32 bytes of the return data let copysize := sub(returndatasize, 0x20) returndatacopy(output, 0x20, copysize) mstore(0x40, add(output, copysize)) // free mem ptr set } } } emit ScriptResult(address(executor), _script, _input, output); return output; } modifier protectState { address preKernel = address(kernel()); bytes32 preAppId = appId(); _; // exec require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED); require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED); } } // File: @aragon/os/contracts/apps/AragonApp.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; // Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so // that they can never be initialized. // Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy. // ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but // are included so that they are automatically usable by subclassing contracts contract AragonApp is AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar { string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED"; modifier auth(bytes32 _role) { require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED); _; } modifier authP(bytes32 _role, uint256[] _params) { require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED); _; } /** * @dev Check whether an action can be performed by a sender for a particular role on this app * @param _sender Sender of the call * @param _role Role on this app * @param _params Permission params for the role * @return Boolean indicating whether the sender has the permissions to perform the action. * Always returns false if the app hasn't been initialized yet. */ function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) { if (!hasInitialized()) { return false; } IKernel linkedKernel = kernel(); if (address(linkedKernel) == address(0)) { return false; } return linkedKernel.hasPermission( _sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params) ); } /** * @dev Get the recovery vault for the app * @return Recovery vault address for the app */ function getRecoveryVault() public view returns (address) { // Funds recovery via a vault is only available when used with a kernel return kernel().getRecoveryVault(); // if kernel is not set, it will revert } } // File: @aragon/os/contracts/common/DepositableStorage.sol pragma solidity 0.4.24; contract DepositableStorage { using UnstructuredStorage for bytes32; // keccak256("aragonOS.depositableStorage.depositable") bytes32 internal constant DEPOSITABLE_POSITION = 0x665fd576fbbe6f247aff98f5c94a561e3f71ec2d3c988d56f12d342396c50cea; function isDepositable() public view returns (bool) { return DEPOSITABLE_POSITION.getStorageBool(); } function setDepositable(bool _depositable) internal { DEPOSITABLE_POSITION.setStorageBool(_depositable); } } // File: @aragon/apps-vault/contracts/Vault.sol pragma solidity 0.4.24; contract Vault is EtherTokenConstant, AragonApp, DepositableStorage { using SafeERC20 for ERC20; bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE"); string private constant ERROR_DATA_NON_ZERO = "VAULT_DATA_NON_ZERO"; string private constant ERROR_NOT_DEPOSITABLE = "VAULT_NOT_DEPOSITABLE"; string private constant ERROR_DEPOSIT_VALUE_ZERO = "VAULT_DEPOSIT_VALUE_ZERO"; string private constant ERROR_TRANSFER_VALUE_ZERO = "VAULT_TRANSFER_VALUE_ZERO"; string private constant ERROR_SEND_REVERTED = "VAULT_SEND_REVERTED"; string private constant ERROR_VALUE_MISMATCH = "VAULT_VALUE_MISMATCH"; string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "VAULT_TOKEN_TRANSFER_FROM_REVERT"; string private constant ERROR_TOKEN_TRANSFER_REVERTED = "VAULT_TOKEN_TRANSFER_REVERTED"; event VaultTransfer(address indexed token, address indexed to, uint256 amount); event VaultDeposit(address indexed token, address indexed sender, uint256 amount); /** * @dev On a normal send() or transfer() this fallback is never executed as it will be * intercepted by the Proxy (see aragonOS#281) */ function () external payable isInitialized { require(msg.data.length == 0, ERROR_DATA_NON_ZERO); _deposit(ETH, msg.value); } /** * @notice Initialize Vault app * @dev As an AragonApp it needs to be initialized in order for roles (`auth` and `authP`) to work */ function initialize() external onlyInit { initialized(); setDepositable(true); } /** * @notice Deposit `_value` `_token` to the vault * @param _token Address of the token being transferred * @param _value Amount of tokens being transferred */ function deposit(address _token, uint256 _value) external payable isInitialized { _deposit(_token, _value); } /** * @notice Transfer `_value` `_token` from the Vault to `_to` * @param _token Address of the token being transferred * @param _to Address of the recipient of tokens * @param _value Amount of tokens being transferred */ /* solium-disable-next-line function-order */ function transfer(address _token, address _to, uint256 _value) external authP(TRANSFER_ROLE, arr(_token, _to, _value)) { require(_value > 0, ERROR_TRANSFER_VALUE_ZERO); if (_token == ETH) { require(_to.send(_value), ERROR_SEND_REVERTED); } else { require(ERC20(_token).safeTransfer(_to, _value), ERROR_TOKEN_TRANSFER_REVERTED); } emit VaultTransfer(_token, _to, _value); } function balance(address _token) public view returns (uint256) { if (_token == ETH) { return address(this).balance; } else { return ERC20(_token).staticBalanceOf(address(this)); } } /** * @dev Disable recovery escape hatch, as it could be used * maliciously to transfer funds away from the vault */ function allowRecoverability(address) public view returns (bool) { return false; } function _deposit(address _token, uint256 _value) internal { require(isDepositable(), ERROR_NOT_DEPOSITABLE); require(_value > 0, ERROR_DEPOSIT_VALUE_ZERO); if (_token == ETH) { // Deposit is implicit in this case require(msg.value == _value, ERROR_VALUE_MISMATCH); } else { require( ERC20(_token).safeTransferFrom(msg.sender, address(this), _value), ERROR_TOKEN_TRANSFER_FROM_REVERTED ); } emit VaultDeposit(_token, msg.sender, _value); } } // File: @aragon/os/contracts/common/IForwarder.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IForwarder { function isForwarder() external pure returns (bool); // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function canForward(address sender, bytes evmCallScript) public view returns (bool); // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function forward(bytes evmCallScript) public; } // File: @aragon/apps-agent/contracts/Agent.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Agent is IERC165, ERC1271Bytes, IForwarder, IsContract, Vault { /* Hardcoded constants to save gas bytes32 public constant EXECUTE_ROLE = keccak256("EXECUTE_ROLE"); bytes32 public constant SAFE_EXECUTE_ROLE = keccak256("SAFE_EXECUTE_ROLE"); bytes32 public constant ADD_PROTECTED_TOKEN_ROLE = keccak256("ADD_PROTECTED_TOKEN_ROLE"); bytes32 public constant REMOVE_PROTECTED_TOKEN_ROLE = keccak256("REMOVE_PROTECTED_TOKEN_ROLE"); bytes32 public constant ADD_PRESIGNED_HASH_ROLE = keccak256("ADD_PRESIGNED_HASH_ROLE"); bytes32 public constant DESIGNATE_SIGNER_ROLE = keccak256("DESIGNATE_SIGNER_ROLE"); bytes32 public constant RUN_SCRIPT_ROLE = keccak256("RUN_SCRIPT_ROLE"); */ bytes32 public constant EXECUTE_ROLE = 0xcebf517aa4440d1d125e0355aae64401211d0848a23c02cc5d29a14822580ba4; bytes32 public constant SAFE_EXECUTE_ROLE = 0x0a1ad7b87f5846153c6d5a1f761d71c7d0cfd122384f56066cd33239b7933694; bytes32 public constant ADD_PROTECTED_TOKEN_ROLE = 0x6eb2a499556bfa2872f5aa15812b956cc4a71b4d64eb3553f7073c7e41415aaa; bytes32 public constant REMOVE_PROTECTED_TOKEN_ROLE = 0x71eee93d500f6f065e38b27d242a756466a00a52a1dbcd6b4260f01a8640402a; bytes32 public constant ADD_PRESIGNED_HASH_ROLE = 0x0b29780bb523a130b3b01f231ef49ed2fa2781645591a0b0a44ca98f15a5994c; bytes32 public constant DESIGNATE_SIGNER_ROLE = 0x23ce341656c3f14df6692eebd4757791e33662b7dcf9970c8308303da5472b7c; bytes32 public constant RUN_SCRIPT_ROLE = 0xb421f7ad7646747f3051c50c0b8e2377839296cd4973e27f63821d73e390338f; uint256 public constant PROTECTED_TOKENS_CAP = 10; bytes4 private constant ERC165_INTERFACE_ID = 0x01ffc9a7; string private constant ERROR_TARGET_PROTECTED = "AGENT_TARGET_PROTECTED"; string private constant ERROR_PROTECTED_TOKENS_MODIFIED = "AGENT_PROTECTED_TOKENS_MODIFIED"; string private constant ERROR_PROTECTED_BALANCE_LOWERED = "AGENT_PROTECTED_BALANCE_LOWERED"; string private constant ERROR_TOKENS_CAP_REACHED = "AGENT_TOKENS_CAP_REACHED"; string private constant ERROR_TOKEN_NOT_ERC20 = "AGENT_TOKEN_NOT_ERC20"; string private constant ERROR_TOKEN_ALREADY_PROTECTED = "AGENT_TOKEN_ALREADY_PROTECTED"; string private constant ERROR_TOKEN_NOT_PROTECTED = "AGENT_TOKEN_NOT_PROTECTED"; string private constant ERROR_DESIGNATED_TO_SELF = "AGENT_DESIGNATED_TO_SELF"; string private constant ERROR_CAN_NOT_FORWARD = "AGENT_CAN_NOT_FORWARD"; mapping (bytes32 => bool) public isPresigned; address public designatedSigner; address[] public protectedTokens; event SafeExecute(address indexed sender, address indexed target, bytes data); event Execute(address indexed sender, address indexed target, uint256 ethValue, bytes data); event AddProtectedToken(address indexed token); event RemoveProtectedToken(address indexed token); event PresignHash(address indexed sender, bytes32 indexed hash); event SetDesignatedSigner(address indexed sender, address indexed oldSigner, address indexed newSigner); /** * @notice Execute '`@radspec(_target, _data)`' on `_target``_ethValue == 0 ? '' : ' (Sending' + @tokenAmount(0x0000000000000000000000000000000000000000, _ethValue) + ')'` * @param _target Address where the action is being executed * @param _ethValue Amount of ETH from the contract that is sent with the action * @param _data Calldata for the action * @return Exits call frame forwarding the return data of the executed call (either error or success data) */ function execute(address _target, uint256 _ethValue, bytes _data) external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context authP(EXECUTE_ROLE, arr(_target, _ethValue, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs { bool result = _target.call.value(_ethValue)(_data); if (result) { emit Execute(msg.sender, _target, _ethValue, _data); } assembly { let ptr := mload(0x40) returndatacopy(ptr, 0, returndatasize) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, returndatasize) } default { return(ptr, returndatasize) } } } /** * @notice Execute '`@radspec(_target, _data)`' on `_target` ensuring that protected tokens can't be spent * @param _target Address where the action is being executed * @param _data Calldata for the action * @return Exits call frame forwarding the return data of the executed call (either error or success data) */ function safeExecute(address _target, bytes _data) external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context authP(SAFE_EXECUTE_ROLE, arr(_target, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs { uint256 protectedTokensLength = protectedTokens.length; address[] memory protectedTokens_ = new address[](protectedTokensLength); uint256[] memory balances = new uint256[](protectedTokensLength); for (uint256 i = 0; i < protectedTokensLength; i++) { address token = protectedTokens[i]; require(_target != token, ERROR_TARGET_PROTECTED); // we copy the protected tokens array to check whether the storage array has been modified during the underlying call protectedTokens_[i] = token; // we copy the balances to check whether they have been modified during the underlying call balances[i] = balance(token); } bool result = _target.call(_data); bytes32 ptr; uint256 size; assembly { size := returndatasize ptr := mload(0x40) mstore(0x40, add(ptr, returndatasize)) returndatacopy(ptr, 0, returndatasize) } if (result) { // if the underlying call has succeeded, we check that the protected tokens // and their balances have not been modified and return the call's return data require(protectedTokens.length == protectedTokensLength, ERROR_PROTECTED_TOKENS_MODIFIED); for (uint256 j = 0; j < protectedTokensLength; j++) { require(protectedTokens[j] == protectedTokens_[j], ERROR_PROTECTED_TOKENS_MODIFIED); require(balance(protectedTokens[j]) >= balances[j], ERROR_PROTECTED_BALANCE_LOWERED); } emit SafeExecute(msg.sender, _target, _data); assembly { return(ptr, size) } } else { // if the underlying call has failed, we revert and forward returned error data assembly { revert(ptr, size) } } } /** * @notice Add `_token.symbol(): string` to the list of protected tokens * @param _token Address of the token to be protected */ function addProtectedToken(address _token) external authP(ADD_PROTECTED_TOKEN_ROLE, arr(_token)) { require(protectedTokens.length < PROTECTED_TOKENS_CAP, ERROR_TOKENS_CAP_REACHED); require(_isERC20(_token), ERROR_TOKEN_NOT_ERC20); require(!_tokenIsProtected(_token), ERROR_TOKEN_ALREADY_PROTECTED); _addProtectedToken(_token); } /** * @notice Remove `_token.symbol(): string` from the list of protected tokens * @param _token Address of the token to be unprotected */ function removeProtectedToken(address _token) external authP(REMOVE_PROTECTED_TOKEN_ROLE, arr(_token)) { require(_tokenIsProtected(_token), ERROR_TOKEN_NOT_PROTECTED); _removeProtectedToken(_token); } /** * @notice Pre-sign hash `_hash` * @param _hash Hash that will be considered signed regardless of the signature checked with 'isValidSignature()' */ function presignHash(bytes32 _hash) external authP(ADD_PRESIGNED_HASH_ROLE, arr(_hash)) { isPresigned[_hash] = true; emit PresignHash(msg.sender, _hash); } /** * @notice Set `_designatedSigner` as the designated signer of the app, which will be able to sign messages on behalf of the app * @param _designatedSigner Address that will be able to sign messages on behalf of the app */ function setDesignatedSigner(address _designatedSigner) external authP(DESIGNATE_SIGNER_ROLE, arr(_designatedSigner)) { // Prevent an infinite loop by setting the app itself as its designated signer. // An undetectable loop can be created by setting a different contract as the // designated signer which calls back into `isValidSignature`. // Given that `isValidSignature` is always called with just 50k gas, the max // damage of the loop is wasting 50k gas. require(_designatedSigner != address(this), ERROR_DESIGNATED_TO_SELF); address oldDesignatedSigner = designatedSigner; designatedSigner = _designatedSigner; emit SetDesignatedSigner(msg.sender, oldDesignatedSigner, _designatedSigner); } // Forwarding fns /** * @notice Tells whether the Agent app is a forwarder or not * @dev IForwarder interface conformance * @return Always true */ function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute the script as the Agent app * @dev IForwarder interface conformance. Forwards any token holder action. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = ""; // no input address[] memory blacklist = new address[](0); // no addr blacklist, can interact with anything runScript(_evmScript, input, blacklist); // We don't need to emit an event here as EVMScriptRunner will emit ScriptResult if successful } /** * @notice Tells whether `_sender` can forward actions or not * @dev IForwarder interface conformance * @param _sender Address of the account intending to forward an action * @return True if the given address can run scripts, false otherwise */ function canForward(address _sender, bytes _evmScript) public view returns (bool) { // Note that `canPerform()` implicitly does an initialization check itself return canPerform(_sender, RUN_SCRIPT_ROLE, arr(_getScriptACLParam(_evmScript))); } // ERC-165 conformance /** * @notice Tells whether this contract supports a given ERC-165 interface * @param _interfaceId Interface bytes to check * @return True if this contract supports the interface */ function supportsInterface(bytes4 _interfaceId) external pure returns (bool) { return _interfaceId == ERC1271_INTERFACE_ID || _interfaceId == ERC165_INTERFACE_ID; } // ERC-1271 conformance /** * @notice Tells whether a signature is seen as valid by this contract through ERC-1271 * @param _hash Arbitrary length data signed on the behalf of address (this) * @param _signature Signature byte array associated with _data * @return The ERC-1271 magic value if the signature is valid */ function isValidSignature(bytes32 _hash, bytes _signature) public view returns (bytes4) { // Short-circuit in case the hash was presigned. Optimization as performing calls // and ecrecover is more expensive than an SLOAD. if (isPresigned[_hash]) { return returnIsValidSignatureMagicNumber(true); } bool isValid; if (designatedSigner == address(0)) { isValid = false; } else { isValid = SignatureValidator.isValidSignature(_hash, designatedSigner, _signature); } return returnIsValidSignatureMagicNumber(isValid); } // Getters function getProtectedTokensLength() public view isInitialized returns (uint256) { return protectedTokens.length; } // Internal fns function _addProtectedToken(address _token) internal { protectedTokens.push(_token); emit AddProtectedToken(_token); } function _removeProtectedToken(address _token) internal { protectedTokens[_protectedTokenIndex(_token)] = protectedTokens[protectedTokens.length - 1]; protectedTokens.length--; emit RemoveProtectedToken(_token); } function _isERC20(address _token) internal view returns (bool) { if (!isContract(_token)) { return false; } // Throwaway sanity check to make sure the token's `balanceOf()` does not error (for now) balance(_token); return true; } function _protectedTokenIndex(address _token) internal view returns (uint256) { for (uint i = 0; i < protectedTokens.length; i++) { if (protectedTokens[i] == _token) { return i; } } revert(ERROR_TOKEN_NOT_PROTECTED); } function _tokenIsProtected(address _token) internal view returns (bool) { for (uint256 i = 0; i < protectedTokens.length; i++) { if (protectedTokens[i] == _token) { return true; } } return false; } function _getScriptACLParam(bytes _evmScript) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(_evmScript))); } function _getSig(bytes _data) internal pure returns (bytes4 sig) { if (_data.length < 4) { return; } assembly { sig := mload(add(_data, 0x20)) } } } // File: @aragon/os/contracts/lib/math/SafeMath.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted to use pragma ^0.4.24 and satisfy our linter rules pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b, ERROR_MUL_OVERFLOW); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // File: @aragon/os/contracts/lib/math/SafeMath64.sol // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted for uint64, pragma ^0.4.24, and satisfying our linter rules // Also optimized the mul() implementation, see https://github.com/aragon/aragonOS/pull/417 pragma solidity ^0.4.24; /** * @title SafeMath64 * @dev Math operations for uint64 with safety checks that revert on error */ library SafeMath64 { string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint64 _a, uint64 _b) internal pure returns (uint64) { uint256 c = uint256(_a) * uint256(_b); require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way) return uint64(c); } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint64 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint64 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint64 _a, uint64 _b) internal pure returns (uint64) { uint64 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // File: @aragon/apps-shared-minime/contracts/ITokenController.sol pragma solidity ^0.4.24; /// @dev The token controller contract must implement these functions interface ITokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) external payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) external returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) external returns(bool); } // File: @aragon/apps-shared-minime/contracts/MiniMeToken.sol pragma solidity ^0.4.24; /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } address public controller; function Controlled() public { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) onlyController public { controller = _newController; } } contract ApproveAndCallFallBack { function receiveApproval( address from, uint256 _amount, address _token, bytes _data ) public; } /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = "MMT_0.1"; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred function MiniMeToken( MiniMeTokenFactory _tokenFactory, MiniMeToken _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = _tokenFactory; name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = _parentToken; parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); return doTransfer(msg.sender, _to, _amount); } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality if (allowed[_from][msg.sender] < _amount) return false; allowed[_from][msg.sender] -= _amount; } return doTransfer(_from, _to, _amount); } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount) internal returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer returns false var previousBalanceFrom = balanceOfAt(_from, block.number); if (previousBalanceFrom < _amount) { return false; } // Alerts the token controller of the transfer if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onTransfer(_from, _to, _amount) == true); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens var previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); return true; } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender,0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onApprove(msg.sender, _spender, _amount) == true); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(ApproveAndCallFallBack _spender, uint256 _amount, bytes _extraData) public returns (bool success) { require(approve(_spender, _amount)); _spender.receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(MiniMeToken) { uint256 snapshot = _snapshotBlock == 0 ? block.number - 1 : _snapshotBlock; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, snapshot, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain NewCloneToken(address(cloneToken), snapshot); return cloneToken; } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) onlyController public { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () external payable { require(isContract(controller)); // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).proxyPayment.value(msg.value)(msg.sender) == true); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) onlyController public { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( MiniMeToken _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } // File: @aragon/apps-voting/contracts/Voting.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Voting is IForwarder, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; bytes32 public constant CREATE_VOTES_ROLE = keccak256("CREATE_VOTES_ROLE"); bytes32 public constant MODIFY_SUPPORT_ROLE = keccak256("MODIFY_SUPPORT_ROLE"); bytes32 public constant MODIFY_QUORUM_ROLE = keccak256("MODIFY_QUORUM_ROLE"); uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18 string private constant ERROR_NO_VOTE = "VOTING_NO_VOTE"; string private constant ERROR_INIT_PCTS = "VOTING_INIT_PCTS"; string private constant ERROR_CHANGE_SUPPORT_PCTS = "VOTING_CHANGE_SUPPORT_PCTS"; string private constant ERROR_CHANGE_QUORUM_PCTS = "VOTING_CHANGE_QUORUM_PCTS"; string private constant ERROR_INIT_SUPPORT_TOO_BIG = "VOTING_INIT_SUPPORT_TOO_BIG"; string private constant ERROR_CHANGE_SUPPORT_TOO_BIG = "VOTING_CHANGE_SUPP_TOO_BIG"; string private constant ERROR_CAN_NOT_VOTE = "VOTING_CAN_NOT_VOTE"; string private constant ERROR_CAN_NOT_EXECUTE = "VOTING_CAN_NOT_EXECUTE"; string private constant ERROR_CAN_NOT_FORWARD = "VOTING_CAN_NOT_FORWARD"; string private constant ERROR_NO_VOTING_POWER = "VOTING_NO_VOTING_POWER"; enum VoterState { Absent, Yea, Nay } struct Vote { bool executed; uint64 startDate; uint64 snapshotBlock; uint64 supportRequiredPct; uint64 minAcceptQuorumPct; uint256 yea; uint256 nay; uint256 votingPower; bytes executionScript; mapping (address => VoterState) voters; } MiniMeToken public token; uint64 public supportRequiredPct; uint64 public minAcceptQuorumPct; uint64 public voteTime; // We are mimicing an array, we use a mapping instead to make app upgrade more graceful mapping (uint256 => Vote) internal votes; uint256 public votesLength; event StartVote(uint256 indexed voteId, address indexed creator, string metadata); event CastVote(uint256 indexed voteId, address indexed voter, bool supports, uint256 stake); event ExecuteVote(uint256 indexed voteId); event ChangeSupportRequired(uint64 supportRequiredPct); event ChangeMinQuorum(uint64 minAcceptQuorumPct); modifier voteExists(uint256 _voteId) { require(_voteId < votesLength, ERROR_NO_VOTE); _; } /** * @notice Initialize Voting app with `_token.symbol(): string` for governance, minimum support of `@formatPct(_supportRequiredPct)`%, minimum acceptance quorum of `@formatPct(_minAcceptQuorumPct)`%, and a voting duration of `@transformTime(_voteTime)` * @param _token MiniMeToken Address that will be used as governance token * @param _supportRequiredPct Percentage of yeas in casted votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%) * @param _minAcceptQuorumPct Percentage of yeas in total possible votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%) * @param _voteTime Seconds that a vote will be open for token holders to vote (unless enough yeas or nays have been cast to make an early decision) */ function initialize( MiniMeToken _token, uint64 _supportRequiredPct, uint64 _minAcceptQuorumPct, uint64 _voteTime ) external onlyInit { initialized(); require(_minAcceptQuorumPct <= _supportRequiredPct, ERROR_INIT_PCTS); require(_supportRequiredPct < PCT_BASE, ERROR_INIT_SUPPORT_TOO_BIG); token = _token; supportRequiredPct = _supportRequiredPct; minAcceptQuorumPct = _minAcceptQuorumPct; voteTime = _voteTime; } /** * @notice Change required support to `@formatPct(_supportRequiredPct)`% * @param _supportRequiredPct New required support */ function changeSupportRequiredPct(uint64 _supportRequiredPct) external authP(MODIFY_SUPPORT_ROLE, arr(uint256(_supportRequiredPct), uint256(supportRequiredPct))) { require(minAcceptQuorumPct <= _supportRequiredPct, ERROR_CHANGE_SUPPORT_PCTS); require(_supportRequiredPct < PCT_BASE, ERROR_CHANGE_SUPPORT_TOO_BIG); supportRequiredPct = _supportRequiredPct; emit ChangeSupportRequired(_supportRequiredPct); } /** * @notice Change minimum acceptance quorum to `@formatPct(_minAcceptQuorumPct)`% * @param _minAcceptQuorumPct New acceptance quorum */ function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct) external authP(MODIFY_QUORUM_ROLE, arr(uint256(_minAcceptQuorumPct), uint256(minAcceptQuorumPct))) { require(_minAcceptQuorumPct <= supportRequiredPct, ERROR_CHANGE_QUORUM_PCTS); minAcceptQuorumPct = _minAcceptQuorumPct; emit ChangeMinQuorum(_minAcceptQuorumPct); } /** * @notice Create a new vote about "`_metadata`" * @param _executionScript EVM script to be executed on approval * @param _metadata Vote metadata * @return voteId Id for newly created vote */ function newVote(bytes _executionScript, string _metadata) external auth(CREATE_VOTES_ROLE) returns (uint256 voteId) { return _newVote(_executionScript, _metadata, true, true); } /** * @notice Create a new vote about "`_metadata`" * @param _executionScript EVM script to be executed on approval * @param _metadata Vote metadata * @param _castVote Whether to also cast newly created vote * @param _executesIfDecided Whether to also immediately execute newly created vote if decided * @return voteId id for newly created vote */ function newVote(bytes _executionScript, string _metadata, bool _castVote, bool _executesIfDecided) external auth(CREATE_VOTES_ROLE) returns (uint256 voteId) { return _newVote(_executionScript, _metadata, _castVote, _executesIfDecided); } /** * @notice Vote `_supports ? 'yes' : 'no'` in vote #`_voteId` * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @param _voteId Id for vote * @param _supports Whether voter supports the vote * @param _executesIfDecided Whether the vote should execute its action if it becomes decided */ function vote(uint256 _voteId, bool _supports, bool _executesIfDecided) external voteExists(_voteId) { require(_canVote(_voteId, msg.sender), ERROR_CAN_NOT_VOTE); _vote(_voteId, _supports, msg.sender, _executesIfDecided); } /** * @notice Execute vote #`_voteId` * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @param _voteId Id for vote */ function executeVote(uint256 _voteId) external voteExists(_voteId) { _executeVote(_voteId); } // Forwarding fns function isForwarder() external pure returns (bool) { return true; } /** * @notice Creates a vote to execute the desired action, and casts a support vote if possible * @dev IForwarder interface conformance * @param _evmScript Start vote with script */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); _newVote(_evmScript, "", true, true); } function canForward(address _sender, bytes) public view returns (bool) { // Note that `canPerform()` implicitly does an initialization check itself return canPerform(_sender, CREATE_VOTES_ROLE, arr()); } // Getter fns /** * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization */ function canExecute(uint256 _voteId) public view voteExists(_voteId) returns (bool) { return _canExecute(_voteId); } /** * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization */ function canVote(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (bool) { return _canVote(_voteId, _voter); } function getVote(uint256 _voteId) public view voteExists(_voteId) returns ( bool open, bool executed, uint64 startDate, uint64 snapshotBlock, uint64 supportRequired, uint64 minAcceptQuorum, uint256 yea, uint256 nay, uint256 votingPower, bytes script ) { Vote storage vote_ = votes[_voteId]; open = _isVoteOpen(vote_); executed = vote_.executed; startDate = vote_.startDate; snapshotBlock = vote_.snapshotBlock; supportRequired = vote_.supportRequiredPct; minAcceptQuorum = vote_.minAcceptQuorumPct; yea = vote_.yea; nay = vote_.nay; votingPower = vote_.votingPower; script = vote_.executionScript; } function getVoterState(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (VoterState) { return votes[_voteId].voters[_voter]; } // Internal fns function _newVote(bytes _executionScript, string _metadata, bool _castVote, bool _executesIfDecided) internal returns (uint256 voteId) { uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block uint256 votingPower = token.totalSupplyAt(snapshotBlock); require(votingPower > 0, ERROR_NO_VOTING_POWER); voteId = votesLength++; Vote storage vote_ = votes[voteId]; vote_.startDate = getTimestamp64(); vote_.snapshotBlock = snapshotBlock; vote_.supportRequiredPct = supportRequiredPct; vote_.minAcceptQuorumPct = minAcceptQuorumPct; vote_.votingPower = votingPower; vote_.executionScript = _executionScript; emit StartVote(voteId, msg.sender, _metadata); if (_castVote && _canVote(voteId, msg.sender)) { _vote(voteId, true, msg.sender, _executesIfDecided); } } function _vote( uint256 _voteId, bool _supports, address _voter, bool _executesIfDecided ) internal { Vote storage vote_ = votes[_voteId]; // This could re-enter, though we can assume the governance token is not malicious uint256 voterStake = token.balanceOfAt(_voter, vote_.snapshotBlock); VoterState state = vote_.voters[_voter]; // If voter had previously voted, decrease count if (state == VoterState.Yea) { vote_.yea = vote_.yea.sub(voterStake); } else if (state == VoterState.Nay) { vote_.nay = vote_.nay.sub(voterStake); } if (_supports) { vote_.yea = vote_.yea.add(voterStake); } else { vote_.nay = vote_.nay.add(voterStake); } vote_.voters[_voter] = _supports ? VoterState.Yea : VoterState.Nay; emit CastVote(_voteId, _voter, _supports, voterStake); if (_executesIfDecided && _canExecute(_voteId)) { // We've already checked if the vote can be executed with `_canExecute()` _unsafeExecuteVote(_voteId); } } function _executeVote(uint256 _voteId) internal { require(_canExecute(_voteId), ERROR_CAN_NOT_EXECUTE); _unsafeExecuteVote(_voteId); } /** * @dev Unsafe version of _executeVote that assumes you have already checked if the vote can be executed */ function _unsafeExecuteVote(uint256 _voteId) internal { Vote storage vote_ = votes[_voteId]; vote_.executed = true; bytes memory input = new bytes(0); // TODO: Consider input for voting scripts runScript(vote_.executionScript, input, new address[](0)); emit ExecuteVote(_voteId); } function _canExecute(uint256 _voteId) internal view returns (bool) { Vote storage vote_ = votes[_voteId]; if (vote_.executed) { return false; } // Voting is already decided if (_isValuePct(vote_.yea, vote_.votingPower, vote_.supportRequiredPct)) { return true; } // Vote ended? if (_isVoteOpen(vote_)) { return false; } // Has enough support? uint256 totalVotes = vote_.yea.add(vote_.nay); if (!_isValuePct(vote_.yea, totalVotes, vote_.supportRequiredPct)) { return false; } // Has min quorum? if (!_isValuePct(vote_.yea, vote_.votingPower, vote_.minAcceptQuorumPct)) { return false; } return true; } function _canVote(uint256 _voteId, address _voter) internal view returns (bool) { Vote storage vote_ = votes[_voteId]; return _isVoteOpen(vote_) && token.balanceOfAt(_voter, vote_.snapshotBlock) > 0; } function _isVoteOpen(Vote storage vote_) internal view returns (bool) { return getTimestamp64() < vote_.startDate.add(voteTime) && !vote_.executed; } /** * @dev Calculates whether `_value` is more than a percentage `_pct` of `_total` */ function _isValuePct(uint256 _value, uint256 _total, uint256 _pct) internal pure returns (bool) { if (_total == 0) { return false; } uint256 computedPct = _value.mul(PCT_BASE) / _total; return computedPct > _pct; } } // File: @aragon/ppf-contracts/contracts/IFeed.sol pragma solidity ^0.4.18; interface IFeed { function ratePrecision() external pure returns (uint256); function get(address base, address quote) external view returns (uint128 xrt, uint64 when); } // File: @aragon/apps-finance/contracts/Finance.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Finance is EtherTokenConstant, IsContract, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; using SafeERC20 for ERC20; bytes32 public constant CREATE_PAYMENTS_ROLE = keccak256("CREATE_PAYMENTS_ROLE"); bytes32 public constant CHANGE_PERIOD_ROLE = keccak256("CHANGE_PERIOD_ROLE"); bytes32 public constant CHANGE_BUDGETS_ROLE = keccak256("CHANGE_BUDGETS_ROLE"); bytes32 public constant EXECUTE_PAYMENTS_ROLE = keccak256("EXECUTE_PAYMENTS_ROLE"); bytes32 public constant MANAGE_PAYMENTS_ROLE = keccak256("MANAGE_PAYMENTS_ROLE"); uint256 internal constant NO_SCHEDULED_PAYMENT = 0; uint256 internal constant NO_TRANSACTION = 0; uint256 internal constant MAX_SCHEDULED_PAYMENTS_PER_TX = 20; uint256 internal constant MAX_UINT256 = uint256(-1); uint64 internal constant MAX_UINT64 = uint64(-1); uint64 internal constant MINIMUM_PERIOD = uint64(1 days); string private constant ERROR_COMPLETE_TRANSITION = "FINANCE_COMPLETE_TRANSITION"; string private constant ERROR_NO_SCHEDULED_PAYMENT = "FINANCE_NO_SCHEDULED_PAYMENT"; string private constant ERROR_NO_TRANSACTION = "FINANCE_NO_TRANSACTION"; string private constant ERROR_NO_PERIOD = "FINANCE_NO_PERIOD"; string private constant ERROR_VAULT_NOT_CONTRACT = "FINANCE_VAULT_NOT_CONTRACT"; string private constant ERROR_SET_PERIOD_TOO_SHORT = "FINANCE_SET_PERIOD_TOO_SHORT"; string private constant ERROR_NEW_PAYMENT_AMOUNT_ZERO = "FINANCE_NEW_PAYMENT_AMOUNT_ZERO"; string private constant ERROR_NEW_PAYMENT_INTERVAL_ZERO = "FINANCE_NEW_PAYMENT_INTRVL_ZERO"; string private constant ERROR_NEW_PAYMENT_EXECS_ZERO = "FINANCE_NEW_PAYMENT_EXECS_ZERO"; string private constant ERROR_NEW_PAYMENT_IMMEDIATE = "FINANCE_NEW_PAYMENT_IMMEDIATE"; string private constant ERROR_RECOVER_AMOUNT_ZERO = "FINANCE_RECOVER_AMOUNT_ZERO"; string private constant ERROR_DEPOSIT_AMOUNT_ZERO = "FINANCE_DEPOSIT_AMOUNT_ZERO"; string private constant ERROR_ETH_VALUE_MISMATCH = "FINANCE_ETH_VALUE_MISMATCH"; string private constant ERROR_BUDGET = "FINANCE_BUDGET"; string private constant ERROR_EXECUTE_PAYMENT_NUM = "FINANCE_EXECUTE_PAYMENT_NUM"; string private constant ERROR_EXECUTE_PAYMENT_TIME = "FINANCE_EXECUTE_PAYMENT_TIME"; string private constant ERROR_PAYMENT_RECEIVER = "FINANCE_PAYMENT_RECEIVER"; string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "FINANCE_TKN_TRANSFER_FROM_REVERT"; string private constant ERROR_TOKEN_APPROVE_FAILED = "FINANCE_TKN_APPROVE_FAILED"; string private constant ERROR_PAYMENT_INACTIVE = "FINANCE_PAYMENT_INACTIVE"; string private constant ERROR_REMAINING_BUDGET = "FINANCE_REMAINING_BUDGET"; // Order optimized for storage struct ScheduledPayment { address token; address receiver; address createdBy; bool inactive; uint256 amount; uint64 initialPaymentTime; uint64 interval; uint64 maxExecutions; uint64 executions; } // Order optimized for storage struct Transaction { address token; address entity; bool isIncoming; uint256 amount; uint256 paymentId; uint64 paymentExecutionNumber; uint64 date; uint64 periodId; } struct TokenStatement { uint256 expenses; uint256 income; } struct Period { uint64 startTime; uint64 endTime; uint256 firstTransactionId; uint256 lastTransactionId; mapping (address => TokenStatement) tokenStatement; } struct Settings { uint64 periodDuration; mapping (address => uint256) budgets; mapping (address => bool) hasBudget; } Vault public vault; Settings internal settings; // We are mimicing arrays, we use mappings instead to make app upgrade more graceful mapping (uint256 => ScheduledPayment) internal scheduledPayments; // Payments start at index 1, to allow us to use scheduledPayments[0] for transactions that are not // linked to a scheduled payment uint256 public paymentsNextIndex; mapping (uint256 => Transaction) internal transactions; uint256 public transactionsNextIndex; mapping (uint64 => Period) internal periods; uint64 public periodsLength; event NewPeriod(uint64 indexed periodId, uint64 periodStarts, uint64 periodEnds); event SetBudget(address indexed token, uint256 amount, bool hasBudget); event NewPayment(uint256 indexed paymentId, address indexed recipient, uint64 maxExecutions, string reference); event NewTransaction(uint256 indexed transactionId, bool incoming, address indexed entity, uint256 amount, string reference); event ChangePaymentState(uint256 indexed paymentId, bool active); event ChangePeriodDuration(uint64 newDuration); event PaymentFailure(uint256 paymentId); // Modifier used by all methods that impact accounting to make sure accounting period // is changed before the operation if needed // NOTE: its use **MUST** be accompanied by an initialization check modifier transitionsPeriod { bool completeTransition = _tryTransitionAccountingPeriod(getMaxPeriodTransitions()); require(completeTransition, ERROR_COMPLETE_TRANSITION); _; } modifier scheduledPaymentExists(uint256 _paymentId) { require(_paymentId > 0 && _paymentId < paymentsNextIndex, ERROR_NO_SCHEDULED_PAYMENT); _; } modifier transactionExists(uint256 _transactionId) { require(_transactionId > 0 && _transactionId < transactionsNextIndex, ERROR_NO_TRANSACTION); _; } modifier periodExists(uint64 _periodId) { require(_periodId < periodsLength, ERROR_NO_PERIOD); _; } /** * @notice Deposit ETH to the Vault, to avoid locking them in this Finance app forever * @dev Send ETH to Vault. Send all the available balance. */ function () external payable isInitialized transitionsPeriod { require(msg.value > 0, ERROR_DEPOSIT_AMOUNT_ZERO); _deposit( ETH, msg.value, "Ether transfer to Finance app", msg.sender, true ); } /** * @notice Initialize Finance app for Vault at `_vault` with period length of `@transformTime(_periodDuration)` * @param _vault Address of the vault Finance will rely on (non changeable) * @param _periodDuration Duration in seconds of each period */ function initialize(Vault _vault, uint64 _periodDuration) external onlyInit { initialized(); require(isContract(_vault), ERROR_VAULT_NOT_CONTRACT); vault = _vault; require(_periodDuration >= MINIMUM_PERIOD, ERROR_SET_PERIOD_TOO_SHORT); settings.periodDuration = _periodDuration; // Reserve the first scheduled payment index as an unused index for transactions not linked // to a scheduled payment scheduledPayments[0].inactive = true; paymentsNextIndex = 1; // Reserve the first transaction index as an unused index for periods with no transactions transactionsNextIndex = 1; // Start the first period _newPeriod(getTimestamp64()); } /** * @notice Deposit `@tokenAmount(_token, _amount)` * @dev Deposit for approved ERC20 tokens or ETH * @param _token Address of deposited token * @param _amount Amount of tokens sent * @param _reference Reason for payment */ function deposit(address _token, uint256 _amount, string _reference) external payable isInitialized transitionsPeriod { require(_amount > 0, ERROR_DEPOSIT_AMOUNT_ZERO); if (_token == ETH) { // Ensure that the ETH sent with the transaction equals the amount in the deposit require(msg.value == _amount, ERROR_ETH_VALUE_MISMATCH); } _deposit( _token, _amount, _reference, msg.sender, true ); } /** * @notice Create a new payment of `@tokenAmount(_token, _amount)` to `_receiver` for '`_reference`' * @dev Note that this function is protected by the `CREATE_PAYMENTS_ROLE` but uses `MAX_UINT256` * as its interval auth parameter (as a sentinel value for "never repeating"). * While this protects against most cases (you typically want to set a baseline requirement * for interval time), it does mean users will have to explicitly check for this case when * granting a permission that includes a upperbound requirement on the interval time. * @param _token Address of token for payment * @param _receiver Address that will receive payment * @param _amount Tokens that are paid every time the payment is due * @param _reference String detailing payment reason */ function newImmediatePayment(address _token, address _receiver, uint256 _amount, string _reference) external // Use MAX_UINT256 as the interval parameter, as this payment will never repeat // Payment time parameter is left as the last param as it was added later authP(CREATE_PAYMENTS_ROLE, _arr(_token, _receiver, _amount, MAX_UINT256, uint256(1), getTimestamp())) transitionsPeriod { require(_amount > 0, ERROR_NEW_PAYMENT_AMOUNT_ZERO); _makePaymentTransaction( _token, _receiver, _amount, NO_SCHEDULED_PAYMENT, // unrelated to any payment id; it isn't created 0, // also unrelated to any payment executions _reference ); } /** * @notice Create a new payment of `@tokenAmount(_token, _amount)` to `_receiver` for `_reference`, executing `_maxExecutions` times at intervals of `@transformTime(_interval)` * @dev See `newImmediatePayment()` for limitations on how the interval auth parameter can be used * @param _token Address of token for payment * @param _receiver Address that will receive payment * @param _amount Tokens that are paid every time the payment is due * @param _initialPaymentTime Timestamp for when the first payment is done * @param _interval Number of seconds that need to pass between payment transactions * @param _maxExecutions Maximum instances a payment can be executed * @param _reference String detailing payment reason */ function newScheduledPayment( address _token, address _receiver, uint256 _amount, uint64 _initialPaymentTime, uint64 _interval, uint64 _maxExecutions, string _reference ) external // Payment time parameter is left as the last param as it was added later authP(CREATE_PAYMENTS_ROLE, _arr(_token, _receiver, _amount, uint256(_interval), uint256(_maxExecutions), uint256(_initialPaymentTime))) transitionsPeriod returns (uint256 paymentId) { require(_amount > 0, ERROR_NEW_PAYMENT_AMOUNT_ZERO); require(_interval > 0, ERROR_NEW_PAYMENT_INTERVAL_ZERO); require(_maxExecutions > 0, ERROR_NEW_PAYMENT_EXECS_ZERO); // Token budget must not be set at all or allow at least one instance of this payment each period require(!settings.hasBudget[_token] || settings.budgets[_token] >= _amount, ERROR_BUDGET); // Don't allow creating single payments that are immediately executable, use `newImmediatePayment()` instead if (_maxExecutions == 1) { require(_initialPaymentTime > getTimestamp64(), ERROR_NEW_PAYMENT_IMMEDIATE); } paymentId = paymentsNextIndex++; emit NewPayment(paymentId, _receiver, _maxExecutions, _reference); ScheduledPayment storage payment = scheduledPayments[paymentId]; payment.token = _token; payment.receiver = _receiver; payment.amount = _amount; payment.initialPaymentTime = _initialPaymentTime; payment.interval = _interval; payment.maxExecutions = _maxExecutions; payment.createdBy = msg.sender; // We skip checking how many times the new payment was executed to allow creating new // scheduled payments before having enough vault balance _executePayment(paymentId); } /** * @notice Change period duration to `@transformTime(_periodDuration)`, effective for next accounting period * @param _periodDuration Duration in seconds for accounting periods */ function setPeriodDuration(uint64 _periodDuration) external authP(CHANGE_PERIOD_ROLE, arr(uint256(_periodDuration), uint256(settings.periodDuration))) transitionsPeriod { require(_periodDuration >= MINIMUM_PERIOD, ERROR_SET_PERIOD_TOO_SHORT); settings.periodDuration = _periodDuration; emit ChangePeriodDuration(_periodDuration); } /** * @notice Set budget for `_token.symbol(): string` to `@tokenAmount(_token, _amount, false)`, effective immediately * @param _token Address for token * @param _amount New budget amount */ function setBudget( address _token, uint256 _amount ) external authP(CHANGE_BUDGETS_ROLE, arr(_token, _amount, settings.budgets[_token], uint256(settings.hasBudget[_token] ? 1 : 0))) transitionsPeriod { settings.budgets[_token] = _amount; if (!settings.hasBudget[_token]) { settings.hasBudget[_token] = true; } emit SetBudget(_token, _amount, true); } /** * @notice Remove spending limit for `_token.symbol(): string`, effective immediately * @param _token Address for token */ function removeBudget(address _token) external authP(CHANGE_BUDGETS_ROLE, arr(_token, uint256(0), settings.budgets[_token], uint256(settings.hasBudget[_token] ? 1 : 0))) transitionsPeriod { settings.budgets[_token] = 0; settings.hasBudget[_token] = false; emit SetBudget(_token, 0, false); } /** * @notice Execute pending payment #`_paymentId` * @dev Executes any payment (requires role) * @param _paymentId Identifier for payment */ function executePayment(uint256 _paymentId) external authP(EXECUTE_PAYMENTS_ROLE, arr(_paymentId, scheduledPayments[_paymentId].amount)) scheduledPaymentExists(_paymentId) transitionsPeriod { _executePaymentAtLeastOnce(_paymentId); } /** * @notice Execute pending payment #`_paymentId` * @dev Always allow receiver of a payment to trigger execution * Initialization check is implicitly provided by `scheduledPaymentExists()` as new * scheduled payments can only be created via `newScheduledPayment(),` which requires initialization * @param _paymentId Identifier for payment */ function receiverExecutePayment(uint256 _paymentId) external scheduledPaymentExists(_paymentId) transitionsPeriod { require(scheduledPayments[_paymentId].receiver == msg.sender, ERROR_PAYMENT_RECEIVER); _executePaymentAtLeastOnce(_paymentId); } /** * @notice `_active ? 'Activate' : 'Disable'` payment #`_paymentId` * @dev Note that we do not require this action to transition periods, as it doesn't directly * impact any accounting periods. * Not having to transition periods also makes disabling payments easier to prevent funds * from being pulled out in the event of a breach. * @param _paymentId Identifier for payment * @param _active Whether it will be active or inactive */ function setPaymentStatus(uint256 _paymentId, bool _active) external authP(MANAGE_PAYMENTS_ROLE, arr(_paymentId, uint256(_active ? 1 : 0))) scheduledPaymentExists(_paymentId) { scheduledPayments[_paymentId].inactive = !_active; emit ChangePaymentState(_paymentId, _active); } /** * @notice Send tokens held in this contract to the Vault * @dev Allows making a simple payment from this contract to the Vault, to avoid locked tokens. * This contract should never receive tokens with a simple transfer call, but in case it * happens, this function allows for their recovery. * @param _token Token whose balance is going to be transferred. */ function recoverToVault(address _token) external isInitialized transitionsPeriod { uint256 amount = _token == ETH ? address(this).balance : ERC20(_token).staticBalanceOf(address(this)); require(amount > 0, ERROR_RECOVER_AMOUNT_ZERO); _deposit( _token, amount, "Recover to Vault", address(this), false ); } /** * @notice Transition accounting period if needed * @dev Transitions accounting periods if needed. For preventing OOG attacks, a maxTransitions * param is provided. If more than the specified number of periods need to be transitioned, * it will return false. * @param _maxTransitions Maximum periods that can be transitioned * @return success Boolean indicating whether the accounting period is the correct one (if false, * maxTransitions was surpased and another call is needed) */ function tryTransitionAccountingPeriod(uint64 _maxTransitions) external isInitialized returns (bool success) { return _tryTransitionAccountingPeriod(_maxTransitions); } // Getter fns /** * @dev Disable recovery escape hatch if the app has been initialized, as it could be used * maliciously to transfer funds in the Finance app to another Vault * finance#recoverToVault() should be used to recover funds to the Finance's vault */ function allowRecoverability(address) public view returns (bool) { return !hasInitialized(); } function getPayment(uint256 _paymentId) public view scheduledPaymentExists(_paymentId) returns ( address token, address receiver, uint256 amount, uint64 initialPaymentTime, uint64 interval, uint64 maxExecutions, bool inactive, uint64 executions, address createdBy ) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; token = payment.token; receiver = payment.receiver; amount = payment.amount; initialPaymentTime = payment.initialPaymentTime; interval = payment.interval; maxExecutions = payment.maxExecutions; executions = payment.executions; inactive = payment.inactive; createdBy = payment.createdBy; } function getTransaction(uint256 _transactionId) public view transactionExists(_transactionId) returns ( uint64 periodId, uint256 amount, uint256 paymentId, uint64 paymentExecutionNumber, address token, address entity, bool isIncoming, uint64 date ) { Transaction storage transaction = transactions[_transactionId]; token = transaction.token; entity = transaction.entity; isIncoming = transaction.isIncoming; date = transaction.date; periodId = transaction.periodId; amount = transaction.amount; paymentId = transaction.paymentId; paymentExecutionNumber = transaction.paymentExecutionNumber; } function getPeriod(uint64 _periodId) public view periodExists(_periodId) returns ( bool isCurrent, uint64 startTime, uint64 endTime, uint256 firstTransactionId, uint256 lastTransactionId ) { Period storage period = periods[_periodId]; isCurrent = _currentPeriodId() == _periodId; startTime = period.startTime; endTime = period.endTime; firstTransactionId = period.firstTransactionId; lastTransactionId = period.lastTransactionId; } function getPeriodTokenStatement(uint64 _periodId, address _token) public view periodExists(_periodId) returns (uint256 expenses, uint256 income) { TokenStatement storage tokenStatement = periods[_periodId].tokenStatement[_token]; expenses = tokenStatement.expenses; income = tokenStatement.income; } /** * @dev We have to check for initialization as periods are only valid after initializing */ function currentPeriodId() public view isInitialized returns (uint64) { return _currentPeriodId(); } /** * @dev We have to check for initialization as periods are only valid after initializing */ function getPeriodDuration() public view isInitialized returns (uint64) { return settings.periodDuration; } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function getBudget(address _token) public view isInitialized returns (uint256 budget, bool hasBudget) { budget = settings.budgets[_token]; hasBudget = settings.hasBudget[_token]; } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function getRemainingBudget(address _token) public view isInitialized returns (uint256) { return _getRemainingBudget(_token); } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function canMakePayment(address _token, uint256 _amount) public view isInitialized returns (bool) { return _canMakePayment(_token, _amount); } /** * @dev Initialization check is implicitly provided by `scheduledPaymentExists()` as new * scheduled payments can only be created via `newScheduledPayment(),` which requires initialization */ function nextPaymentTime(uint256 _paymentId) public view scheduledPaymentExists(_paymentId) returns (uint64) { return _nextPaymentTime(_paymentId); } // Internal fns function _deposit(address _token, uint256 _amount, string _reference, address _sender, bool _isExternalDeposit) internal { _recordIncomingTransaction( _token, _sender, _amount, _reference ); if (_token == ETH) { vault.deposit.value(_amount)(ETH, _amount); } else { // First, transfer the tokens to Finance if necessary // External deposit will be false when the assets were already in the Finance app // and just need to be transferred to the Vault if (_isExternalDeposit) { // This assumes the sender has approved the tokens for Finance require( ERC20(_token).safeTransferFrom(msg.sender, address(this), _amount), ERROR_TOKEN_TRANSFER_FROM_REVERTED ); } // Approve the tokens for the Vault (it does the actual transferring) require(ERC20(_token).safeApprove(vault, _amount), ERROR_TOKEN_APPROVE_FAILED); // Finally, initiate the deposit vault.deposit(_token, _amount); } } function _executePayment(uint256 _paymentId) internal returns (uint256) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; require(!payment.inactive, ERROR_PAYMENT_INACTIVE); uint64 paid = 0; while (_nextPaymentTime(_paymentId) <= getTimestamp64() && paid < MAX_SCHEDULED_PAYMENTS_PER_TX) { if (!_canMakePayment(payment.token, payment.amount)) { emit PaymentFailure(_paymentId); break; } // The while() predicate prevents these two from ever overflowing payment.executions += 1; paid += 1; // We've already checked the remaining budget with `_canMakePayment()` _unsafeMakePaymentTransaction( payment.token, payment.receiver, payment.amount, _paymentId, payment.executions, "" ); } return paid; } function _executePaymentAtLeastOnce(uint256 _paymentId) internal { uint256 paid = _executePayment(_paymentId); if (paid == 0) { if (_nextPaymentTime(_paymentId) <= getTimestamp64()) { revert(ERROR_EXECUTE_PAYMENT_NUM); } else { revert(ERROR_EXECUTE_PAYMENT_TIME); } } } function _makePaymentTransaction( address _token, address _receiver, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { require(_getRemainingBudget(_token) >= _amount, ERROR_REMAINING_BUDGET); _unsafeMakePaymentTransaction(_token, _receiver, _amount, _paymentId, _paymentExecutionNumber, _reference); } /** * @dev Unsafe version of _makePaymentTransaction that assumes you have already checked the * remaining budget */ function _unsafeMakePaymentTransaction( address _token, address _receiver, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { _recordTransaction( false, _token, _receiver, _amount, _paymentId, _paymentExecutionNumber, _reference ); vault.transfer(_token, _receiver, _amount); } function _newPeriod(uint64 _startTime) internal returns (Period storage) { // There should be no way for this to overflow since each period is at least one day uint64 newPeriodId = periodsLength++; Period storage period = periods[newPeriodId]; period.startTime = _startTime; // Be careful here to not overflow; if startTime + periodDuration overflows, we set endTime // to MAX_UINT64 (let's assume that's the end of time for now). uint64 endTime = _startTime + settings.periodDuration - 1; if (endTime < _startTime) { // overflowed endTime = MAX_UINT64; } period.endTime = endTime; emit NewPeriod(newPeriodId, period.startTime, period.endTime); return period; } function _recordIncomingTransaction( address _token, address _sender, uint256 _amount, string _reference ) internal { _recordTransaction( true, // incoming transaction _token, _sender, _amount, NO_SCHEDULED_PAYMENT, // unrelated to any existing payment 0, // and no payment executions _reference ); } function _recordTransaction( bool _incoming, address _token, address _entity, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { uint64 periodId = _currentPeriodId(); TokenStatement storage tokenStatement = periods[periodId].tokenStatement[_token]; if (_incoming) { tokenStatement.income = tokenStatement.income.add(_amount); } else { tokenStatement.expenses = tokenStatement.expenses.add(_amount); } uint256 transactionId = transactionsNextIndex++; Transaction storage transaction = transactions[transactionId]; transaction.token = _token; transaction.entity = _entity; transaction.isIncoming = _incoming; transaction.amount = _amount; transaction.paymentId = _paymentId; transaction.paymentExecutionNumber = _paymentExecutionNumber; transaction.date = getTimestamp64(); transaction.periodId = periodId; Period storage period = periods[periodId]; if (period.firstTransactionId == NO_TRANSACTION) { period.firstTransactionId = transactionId; } emit NewTransaction(transactionId, _incoming, _entity, _amount, _reference); } function _tryTransitionAccountingPeriod(uint64 _maxTransitions) internal returns (bool success) { Period storage currentPeriod = periods[_currentPeriodId()]; uint64 timestamp = getTimestamp64(); // Transition periods if necessary while (timestamp > currentPeriod.endTime) { if (_maxTransitions == 0) { // Required number of transitions is over allowed number, return false indicating // it didn't fully transition return false; } // We're already protected from underflowing above _maxTransitions -= 1; // If there were any transactions in period, record which was the last // In case 0 transactions occured, first and last tx id will be 0 if (currentPeriod.firstTransactionId != NO_TRANSACTION) { currentPeriod.lastTransactionId = transactionsNextIndex.sub(1); } // New period starts at end time + 1 currentPeriod = _newPeriod(currentPeriod.endTime.add(1)); } return true; } function _canMakePayment(address _token, uint256 _amount) internal view returns (bool) { return _getRemainingBudget(_token) >= _amount && vault.balance(_token) >= _amount; } function _currentPeriodId() internal view returns (uint64) { // There is no way for this to overflow if protected by an initialization check return periodsLength - 1; } function _getRemainingBudget(address _token) internal view returns (uint256) { if (!settings.hasBudget[_token]) { return MAX_UINT256; } uint256 budget = settings.budgets[_token]; uint256 spent = periods[_currentPeriodId()].tokenStatement[_token].expenses; // A budget decrease can cause the spent amount to be greater than period budget // If so, return 0 to not allow more spending during period if (spent >= budget) { return 0; } // We're already protected from the overflow above return budget - spent; } function _nextPaymentTime(uint256 _paymentId) internal view returns (uint64) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; if (payment.executions >= payment.maxExecutions) { return MAX_UINT64; // re-executes in some billions of years time... should not need to worry } // Split in multiple lines to circumvent linter warning uint64 increase = payment.executions.mul(payment.interval); uint64 nextPayment = payment.initialPaymentTime.add(increase); return nextPayment; } // Syntax sugar function _arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e, uint256 _f) internal pure returns (uint256[] r) { r = new uint256[](6); r[0] = uint256(_a); r[1] = uint256(_b); r[2] = _c; r[3] = _d; r[4] = _e; r[5] = _f; } // Mocked fns (overrided during testing) // Must be view for mocking purposes function getMaxPeriodTransitions() internal view returns (uint64) { return MAX_UINT64; } } // File: @aragon/apps-payroll/contracts/Payroll.sol pragma solidity 0.4.24; /** * @title Payroll in multiple currencies */ contract Payroll is EtherTokenConstant, IForwarder, IsContract, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; /* Hardcoded constants to save gas * bytes32 constant public ADD_EMPLOYEE_ROLE = keccak256("ADD_EMPLOYEE_ROLE"); * bytes32 constant public TERMINATE_EMPLOYEE_ROLE = keccak256("TERMINATE_EMPLOYEE_ROLE"); * bytes32 constant public SET_EMPLOYEE_SALARY_ROLE = keccak256("SET_EMPLOYEE_SALARY_ROLE"); * bytes32 constant public ADD_BONUS_ROLE = keccak256("ADD_BONUS_ROLE"); * bytes32 constant public ADD_REIMBURSEMENT_ROLE = keccak256("ADD_REIMBURSEMENT_ROLE"); * bytes32 constant public MANAGE_ALLOWED_TOKENS_ROLE = keccak256("MANAGE_ALLOWED_TOKENS_ROLE"); * bytes32 constant public MODIFY_PRICE_FEED_ROLE = keccak256("MODIFY_PRICE_FEED_ROLE"); * bytes32 constant public MODIFY_RATE_EXPIRY_ROLE = keccak256("MODIFY_RATE_EXPIRY_ROLE"); */ bytes32 constant public ADD_EMPLOYEE_ROLE = 0x9ecdc3c63716b45d0756eece5fe1614cae1889ec5a1ce62b3127c1f1f1615d6e; bytes32 constant public TERMINATE_EMPLOYEE_ROLE = 0x69c67f914d12b6440e7ddf01961214818d9158fbcb19211e0ff42800fdea9242; bytes32 constant public SET_EMPLOYEE_SALARY_ROLE = 0xea9ac65018da2421cf419ee2152371440c08267a193a33ccc1e39545d197e44d; bytes32 constant public ADD_BONUS_ROLE = 0xceca7e2f5eb749a87aaf68f3f76d6b9251aa2f4600f13f93c5a4adf7a72df4ae; bytes32 constant public ADD_REIMBURSEMENT_ROLE = 0x90698b9d54427f1e41636025017309bdb1b55320da960c8845bab0a504b01a16; bytes32 constant public MANAGE_ALLOWED_TOKENS_ROLE = 0x0be34987c45700ee3fae8c55e270418ba903337decc6bacb1879504be9331c06; bytes32 constant public MODIFY_PRICE_FEED_ROLE = 0x74350efbcba8b85341c5bbf70cc34e2a585fc1463524773a12fa0a71d4eb9302; bytes32 constant public MODIFY_RATE_EXPIRY_ROLE = 0x79fe989a8899060dfbdabb174ebb96616fa9f1d9dadd739f8d814cbab452404e; uint256 internal constant MAX_ALLOWED_TOKENS = 20; // prevent OOG issues with `payday()` uint64 internal constant MIN_RATE_EXPIRY = uint64(1 minutes); // 1 min == ~4 block window to mine both a price feed update and a payout uint256 internal constant MAX_UINT256 = uint256(-1); uint64 internal constant MAX_UINT64 = uint64(-1); string private constant ERROR_EMPLOYEE_DOESNT_EXIST = "PAYROLL_EMPLOYEE_DOESNT_EXIST"; string private constant ERROR_NON_ACTIVE_EMPLOYEE = "PAYROLL_NON_ACTIVE_EMPLOYEE"; string private constant ERROR_SENDER_DOES_NOT_MATCH = "PAYROLL_SENDER_DOES_NOT_MATCH"; string private constant ERROR_FINANCE_NOT_CONTRACT = "PAYROLL_FINANCE_NOT_CONTRACT"; string private constant ERROR_TOKEN_ALREADY_SET = "PAYROLL_TOKEN_ALREADY_SET"; string private constant ERROR_MAX_ALLOWED_TOKENS = "PAYROLL_MAX_ALLOWED_TOKENS"; string private constant ERROR_MIN_RATES_MISMATCH = "PAYROLL_MIN_RATES_MISMATCH"; string private constant ERROR_TOKEN_ALLOCATION_MISMATCH = "PAYROLL_TOKEN_ALLOCATION_MISMATCH"; string private constant ERROR_NOT_ALLOWED_TOKEN = "PAYROLL_NOT_ALLOWED_TOKEN"; string private constant ERROR_DISTRIBUTION_NOT_FULL = "PAYROLL_DISTRIBUTION_NOT_FULL"; string private constant ERROR_INVALID_PAYMENT_TYPE = "PAYROLL_INVALID_PAYMENT_TYPE"; string private constant ERROR_NOTHING_PAID = "PAYROLL_NOTHING_PAID"; string private constant ERROR_CAN_NOT_FORWARD = "PAYROLL_CAN_NOT_FORWARD"; string private constant ERROR_EMPLOYEE_NULL_ADDRESS = "PAYROLL_EMPLOYEE_NULL_ADDRESS"; string private constant ERROR_EMPLOYEE_ALREADY_EXIST = "PAYROLL_EMPLOYEE_ALREADY_EXIST"; string private constant ERROR_FEED_NOT_CONTRACT = "PAYROLL_FEED_NOT_CONTRACT"; string private constant ERROR_EXPIRY_TIME_TOO_SHORT = "PAYROLL_EXPIRY_TIME_TOO_SHORT"; string private constant ERROR_PAST_TERMINATION_DATE = "PAYROLL_PAST_TERMINATION_DATE"; string private constant ERROR_EXCHANGE_RATE_TOO_LOW = "PAYROLL_EXCHANGE_RATE_TOO_LOW"; string private constant ERROR_LAST_PAYROLL_DATE_TOO_BIG = "PAYROLL_LAST_DATE_TOO_BIG"; string private constant ERROR_INVALID_REQUESTED_AMOUNT = "PAYROLL_INVALID_REQUESTED_AMT"; enum PaymentType { Payroll, Reimbursement, Bonus } struct Employee { address accountAddress; // unique, but can be changed over time uint256 denominationTokenSalary; // salary per second in denomination Token uint256 accruedSalary; // keep track of any leftover accrued salary when changing salaries uint256 bonus; uint256 reimbursements; uint64 lastPayroll; uint64 endDate; address[] allocationTokenAddresses; mapping(address => uint256) allocationTokens; } Finance public finance; address public denominationToken; IFeed public feed; uint64 public rateExpiryTime; // Employees start at index 1, to allow us to use employees[0] to check for non-existent employees uint256 public nextEmployee; mapping(uint256 => Employee) internal employees; // employee ID -> employee mapping(address => uint256) internal employeeIds; // employee address -> employee ID mapping(address => bool) internal allowedTokens; event AddEmployee( uint256 indexed employeeId, address indexed accountAddress, uint256 initialDenominationSalary, uint64 startDate, string role ); event TerminateEmployee(uint256 indexed employeeId, uint64 endDate); event SetEmployeeSalary(uint256 indexed employeeId, uint256 denominationSalary); event AddEmployeeAccruedSalary(uint256 indexed employeeId, uint256 amount); event AddEmployeeBonus(uint256 indexed employeeId, uint256 amount); event AddEmployeeReimbursement(uint256 indexed employeeId, uint256 amount); event ChangeAddressByEmployee(uint256 indexed employeeId, address indexed newAccountAddress, address indexed oldAccountAddress); event DetermineAllocation(uint256 indexed employeeId); event SendPayment( uint256 indexed employeeId, address indexed accountAddress, address indexed token, uint256 amount, uint256 exchangeRate, string paymentReference ); event SetAllowedToken(address indexed token, bool allowed); event SetPriceFeed(address indexed feed); event SetRateExpiryTime(uint64 time); // Check employee exists by ID modifier employeeIdExists(uint256 _employeeId) { require(_employeeExists(_employeeId), ERROR_EMPLOYEE_DOESNT_EXIST); _; } // Check employee exists and is still active modifier employeeActive(uint256 _employeeId) { // No need to check for existence as _isEmployeeIdActive() is false for non-existent employees require(_isEmployeeIdActive(_employeeId), ERROR_NON_ACTIVE_EMPLOYEE); _; } // Check sender matches an existing employee modifier employeeMatches { require(employees[employeeIds[msg.sender]].accountAddress == msg.sender, ERROR_SENDER_DOES_NOT_MATCH); _; } /** * @notice Initialize Payroll app for Finance at `_finance` and price feed at `_priceFeed`, setting denomination token to `_token` and exchange rate expiry time to `@transformTime(_rateExpiryTime)` * @dev Note that we do not require _denominationToken to be a contract, as it may be a "fake" * address used by the price feed to denominate fiat currencies * @param _finance Address of the Finance app this Payroll app will rely on for payments (non-changeable) * @param _denominationToken Address of the denomination token used for salary accounting * @param _priceFeed Address of the price feed * @param _rateExpiryTime Acceptable expiry time in seconds for the price feed's exchange rates */ function initialize(Finance _finance, address _denominationToken, IFeed _priceFeed, uint64 _rateExpiryTime) external onlyInit { initialized(); require(isContract(_finance), ERROR_FINANCE_NOT_CONTRACT); finance = _finance; denominationToken = _denominationToken; _setPriceFeed(_priceFeed); _setRateExpiryTime(_rateExpiryTime); // Employees start at index 1, to allow us to use employees[0] to check for non-existent employees nextEmployee = 1; } /** * @notice `_allowed ? 'Add' : 'Remove'` `_token.symbol(): string` `_allowed ? 'to' : 'from'` the set of allowed tokens * @param _token Address of the token to be added or removed from the list of allowed tokens for payments * @param _allowed Boolean to tell whether the given token should be added or removed from the list */ function setAllowedToken(address _token, bool _allowed) external authP(MANAGE_ALLOWED_TOKENS_ROLE, arr(_token)) { require(allowedTokens[_token] != _allowed, ERROR_TOKEN_ALREADY_SET); allowedTokens[_token] = _allowed; emit SetAllowedToken(_token, _allowed); } /** * @notice Set the price feed for exchange rates to `_feed` * @param _feed Address of the new price feed instance */ function setPriceFeed(IFeed _feed) external authP(MODIFY_PRICE_FEED_ROLE, arr(_feed, feed)) { _setPriceFeed(_feed); } /** * @notice Set the acceptable expiry time for the price feed's exchange rates to `@transformTime(_time)` * @dev Exchange rates older than the given value won't be accepted for payments and will cause payouts to revert * @param _time The expiration time in seconds for exchange rates */ function setRateExpiryTime(uint64 _time) external authP(MODIFY_RATE_EXPIRY_ROLE, arr(uint256(_time), uint256(rateExpiryTime))) { _setRateExpiryTime(_time); } /** * @notice Add employee with address `_accountAddress` to payroll with an salary of `_initialDenominationSalary` per second, starting on `@formatDate(_startDate)` * @param _accountAddress Employee's address to receive payroll * @param _initialDenominationSalary Employee's salary, per second in denomination token * @param _startDate Employee's starting timestamp in seconds (it actually sets their initial lastPayroll value) * @param _role Employee's role */ function addEmployee(address _accountAddress, uint256 _initialDenominationSalary, uint64 _startDate, string _role) external authP(ADD_EMPLOYEE_ROLE, arr(_accountAddress, _initialDenominationSalary, uint256(_startDate))) { _addEmployee(_accountAddress, _initialDenominationSalary, _startDate, _role); } /** * @notice Add `_amount` to bonus for employee #`_employeeId` * @param _employeeId Employee's identifier * @param _amount Amount to be added to the employee's bonuses in denomination token */ function addBonus(uint256 _employeeId, uint256 _amount) external authP(ADD_BONUS_ROLE, arr(_employeeId, _amount)) employeeActive(_employeeId) { _addBonus(_employeeId, _amount); } /** * @notice Add `_amount` to reimbursements for employee #`_employeeId` * @param _employeeId Employee's identifier * @param _amount Amount to be added to the employee's reimbursements in denomination token */ function addReimbursement(uint256 _employeeId, uint256 _amount) external authP(ADD_REIMBURSEMENT_ROLE, arr(_employeeId, _amount)) employeeActive(_employeeId) { _addReimbursement(_employeeId, _amount); } /** * @notice Set employee #`_employeeId`'s salary to `_denominationSalary` per second * @dev This reverts if either the employee's owed salary or accrued salary overflows, to avoid * losing any accrued salary for an employee due to the employer changing their salary. * @param _employeeId Employee's identifier * @param _denominationSalary Employee's new salary, per second in denomination token */ function setEmployeeSalary(uint256 _employeeId, uint256 _denominationSalary) external authP(SET_EMPLOYEE_SALARY_ROLE, arr(_employeeId, _denominationSalary, employees[_employeeId].denominationTokenSalary)) employeeActive(_employeeId) { Employee storage employee = employees[_employeeId]; // Accrue employee's owed salary; don't cap to revert on overflow uint256 owed = _getOwedSalarySinceLastPayroll(employee, false); _addAccruedSalary(_employeeId, owed); // Update employee to track the new salary and payment date employee.lastPayroll = getTimestamp64(); employee.denominationTokenSalary = _denominationSalary; emit SetEmployeeSalary(_employeeId, _denominationSalary); } /** * @notice Terminate employee #`_employeeId` on `@formatDate(_endDate)` * @param _employeeId Employee's identifier * @param _endDate Termination timestamp in seconds */ function terminateEmployee(uint256 _employeeId, uint64 _endDate) external authP(TERMINATE_EMPLOYEE_ROLE, arr(_employeeId, uint256(_endDate))) employeeActive(_employeeId) { _terminateEmployee(_employeeId, _endDate); } /** * @notice Change your employee account address to `_newAccountAddress` * @dev Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _newAccountAddress New address to receive payments for the requesting employee */ function changeAddressByEmployee(address _newAccountAddress) external employeeMatches nonReentrant { uint256 employeeId = employeeIds[msg.sender]; address oldAddress = employees[employeeId].accountAddress; _setEmployeeAddress(employeeId, _newAccountAddress); // Don't delete the old address until after setting the new address to check that the // employee specified a new address delete employeeIds[oldAddress]; emit ChangeAddressByEmployee(employeeId, _newAccountAddress, oldAddress); } /** * @notice Set the token distribution for your payments * @dev Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _tokens Array of token addresses; they must belong to the list of allowed tokens * @param _distribution Array with each token's corresponding proportions (must be integers summing to 100) */ function determineAllocation(address[] _tokens, uint256[] _distribution) external employeeMatches nonReentrant { // Check array lengthes match require(_tokens.length <= MAX_ALLOWED_TOKENS, ERROR_MAX_ALLOWED_TOKENS); require(_tokens.length == _distribution.length, ERROR_TOKEN_ALLOCATION_MISMATCH); uint256 employeeId = employeeIds[msg.sender]; Employee storage employee = employees[employeeId]; // Delete previous token allocations address[] memory previousAllowedTokenAddresses = employee.allocationTokenAddresses; for (uint256 j = 0; j < previousAllowedTokenAddresses.length; j++) { delete employee.allocationTokens[previousAllowedTokenAddresses[j]]; } delete employee.allocationTokenAddresses; // Set distributions only if given tokens are allowed for (uint256 i = 0; i < _tokens.length; i++) { employee.allocationTokenAddresses.push(_tokens[i]); employee.allocationTokens[_tokens[i]] = _distribution[i]; } _ensureEmployeeTokenAllocationsIsValid(employee); emit DetermineAllocation(employeeId); } /** * @notice Request your `_type == 0 ? 'salary' : _type == 1 ? 'reimbursements' : 'bonus'` * @dev Reverts if no payments were made. * Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _type Payment type being requested (Payroll, Reimbursement or Bonus) * @param _requestedAmount Requested amount to pay for the payment type. Must be less than or equal to total owed amount for the payment type, or zero to request all. * @param _minRates Array of employee's minimum acceptable rates for their allowed payment tokens */ function payday(PaymentType _type, uint256 _requestedAmount, uint256[] _minRates) external employeeMatches nonReentrant { uint256 paymentAmount; uint256 employeeId = employeeIds[msg.sender]; Employee storage employee = employees[employeeId]; _ensureEmployeeTokenAllocationsIsValid(employee); require(_minRates.length == 0 || _minRates.length == employee.allocationTokenAddresses.length, ERROR_MIN_RATES_MISMATCH); // Do internal employee accounting if (_type == PaymentType.Payroll) { // Salary is capped here to avoid reverting at this point if it becomes too big // (so employees aren't DDOSed if their salaries get too large) // If we do use a capped value, the employee's lastPayroll date will be adjusted accordingly uint256 totalOwedSalary = _getTotalOwedCappedSalary(employee); paymentAmount = _ensurePaymentAmount(totalOwedSalary, _requestedAmount); _updateEmployeeAccountingBasedOnPaidSalary(employee, paymentAmount); } else if (_type == PaymentType.Reimbursement) { uint256 owedReimbursements = employee.reimbursements; paymentAmount = _ensurePaymentAmount(owedReimbursements, _requestedAmount); employee.reimbursements = owedReimbursements.sub(paymentAmount); } else if (_type == PaymentType.Bonus) { uint256 owedBonusAmount = employee.bonus; paymentAmount = _ensurePaymentAmount(owedBonusAmount, _requestedAmount); employee.bonus = owedBonusAmount.sub(paymentAmount); } else { revert(ERROR_INVALID_PAYMENT_TYPE); } // Actually transfer the owed funds require(_transferTokensAmount(employeeId, _type, paymentAmount, _minRates), ERROR_NOTHING_PAID); _removeEmployeeIfTerminatedAndPaidOut(employeeId); } // Forwarding fns /** * @dev IForwarder interface conformance. Tells whether the Payroll app is a forwarder or not. * @return Always true */ function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute desired action as an active employee * @dev IForwarder interface conformance. Allows active employees to run EVMScripts in the context of the Payroll app. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = new bytes(0); // TODO: Consider input for this // Add the Finance app to the blacklist to disallow employees from executing actions on the // Finance app from Payroll's context (since Payroll requires permissions on Finance) address[] memory blacklist = new address[](1); blacklist[0] = address(finance); runScript(_evmScript, input, blacklist); } /** * @dev IForwarder interface conformance. Tells whether a given address can forward actions or not. * @param _sender Address of the account intending to forward an action * @return True if the given address is an active employee, false otherwise */ function canForward(address _sender, bytes) public view returns (bool) { return _isEmployeeIdActive(employeeIds[_sender]); } // Getter fns /** * @dev Return employee's identifier by their account address * @param _accountAddress Employee's address to receive payments * @return Employee's identifier */ function getEmployeeIdByAddress(address _accountAddress) public view returns (uint256) { require(employeeIds[_accountAddress] != uint256(0), ERROR_EMPLOYEE_DOESNT_EXIST); return employeeIds[_accountAddress]; } /** * @dev Return all information for employee by their ID * @param _employeeId Employee's identifier * @return Employee's address to receive payments * @return Employee's salary, per second in denomination token * @return Employee's accrued salary * @return Employee's bonus amount * @return Employee's reimbursements amount * @return Employee's last payment date * @return Employee's termination date (max uint64 if none) * @return Employee's allowed payment tokens */ function getEmployee(uint256 _employeeId) public view employeeIdExists(_employeeId) returns ( address accountAddress, uint256 denominationSalary, uint256 accruedSalary, uint256 bonus, uint256 reimbursements, uint64 lastPayroll, uint64 endDate, address[] allocationTokens ) { Employee storage employee = employees[_employeeId]; accountAddress = employee.accountAddress; denominationSalary = employee.denominationTokenSalary; accruedSalary = employee.accruedSalary; bonus = employee.bonus; reimbursements = employee.reimbursements; lastPayroll = employee.lastPayroll; endDate = employee.endDate; allocationTokens = employee.allocationTokenAddresses; } /** * @dev Get owed salary since last payroll for an employee. It will take into account the accrued salary as well. * The result will be capped to max uint256 to avoid having an overflow. * @return Employee's total owed salary: current owed payroll since the last payroll date, plus the accrued salary. */ function getTotalOwedSalary(uint256 _employeeId) public view employeeIdExists(_employeeId) returns (uint256) { return _getTotalOwedCappedSalary(employees[_employeeId]); } /** * @dev Get an employee's payment allocation for a token * @param _employeeId Employee's identifier * @param _token Token to query the payment allocation for * @return Employee's payment allocation for the token being queried */ function getAllocation(uint256 _employeeId, address _token) public view employeeIdExists(_employeeId) returns (uint256) { return employees[_employeeId].allocationTokens[_token]; } /** * @dev Check if a token is allowed to be used for payments * @param _token Address of the token to be checked * @return True if the given token is allowed, false otherwise */ function isTokenAllowed(address _token) public view isInitialized returns (bool) { return allowedTokens[_token]; } // Internal fns /** * @dev Set the price feed used for exchange rates * @param _feed Address of the new price feed instance */ function _setPriceFeed(IFeed _feed) internal { require(isContract(_feed), ERROR_FEED_NOT_CONTRACT); feed = _feed; emit SetPriceFeed(feed); } /** * @dev Set the exchange rate expiry time in seconds. * Exchange rates older than the given value won't be accepted for payments and will cause * payouts to revert. * @param _time The expiration time in seconds for exchange rates */ function _setRateExpiryTime(uint64 _time) internal { // Require a sane minimum for the rate expiry time require(_time >= MIN_RATE_EXPIRY, ERROR_EXPIRY_TIME_TOO_SHORT); rateExpiryTime = _time; emit SetRateExpiryTime(rateExpiryTime); } /** * @dev Add a new employee to Payroll * @param _accountAddress Employee's address to receive payroll * @param _initialDenominationSalary Employee's salary, per second in denomination token * @param _startDate Employee's starting timestamp in seconds * @param _role Employee's role */ function _addEmployee(address _accountAddress, uint256 _initialDenominationSalary, uint64 _startDate, string _role) internal { uint256 employeeId = nextEmployee++; _setEmployeeAddress(employeeId, _accountAddress); Employee storage employee = employees[employeeId]; employee.denominationTokenSalary = _initialDenominationSalary; employee.lastPayroll = _startDate; employee.endDate = MAX_UINT64; emit AddEmployee(employeeId, _accountAddress, _initialDenominationSalary, _startDate, _role); } /** * @dev Add amount to an employee's bonuses * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's bonuses in denomination token */ function _addBonus(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.bonus = employee.bonus.add(_amount); emit AddEmployeeBonus(_employeeId, _amount); } /** * @dev Add amount to an employee's reimbursements * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's reimbursements in denomination token */ function _addReimbursement(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.reimbursements = employee.reimbursements.add(_amount); emit AddEmployeeReimbursement(_employeeId, _amount); } /** * @dev Add amount to an employee's accrued salary * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's accrued salary in denomination token */ function _addAccruedSalary(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.accruedSalary = employee.accruedSalary.add(_amount); emit AddEmployeeAccruedSalary(_employeeId, _amount); } /** * @dev Set an employee's account address * @param _employeeId Employee's identifier * @param _accountAddress Employee's address to receive payroll */ function _setEmployeeAddress(uint256 _employeeId, address _accountAddress) internal { // Check address is non-null require(_accountAddress != address(0), ERROR_EMPLOYEE_NULL_ADDRESS); // Check address isn't already being used require(employeeIds[_accountAddress] == uint256(0), ERROR_EMPLOYEE_ALREADY_EXIST); employees[_employeeId].accountAddress = _accountAddress; // Create IDs mapping employeeIds[_accountAddress] = _employeeId; } /** * @dev Terminate employee on end date * @param _employeeId Employee's identifier * @param _endDate Termination timestamp in seconds */ function _terminateEmployee(uint256 _employeeId, uint64 _endDate) internal { // Prevent past termination dates require(_endDate >= getTimestamp64(), ERROR_PAST_TERMINATION_DATE); employees[_employeeId].endDate = _endDate; emit TerminateEmployee(_employeeId, _endDate); } /** * @dev Loop over allowed tokens to send requested amount to the employee in their desired allocation * @param _employeeId Employee's identifier * @param _totalAmount Total amount to be transferred to the employee distributed in accordance to the employee's token allocation. * @param _type Payment type being transferred (Payroll, Reimbursement or Bonus) * @param _minRates Array of employee's minimum acceptable rates for their allowed payment tokens * @return True if there was at least one token transfer */ function _transferTokensAmount(uint256 _employeeId, PaymentType _type, uint256 _totalAmount, uint256[] _minRates) internal returns (bool somethingPaid) { if (_totalAmount == 0) { return false; } Employee storage employee = employees[_employeeId]; address employeeAddress = employee.accountAddress; string memory paymentReference = _paymentReferenceFor(_type); address[] storage allocationTokenAddresses = employee.allocationTokenAddresses; for (uint256 i = 0; i < allocationTokenAddresses.length; i++) { address token = allocationTokenAddresses[i]; uint256 tokenAllocation = employee.allocationTokens[token]; if (tokenAllocation != uint256(0)) { // Get the exchange rate for the payout token in denomination token, // as we do accounting in denomination tokens uint256 exchangeRate = _getExchangeRateInDenominationToken(token); require(_minRates.length > 0 ? exchangeRate >= _minRates[i] : exchangeRate > 0, ERROR_EXCHANGE_RATE_TOO_LOW); // Convert amount (in denomination tokens) to payout token and apply allocation uint256 tokenAmount = _totalAmount.mul(exchangeRate).mul(tokenAllocation); // Divide by 100 for the allocation percentage and by the exchange rate precision tokenAmount = tokenAmount.div(100).div(feed.ratePrecision()); // Finance reverts if the payment wasn't possible finance.newImmediatePayment(token, employeeAddress, tokenAmount, paymentReference); emit SendPayment(_employeeId, employeeAddress, token, tokenAmount, exchangeRate, paymentReference); somethingPaid = true; } } } /** * @dev Remove employee if there are no owed funds and employee's end date has been reached * @param _employeeId Employee's identifier */ function _removeEmployeeIfTerminatedAndPaidOut(uint256 _employeeId) internal { Employee storage employee = employees[_employeeId]; if ( employee.lastPayroll == employee.endDate && (employee.accruedSalary == 0 && employee.bonus == 0 && employee.reimbursements == 0) ) { delete employeeIds[employee.accountAddress]; delete employees[_employeeId]; } } /** * @dev Updates the accrued salary and payroll date of an employee based on a payment amount and * their currently owed salary since last payroll date * @param _employee Employee struct in storage * @param _paymentAmount Amount being paid to the employee */ function _updateEmployeeAccountingBasedOnPaidSalary(Employee storage _employee, uint256 _paymentAmount) internal { uint256 accruedSalary = _employee.accruedSalary; if (_paymentAmount <= accruedSalary) { // Employee is only cashing out some previously owed salary so we don't need to update // their last payroll date // No need to use SafeMath as we already know _paymentAmount <= accruedSalary _employee.accruedSalary = accruedSalary - _paymentAmount; return; } // Employee is cashing out some of their currently owed salary so their last payroll date // needs to be modified based on the amount of salary paid uint256 currentSalaryPaid = _paymentAmount; if (accruedSalary > 0) { // Employee is cashing out a mixed amount between previous and current owed salaries; // first use up their accrued salary // No need to use SafeMath here as we already know _paymentAmount > accruedSalary currentSalaryPaid = _paymentAmount - accruedSalary; // We finally need to clear their accrued salary _employee.accruedSalary = 0; } uint256 salary = _employee.denominationTokenSalary; uint256 timeDiff = currentSalaryPaid.div(salary); // If they're being paid an amount that doesn't match perfectly with the adjusted time // (up to a seconds' worth of salary), add the second and put the extra remaining salary // into their accrued salary uint256 extraSalary = currentSalaryPaid % salary; if (extraSalary > 0) { timeDiff = timeDiff.add(1); _employee.accruedSalary = salary - extraSalary; } uint256 lastPayrollDate = uint256(_employee.lastPayroll).add(timeDiff); // Even though this function should never receive a currentSalaryPaid value that would // result in the lastPayrollDate being higher than the current time, // let's double check to be safe require(lastPayrollDate <= uint256(getTimestamp64()), ERROR_LAST_PAYROLL_DATE_TOO_BIG); // Already know lastPayrollDate must fit in uint64 from above _employee.lastPayroll = uint64(lastPayrollDate); } /** * @dev Tell whether an employee is registered in this Payroll or not * @param _employeeId Employee's identifier * @return True if the given employee ID belongs to an registered employee, false otherwise */ function _employeeExists(uint256 _employeeId) internal view returns (bool) { return employees[_employeeId].accountAddress != address(0); } /** * @dev Tell whether an employee has a valid token allocation or not. * A valid allocation is one that sums to 100 and only includes allowed tokens. * @param _employee Employee struct in storage * @return Reverts if employee's allocation is invalid */ function _ensureEmployeeTokenAllocationsIsValid(Employee storage _employee) internal view { uint256 sum = 0; address[] memory allocationTokenAddresses = _employee.allocationTokenAddresses; for (uint256 i = 0; i < allocationTokenAddresses.length; i++) { address token = allocationTokenAddresses[i]; require(allowedTokens[token], ERROR_NOT_ALLOWED_TOKEN); sum = sum.add(_employee.allocationTokens[token]); } require(sum == 100, ERROR_DISTRIBUTION_NOT_FULL); } /** * @dev Tell whether an employee is still active or not * @param _employee Employee struct in storage * @return True if the employee exists and has an end date that has not been reached yet, false otherwise */ function _isEmployeeActive(Employee storage _employee) internal view returns (bool) { return _employee.endDate >= getTimestamp64(); } /** * @dev Tell whether an employee id is still active or not * @param _employeeId Employee's identifier * @return True if the employee exists and has an end date that has not been reached yet, false otherwise */ function _isEmployeeIdActive(uint256 _employeeId) internal view returns (bool) { return _isEmployeeActive(employees[_employeeId]); } /** * @dev Get exchange rate for a token based on the denomination token. * As an example, if the denomination token was USD and ETH's price was 100USD, * this would return 0.01 * precision rate for ETH. * @param _token Token to get price of in denomination tokens * @return Exchange rate (multiplied by the PPF rate precision) */ function _getExchangeRateInDenominationToken(address _token) internal view returns (uint256) { // xrt is the number of `_token` that can be exchanged for one `denominationToken` (uint128 xrt, uint64 when) = feed.get( denominationToken, // Base (e.g. USD) _token // Quote (e.g. ETH) ); // Check the price feed is recent enough if (getTimestamp64().sub(when) >= rateExpiryTime) { return 0; } return uint256(xrt); } /** * @dev Get owed salary since last payroll for an employee * @param _employee Employee struct in storage * @param _capped Safely cap the owed salary at max uint * @return Owed salary in denomination tokens since last payroll for the employee. * If _capped is false, it reverts in case of an overflow. */ function _getOwedSalarySinceLastPayroll(Employee storage _employee, bool _capped) internal view returns (uint256) { uint256 timeDiff = _getOwedPayrollPeriod(_employee); if (timeDiff == 0) { return 0; } uint256 salary = _employee.denominationTokenSalary; if (_capped) { // Return max uint if the result overflows uint256 result = salary * timeDiff; return (result / timeDiff != salary) ? MAX_UINT256 : result; } else { return salary.mul(timeDiff); } } /** * @dev Get owed payroll period for an employee * @param _employee Employee struct in storage * @return Owed time in seconds since the employee's last payroll date */ function _getOwedPayrollPeriod(Employee storage _employee) internal view returns (uint256) { // Get the min of current date and termination date uint64 date = _isEmployeeActive(_employee) ? getTimestamp64() : _employee.endDate; // Make sure we don't revert if we try to get the owed salary for an employee whose last // payroll date is now or in the future // This can happen either by adding new employees with start dates in the future, to allow // us to change their salary before their start date, or by terminating an employee and // paying out their full owed salary if (date <= _employee.lastPayroll) { return 0; } // Return time diff in seconds, no need to use SafeMath as the underflow was covered by the previous check return uint256(date - _employee.lastPayroll); } /** * @dev Get owed salary since last payroll for an employee. It will take into account the accrued salary as well. * The result will be capped to max uint256 to avoid having an overflow. * @param _employee Employee struct in storage * @return Employee's total owed salary: current owed payroll since the last payroll date, plus the accrued salary. */ function _getTotalOwedCappedSalary(Employee storage _employee) internal view returns (uint256) { uint256 currentOwedSalary = _getOwedSalarySinceLastPayroll(_employee, true); // cap amount uint256 totalOwedSalary = currentOwedSalary + _employee.accruedSalary; if (totalOwedSalary < currentOwedSalary) { totalOwedSalary = MAX_UINT256; } return totalOwedSalary; } /** * @dev Get payment reference for a given payment type * @param _type Payment type to query the reference of * @return Payment reference for the given payment type */ function _paymentReferenceFor(PaymentType _type) internal pure returns (string memory) { if (_type == PaymentType.Payroll) { return "Employee salary"; } else if (_type == PaymentType.Reimbursement) { return "Employee reimbursement"; } if (_type == PaymentType.Bonus) { return "Employee bonus"; } revert(ERROR_INVALID_PAYMENT_TYPE); } function _ensurePaymentAmount(uint256 _owedAmount, uint256 _requestedAmount) private pure returns (uint256) { require(_owedAmount > 0, ERROR_NOTHING_PAID); require(_owedAmount >= _requestedAmount, ERROR_INVALID_REQUESTED_AMOUNT); return _requestedAmount > 0 ? _requestedAmount : _owedAmount; } } // File: @aragon/apps-token-manager/contracts/TokenManager.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ /* solium-disable function-order */ pragma solidity 0.4.24; contract TokenManager is ITokenController, IForwarder, AragonApp { using SafeMath for uint256; bytes32 public constant MINT_ROLE = keccak256("MINT_ROLE"); bytes32 public constant ISSUE_ROLE = keccak256("ISSUE_ROLE"); bytes32 public constant ASSIGN_ROLE = keccak256("ASSIGN_ROLE"); bytes32 public constant REVOKE_VESTINGS_ROLE = keccak256("REVOKE_VESTINGS_ROLE"); bytes32 public constant BURN_ROLE = keccak256("BURN_ROLE"); uint256 public constant MAX_VESTINGS_PER_ADDRESS = 50; string private constant ERROR_CALLER_NOT_TOKEN = "TM_CALLER_NOT_TOKEN"; string private constant ERROR_NO_VESTING = "TM_NO_VESTING"; string private constant ERROR_TOKEN_CONTROLLER = "TM_TOKEN_CONTROLLER"; string private constant ERROR_MINT_RECEIVER_IS_TM = "TM_MINT_RECEIVER_IS_TM"; string private constant ERROR_VESTING_TO_TM = "TM_VESTING_TO_TM"; string private constant ERROR_TOO_MANY_VESTINGS = "TM_TOO_MANY_VESTINGS"; string private constant ERROR_WRONG_CLIFF_DATE = "TM_WRONG_CLIFF_DATE"; string private constant ERROR_VESTING_NOT_REVOKABLE = "TM_VESTING_NOT_REVOKABLE"; string private constant ERROR_REVOKE_TRANSFER_FROM_REVERTED = "TM_REVOKE_TRANSFER_FROM_REVERTED"; string private constant ERROR_CAN_NOT_FORWARD = "TM_CAN_NOT_FORWARD"; string private constant ERROR_BALANCE_INCREASE_NOT_ALLOWED = "TM_BALANCE_INC_NOT_ALLOWED"; string private constant ERROR_ASSIGN_TRANSFER_FROM_REVERTED = "TM_ASSIGN_TRANSFER_FROM_REVERTED"; struct TokenVesting { uint256 amount; uint64 start; uint64 cliff; uint64 vesting; bool revokable; } // Note that we COMPLETELY trust this MiniMeToken to not be malicious for proper operation of this contract MiniMeToken public token; uint256 public maxAccountTokens; // We are mimicing an array in the inner mapping, we use a mapping instead to make app upgrade more graceful mapping (address => mapping (uint256 => TokenVesting)) internal vestings; mapping (address => uint256) public vestingsLengths; // Other token specific events can be watched on the token address directly (avoids duplication) event NewVesting(address indexed receiver, uint256 vestingId, uint256 amount); event RevokeVesting(address indexed receiver, uint256 vestingId, uint256 nonVestedAmount); modifier onlyToken() { require(msg.sender == address(token), ERROR_CALLER_NOT_TOKEN); _; } modifier vestingExists(address _holder, uint256 _vestingId) { // TODO: it's not checking for gaps that may appear because of deletes in revokeVesting function require(_vestingId < vestingsLengths[_holder], ERROR_NO_VESTING); _; } /** * @notice Initialize Token Manager for `_token.symbol(): string`, whose tokens are `transferable ? 'not' : ''` transferable`_maxAccountTokens > 0 ? ' and limited to a maximum of ' + @tokenAmount(_token, _maxAccountTokens, false) + ' per account' : ''` * @param _token MiniMeToken address for the managed token (Token Manager instance must be already set as the token controller) * @param _transferable whether the token can be transferred by holders * @param _maxAccountTokens Maximum amount of tokens an account can have (0 for infinite tokens) */ function initialize( MiniMeToken _token, bool _transferable, uint256 _maxAccountTokens ) external onlyInit { initialized(); require(_token.controller() == address(this), ERROR_TOKEN_CONTROLLER); token = _token; maxAccountTokens = _maxAccountTokens == 0 ? uint256(-1) : _maxAccountTokens; if (token.transfersEnabled() != _transferable) { token.enableTransfers(_transferable); } } /** * @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for `_receiver` * @param _receiver The address receiving the tokens, cannot be the Token Manager itself (use `issue()` instead) * @param _amount Number of tokens minted */ function mint(address _receiver, uint256 _amount) external authP(MINT_ROLE, arr(_receiver, _amount)) { require(_receiver != address(this), ERROR_MINT_RECEIVER_IS_TM); _mint(_receiver, _amount); } /** * @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for the Token Manager * @param _amount Number of tokens minted */ function issue(uint256 _amount) external authP(ISSUE_ROLE, arr(_amount)) { _mint(address(this), _amount); } /** * @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings * @param _receiver The address receiving the tokens * @param _amount Number of tokens transferred */ function assign(address _receiver, uint256 _amount) external authP(ASSIGN_ROLE, arr(_receiver, _amount)) { _assign(_receiver, _amount); } /** * @notice Burn `@tokenAmount(self.token(): address, _amount, false)` tokens from `_holder` * @param _holder Holder of tokens being burned * @param _amount Number of tokens being burned */ function burn(address _holder, uint256 _amount) external authP(BURN_ROLE, arr(_holder, _amount)) { // minime.destroyTokens() never returns false, only reverts on failure token.destroyTokens(_holder, _amount); } /** * @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings with a `_revokable : 'revokable' : ''` vesting starting at `@formatDate(_start)`, cliff at `@formatDate(_cliff)` (first portion of tokens transferable), and completed vesting at `@formatDate(_vested)` (all tokens transferable) * @param _receiver The address receiving the tokens, cannot be Token Manager itself * @param _amount Number of tokens vested * @param _start Date the vesting calculations start * @param _cliff Date when the initial portion of tokens are transferable * @param _vested Date when all tokens are transferable * @param _revokable Whether the vesting can be revoked by the Token Manager */ function assignVested( address _receiver, uint256 _amount, uint64 _start, uint64 _cliff, uint64 _vested, bool _revokable ) external authP(ASSIGN_ROLE, arr(_receiver, _amount)) returns (uint256) { require(_receiver != address(this), ERROR_VESTING_TO_TM); require(vestingsLengths[_receiver] < MAX_VESTINGS_PER_ADDRESS, ERROR_TOO_MANY_VESTINGS); require(_start <= _cliff && _cliff <= _vested, ERROR_WRONG_CLIFF_DATE); uint256 vestingId = vestingsLengths[_receiver]++; vestings[_receiver][vestingId] = TokenVesting( _amount, _start, _cliff, _vested, _revokable ); _assign(_receiver, _amount); emit NewVesting(_receiver, vestingId, _amount); return vestingId; } /** * @notice Revoke vesting #`_vestingId` from `_holder`, returning unvested tokens to the Token Manager * @param _holder Address whose vesting to revoke * @param _vestingId Numeric id of the vesting */ function revokeVesting(address _holder, uint256 _vestingId) external authP(REVOKE_VESTINGS_ROLE, arr(_holder)) vestingExists(_holder, _vestingId) { TokenVesting storage v = vestings[_holder][_vestingId]; require(v.revokable, ERROR_VESTING_NOT_REVOKABLE); uint256 nonVested = _calculateNonVestedTokens( v.amount, getTimestamp(), v.start, v.cliff, v.vesting ); // To make vestingIds immutable over time, we just zero out the revoked vesting // Clearing this out also allows the token transfer back to the Token Manager to succeed delete vestings[_holder][_vestingId]; // transferFrom always works as controller // onTransfer hook always allows if transfering to token controller require(token.transferFrom(_holder, address(this), nonVested), ERROR_REVOKE_TRANSFER_FROM_REVERTED); emit RevokeVesting(_holder, _vestingId, nonVested); } // ITokenController fns // `onTransfer()`, `onApprove()`, and `proxyPayment()` are callbacks from the MiniMe token // contract and are only meant to be called through the managed MiniMe token that gets assigned // during initialization. /* * @dev Notifies the controller about a token transfer allowing the controller to decide whether * to allow it or react if desired (only callable from the token). * Initialization check is implicitly provided by `onlyToken()`. * @param _from The origin of the transfer * @param _to The destination of the transfer * @param _amount The amount of the transfer * @return False if the controller does not authorize the transfer */ function onTransfer(address _from, address _to, uint256 _amount) external onlyToken returns (bool) { return _isBalanceIncreaseAllowed(_to, _amount) && _transferableBalance(_from, getTimestamp()) >= _amount; } /** * @dev Notifies the controller about an approval allowing the controller to react if desired * Initialization check is implicitly provided by `onlyToken()`. * @return False if the controller does not authorize the approval */ function onApprove(address, address, uint) external onlyToken returns (bool) { return true; } /** * @dev Called when ether is sent to the MiniMe Token contract * Initialization check is implicitly provided by `onlyToken()`. * @return True if the ether is accepted, false for it to throw */ function proxyPayment(address) external payable onlyToken returns (bool) { return false; } // Forwarding fns function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute desired action as a token holder * @dev IForwarder interface conformance. Forwards any token holder action. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = new bytes(0); // TODO: Consider input for this // Add the managed token to the blacklist to disallow a token holder from executing actions // on the token controller's (this contract) behalf address[] memory blacklist = new address[](1); blacklist[0] = address(token); runScript(_evmScript, input, blacklist); } function canForward(address _sender, bytes) public view returns (bool) { return hasInitialized() && token.balanceOf(_sender) > 0; } // Getter fns function getVesting( address _recipient, uint256 _vestingId ) public view vestingExists(_recipient, _vestingId) returns ( uint256 amount, uint64 start, uint64 cliff, uint64 vesting, bool revokable ) { TokenVesting storage tokenVesting = vestings[_recipient][_vestingId]; amount = tokenVesting.amount; start = tokenVesting.start; cliff = tokenVesting.cliff; vesting = tokenVesting.vesting; revokable = tokenVesting.revokable; } function spendableBalanceOf(address _holder) public view isInitialized returns (uint256) { return _transferableBalance(_holder, getTimestamp()); } function transferableBalance(address _holder, uint256 _time) public view isInitialized returns (uint256) { return _transferableBalance(_holder, _time); } /** * @dev Disable recovery escape hatch for own token, * as the it has the concept of issuing tokens without assigning them */ function allowRecoverability(address _token) public view returns (bool) { return _token != address(token); } // Internal fns function _assign(address _receiver, uint256 _amount) internal { require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED); // Must use transferFrom() as transfer() does not give the token controller full control require(token.transferFrom(address(this), _receiver, _amount), ERROR_ASSIGN_TRANSFER_FROM_REVERTED); } function _mint(address _receiver, uint256 _amount) internal { require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED); token.generateTokens(_receiver, _amount); // minime.generateTokens() never returns false } function _isBalanceIncreaseAllowed(address _receiver, uint256 _inc) internal view returns (bool) { // Max balance doesn't apply to the token manager itself if (_receiver == address(this)) { return true; } return token.balanceOf(_receiver).add(_inc) <= maxAccountTokens; } /** * @dev Calculate amount of non-vested tokens at a specifc time * @param tokens The total amount of tokens vested * @param time The time at which to check * @param start The date vesting started * @param cliff The cliff period * @param vested The fully vested date * @return The amount of non-vested tokens of a specific grant * transferableTokens * | _/-------- vestedTokens rect * | _/ * | _/ * | _/ * | _/ * | / * | .| * | . | * | . | * | . | * | . | * | . | * +===+===========+---------+----------> time * Start Cliff Vested */ function _calculateNonVestedTokens( uint256 tokens, uint256 time, uint256 start, uint256 cliff, uint256 vested ) private pure returns (uint256) { // Shortcuts for before cliff and after vested cases. if (time >= vested) { return 0; } if (time < cliff) { return tokens; } // Interpolate all vested tokens. // As before cliff the shortcut returns 0, we can just calculate a value // in the vesting rect (as shown in above's figure) // vestedTokens = tokens * (time - start) / (vested - start) // In assignVesting we enforce start <= cliff <= vested // Here we shortcut time >= vested and time < cliff, // so no division by 0 is possible uint256 vestedTokens = tokens.mul(time.sub(start)) / vested.sub(start); // tokens - vestedTokens return tokens.sub(vestedTokens); } function _transferableBalance(address _holder, uint256 _time) internal view returns (uint256) { uint256 transferable = token.balanceOf(_holder); // This check is not strictly necessary for the current version of this contract, as // Token Managers now cannot assign vestings to themselves. // However, this was a possibility in the past, so in case there were vestings assigned to // themselves, this will still return the correct value (entire balance, as the Token // Manager does not have a spending limit on its own balance). if (_holder != address(this)) { uint256 vestingsCount = vestingsLengths[_holder]; for (uint256 i = 0; i < vestingsCount; i++) { TokenVesting storage v = vestings[_holder][i]; uint256 nonTransferable = _calculateNonVestedTokens( v.amount, _time, v.start, v.cliff, v.vesting ); transferable = transferable.sub(nonTransferable); } } return transferable; } } // File: @aragon/apps-survey/contracts/Survey.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Survey is AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; bytes32 public constant CREATE_SURVEYS_ROLE = keccak256("CREATE_SURVEYS_ROLE"); bytes32 public constant MODIFY_PARTICIPATION_ROLE = keccak256("MODIFY_PARTICIPATION_ROLE"); uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18 uint256 public constant ABSTAIN_VOTE = 0; string private constant ERROR_MIN_PARTICIPATION = "SURVEY_MIN_PARTICIPATION"; string private constant ERROR_NO_SURVEY = "SURVEY_NO_SURVEY"; string private constant ERROR_NO_VOTING_POWER = "SURVEY_NO_VOTING_POWER"; string private constant ERROR_CAN_NOT_VOTE = "SURVEY_CAN_NOT_VOTE"; string private constant ERROR_VOTE_WRONG_INPUT = "SURVEY_VOTE_WRONG_INPUT"; string private constant ERROR_VOTE_WRONG_OPTION = "SURVEY_VOTE_WRONG_OPTION"; string private constant ERROR_NO_STAKE = "SURVEY_NO_STAKE"; string private constant ERROR_OPTIONS_NOT_ORDERED = "SURVEY_OPTIONS_NOT_ORDERED"; string private constant ERROR_NO_OPTION = "SURVEY_NO_OPTION"; struct OptionCast { uint256 optionId; uint256 stake; } /* Allows for multiple option votes. * Index 0 is always used for the ABSTAIN_VOTE option, that's calculated automatically by the * contract. */ struct MultiOptionVote { uint256 optionsCastedLength; // `castedVotes` simulates an array // Each OptionCast in `castedVotes` must be ordered by ascending option IDs mapping (uint256 => OptionCast) castedVotes; } struct SurveyStruct { uint64 startDate; uint64 snapshotBlock; uint64 minParticipationPct; uint256 options; uint256 votingPower; // total tokens that can cast a vote uint256 participation; // tokens that casted a vote // Note that option IDs are from 1 to `options`, due to ABSTAIN_VOTE taking 0 mapping (uint256 => uint256) optionPower; // option ID -> voting power for option mapping (address => MultiOptionVote) votes; // voter -> options voted, with its stakes } MiniMeToken public token; uint64 public minParticipationPct; uint64 public surveyTime; // We are mimicing an array, we use a mapping instead to make app upgrade more graceful mapping (uint256 => SurveyStruct) internal surveys; uint256 public surveysLength; event StartSurvey(uint256 indexed surveyId, address indexed creator, string metadata); event CastVote(uint256 indexed surveyId, address indexed voter, uint256 option, uint256 stake, uint256 optionPower); event ResetVote(uint256 indexed surveyId, address indexed voter, uint256 option, uint256 previousStake, uint256 optionPower); event ChangeMinParticipation(uint64 minParticipationPct); modifier acceptableMinParticipationPct(uint64 _minParticipationPct) { require(_minParticipationPct > 0 && _minParticipationPct <= PCT_BASE, ERROR_MIN_PARTICIPATION); _; } modifier surveyExists(uint256 _surveyId) { require(_surveyId < surveysLength, ERROR_NO_SURVEY); _; } /** * @notice Initialize Survey app with `_token.symbol(): string` for governance, minimum acceptance participation of `@formatPct(_minParticipationPct)`%, and a voting duration of `@transformTime(_surveyTime)` * @param _token MiniMeToken address that will be used as governance token * @param _minParticipationPct Percentage of total voting power that must participate in a survey for it to be taken into account (expressed as a 10^18 percentage, (eg 10^16 = 1%, 10^18 = 100%) * @param _surveyTime Seconds that a survey will be open for token holders to vote */ function initialize( MiniMeToken _token, uint64 _minParticipationPct, uint64 _surveyTime ) external onlyInit acceptableMinParticipationPct(_minParticipationPct) { initialized(); token = _token; minParticipationPct = _minParticipationPct; surveyTime = _surveyTime; } /** * @notice Change minimum acceptance participation to `@formatPct(_minParticipationPct)`% * @param _minParticipationPct New acceptance participation */ function changeMinAcceptParticipationPct(uint64 _minParticipationPct) external authP(MODIFY_PARTICIPATION_ROLE, arr(uint256(_minParticipationPct), uint256(minParticipationPct))) acceptableMinParticipationPct(_minParticipationPct) { minParticipationPct = _minParticipationPct; emit ChangeMinParticipation(_minParticipationPct); } /** * @notice Create a new non-binding survey about "`_metadata`" * @param _metadata Survey metadata * @param _options Number of options voters can decide between * @return surveyId id for newly created survey */ function newSurvey(string _metadata, uint256 _options) external auth(CREATE_SURVEYS_ROLE) returns (uint256 surveyId) { uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block uint256 votingPower = token.totalSupplyAt(snapshotBlock); require(votingPower > 0, ERROR_NO_VOTING_POWER); surveyId = surveysLength++; SurveyStruct storage survey = surveys[surveyId]; survey.startDate = getTimestamp64(); survey.snapshotBlock = snapshotBlock; // avoid double voting in this very block survey.minParticipationPct = minParticipationPct; survey.options = _options; survey.votingPower = votingPower; emit StartSurvey(surveyId, msg.sender, _metadata); } /** * @notice Reset previously casted vote in survey #`_surveyId`, if any. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @param _surveyId Id for survey */ function resetVote(uint256 _surveyId) external surveyExists(_surveyId) { require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); _resetVote(_surveyId); } /** * @notice Vote for multiple options in survey #`_surveyId`. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @param _surveyId Id for survey * @param _optionIds Array with indexes of supported options * @param _stakes Number of tokens assigned to each option */ function voteOptions(uint256 _surveyId, uint256[] _optionIds, uint256[] _stakes) external surveyExists(_surveyId) { require(_optionIds.length == _stakes.length && _optionIds.length > 0, ERROR_VOTE_WRONG_INPUT); require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); _voteOptions(_surveyId, _optionIds, _stakes); } /** * @notice Vote option #`_optionId` in survey #`_surveyId`. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @dev It will use the whole balance. * @param _surveyId Id for survey * @param _optionId Index of supported option */ function voteOption(uint256 _surveyId, uint256 _optionId) external surveyExists(_surveyId) { require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); SurveyStruct storage survey = surveys[_surveyId]; // This could re-enter, though we can asume the governance token is not maliciuous uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); uint256[] memory options = new uint256[](1); uint256[] memory stakes = new uint256[](1); options[0] = _optionId; stakes[0] = voterStake; _voteOptions(_surveyId, options, stakes); } // Getter fns function canVote(uint256 _surveyId, address _voter) public view surveyExists(_surveyId) returns (bool) { SurveyStruct storage survey = surveys[_surveyId]; return _isSurveyOpen(survey) && token.balanceOfAt(_voter, survey.snapshotBlock) > 0; } function getSurvey(uint256 _surveyId) public view surveyExists(_surveyId) returns ( bool open, uint64 startDate, uint64 snapshotBlock, uint64 minParticipation, uint256 votingPower, uint256 participation, uint256 options ) { SurveyStruct storage survey = surveys[_surveyId]; open = _isSurveyOpen(survey); startDate = survey.startDate; snapshotBlock = survey.snapshotBlock; minParticipation = survey.minParticipationPct; votingPower = survey.votingPower; participation = survey.participation; options = survey.options; } /** * @dev This is not meant to be used on-chain */ /* solium-disable-next-line function-order */ function getVoterState(uint256 _surveyId, address _voter) external view surveyExists(_surveyId) returns (uint256[] options, uint256[] stakes) { MultiOptionVote storage vote = surveys[_surveyId].votes[_voter]; if (vote.optionsCastedLength == 0) { return (new uint256[](0), new uint256[](0)); } options = new uint256[](vote.optionsCastedLength + 1); stakes = new uint256[](vote.optionsCastedLength + 1); for (uint256 i = 0; i <= vote.optionsCastedLength; i++) { options[i] = vote.castedVotes[i].optionId; stakes[i] = vote.castedVotes[i].stake; } } function getOptionPower(uint256 _surveyId, uint256 _optionId) public view surveyExists(_surveyId) returns (uint256) { SurveyStruct storage survey = surveys[_surveyId]; require(_optionId <= survey.options, ERROR_NO_OPTION); return survey.optionPower[_optionId]; } function isParticipationAchieved(uint256 _surveyId) public view surveyExists(_surveyId) returns (bool) { SurveyStruct storage survey = surveys[_surveyId]; // votingPower is always > 0 uint256 participationPct = survey.participation.mul(PCT_BASE) / survey.votingPower; return participationPct >= survey.minParticipationPct; } // Internal fns /* * @dev Assumes the survey exists and that msg.sender can vote */ function _resetVote(uint256 _surveyId) internal { SurveyStruct storage survey = surveys[_surveyId]; MultiOptionVote storage previousVote = survey.votes[msg.sender]; if (previousVote.optionsCastedLength > 0) { // Voter removes their vote (index 0 is the abstain vote) for (uint256 i = 1; i <= previousVote.optionsCastedLength; i++) { OptionCast storage previousOptionCast = previousVote.castedVotes[i]; uint256 previousOptionPower = survey.optionPower[previousOptionCast.optionId]; uint256 currentOptionPower = previousOptionPower.sub(previousOptionCast.stake); survey.optionPower[previousOptionCast.optionId] = currentOptionPower; emit ResetVote(_surveyId, msg.sender, previousOptionCast.optionId, previousOptionCast.stake, currentOptionPower); } // Compute previously casted votes (i.e. substract non-used tokens from stake) uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); uint256 previousParticipation = voterStake.sub(previousVote.castedVotes[0].stake); // And remove it from total participation survey.participation = survey.participation.sub(previousParticipation); // Reset previously voted options delete survey.votes[msg.sender]; } } /* * @dev Assumes the survey exists and that msg.sender can vote */ function _voteOptions(uint256 _surveyId, uint256[] _optionIds, uint256[] _stakes) internal { SurveyStruct storage survey = surveys[_surveyId]; MultiOptionVote storage senderVotes = survey.votes[msg.sender]; // Revert previous votes, if any _resetVote(_surveyId); uint256 totalVoted = 0; // Reserve first index for ABSTAIN_VOTE senderVotes.castedVotes[0] = OptionCast({ optionId: ABSTAIN_VOTE, stake: 0 }); for (uint256 optionIndex = 1; optionIndex <= _optionIds.length; optionIndex++) { // Voters don't specify that they're abstaining, // but we still keep track of this by reserving the first index of a survey's votes. // We subtract 1 from the indexes of the arrays passed in by the voter to account for this. uint256 optionId = _optionIds[optionIndex - 1]; uint256 stake = _stakes[optionIndex - 1]; require(optionId != ABSTAIN_VOTE && optionId <= survey.options, ERROR_VOTE_WRONG_OPTION); require(stake > 0, ERROR_NO_STAKE); // Let's avoid repeating an option by making sure that ascending order is preserved in // the options array by checking that the current optionId is larger than the last one // we added require(senderVotes.castedVotes[optionIndex - 1].optionId < optionId, ERROR_OPTIONS_NOT_ORDERED); // Register voter amount senderVotes.castedVotes[optionIndex] = OptionCast({ optionId: optionId, stake: stake }); // Add to total option support survey.optionPower[optionId] = survey.optionPower[optionId].add(stake); // Keep track of stake used so far totalVoted = totalVoted.add(stake); emit CastVote(_surveyId, msg.sender, optionId, stake, survey.optionPower[optionId]); } // Compute and register non used tokens // Implictly we are doing require(totalVoted <= voterStake) too // (as stated before, index 0 is for ABSTAIN_VOTE option) uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); senderVotes.castedVotes[0].stake = voterStake.sub(totalVoted); // Register number of options voted senderVotes.optionsCastedLength = _optionIds.length; // Add voter tokens to participation survey.participation = survey.participation.add(totalVoted); assert(survey.participation <= survey.votingPower); } function _isSurveyOpen(SurveyStruct storage _survey) internal view returns (bool) { return getTimestamp64() < _survey.startDate.add(surveyTime); } } // File: @aragon/os/contracts/acl/IACLOracle.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IACLOracle { function canPerform(address who, address where, bytes32 what, uint256[] how) external view returns (bool); } // File: @aragon/os/contracts/acl/ACL.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract ACL is IACL, TimeHelpers, AragonApp, ACLHelpers { /* Hardcoded constants to save gas bytes32 public constant CREATE_PERMISSIONS_ROLE = keccak256("CREATE_PERMISSIONS_ROLE"); */ bytes32 public constant CREATE_PERMISSIONS_ROLE = 0x0b719b33c83b8e5d300c521cb8b54ae9bd933996a14bef8c2f4e0285d2d2400a; enum Op { NONE, EQ, NEQ, GT, LT, GTE, LTE, RET, NOT, AND, OR, XOR, IF_ELSE } // op types struct Param { uint8 id; uint8 op; uint240 value; // even though value is an uint240 it can store addresses // in the case of 32 byte hashes losing 2 bytes precision isn't a huge deal // op and id take less than 1 byte each so it can be kept in 1 sstore } uint8 internal constant BLOCK_NUMBER_PARAM_ID = 200; uint8 internal constant TIMESTAMP_PARAM_ID = 201; // 202 is unused uint8 internal constant ORACLE_PARAM_ID = 203; uint8 internal constant LOGIC_OP_PARAM_ID = 204; uint8 internal constant PARAM_VALUE_PARAM_ID = 205; // TODO: Add execution times param type? /* Hardcoded constant to save gas bytes32 public constant EMPTY_PARAM_HASH = keccak256(uint256(0)); */ bytes32 public constant EMPTY_PARAM_HASH = 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563; bytes32 public constant NO_PERMISSION = bytes32(0); address public constant ANY_ENTITY = address(-1); address public constant BURN_ENTITY = address(1); // address(0) is already used as "no permission manager" uint256 internal constant ORACLE_CHECK_GAS = 30000; string private constant ERROR_AUTH_INIT_KERNEL = "ACL_AUTH_INIT_KERNEL"; string private constant ERROR_AUTH_NO_MANAGER = "ACL_AUTH_NO_MANAGER"; string private constant ERROR_EXISTENT_MANAGER = "ACL_EXISTENT_MANAGER"; // Whether someone has a permission mapping (bytes32 => bytes32) internal permissions; // permissions hash => params hash mapping (bytes32 => Param[]) internal permissionParams; // params hash => params // Who is the manager of a permission mapping (bytes32 => address) internal permissionManager; event SetPermission(address indexed entity, address indexed app, bytes32 indexed role, bool allowed); event SetPermissionParams(address indexed entity, address indexed app, bytes32 indexed role, bytes32 paramsHash); event ChangePermissionManager(address indexed app, bytes32 indexed role, address indexed manager); modifier onlyPermissionManager(address _app, bytes32 _role) { require(msg.sender == getPermissionManager(_app, _role), ERROR_AUTH_NO_MANAGER); _; } modifier noPermissionManager(address _app, bytes32 _role) { // only allow permission creation (or re-creation) when there is no manager require(getPermissionManager(_app, _role) == address(0), ERROR_EXISTENT_MANAGER); _; } /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize an ACL instance and set `_permissionsCreator` as the entity that can create other permissions * @param _permissionsCreator Entity that will be given permission over createPermission */ function initialize(address _permissionsCreator) public onlyInit { initialized(); require(msg.sender == address(kernel()), ERROR_AUTH_INIT_KERNEL); _createPermission(_permissionsCreator, this, CREATE_PERMISSIONS_ROLE, _permissionsCreator); } /** * @dev Creates a permission that wasn't previously set and managed. * If a created permission is removed it is possible to reset it with createPermission. * This is the **ONLY** way to create permissions and set managers to permissions that don't * have a manager. * In terms of the ACL being initialized, this function implicitly protects all the other * state-changing external functions, as they all require the sender to be a manager. * @notice Create a new permission granting `_entity` the ability to perform actions requiring `_role` on `_app`, setting `_manager` as the permission's manager * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform * @param _manager Address of the entity that will be able to grant and revoke the permission further. */ function createPermission(address _entity, address _app, bytes32 _role, address _manager) external auth(CREATE_PERMISSIONS_ROLE) noPermissionManager(_app, _role) { _createPermission(_entity, _app, _role, _manager); } /** * @dev Grants permission if allowed. This requires `msg.sender` to be the permission manager * @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform */ function grantPermission(address _entity, address _app, bytes32 _role) external { grantPermissionP(_entity, _app, _role, new uint256[](0)); } /** * @dev Grants a permission with parameters if allowed. This requires `msg.sender` to be the permission manager * @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform * @param _params Permission parameters */ function grantPermissionP(address _entity, address _app, bytes32 _role, uint256[] _params) public onlyPermissionManager(_app, _role) { bytes32 paramsHash = _params.length > 0 ? _saveParams(_params) : EMPTY_PARAM_HASH; _setPermission(_entity, _app, _role, paramsHash); } /** * @dev Revokes permission if allowed. This requires `msg.sender` to be the the permission manager * @notice Revoke from `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity to revoke access from * @param _app Address of the app in which the role will be revoked * @param _role Identifier for the group of actions in app being revoked */ function revokePermission(address _entity, address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermission(_entity, _app, _role, NO_PERMISSION); } /** * @notice Set `_newManager` as the manager of `_role` in `_app` * @param _newManager Address for the new manager * @param _app Address of the app in which the permission management is being transferred * @param _role Identifier for the group of actions being transferred */ function setPermissionManager(address _newManager, address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(_newManager, _app, _role); } /** * @notice Remove the manager of `_role` in `_app` * @param _app Address of the app in which the permission is being unmanaged * @param _role Identifier for the group of actions being unmanaged */ function removePermissionManager(address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(address(0), _app, _role); } /** * @notice Burn non-existent `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager) * @param _app Address of the app in which the permission is being burned * @param _role Identifier for the group of actions being burned */ function createBurnedPermission(address _app, bytes32 _role) external auth(CREATE_PERMISSIONS_ROLE) noPermissionManager(_app, _role) { _setPermissionManager(BURN_ENTITY, _app, _role); } /** * @notice Burn `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager) * @param _app Address of the app in which the permission is being burned * @param _role Identifier for the group of actions being burned */ function burnPermissionManager(address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(BURN_ENTITY, _app, _role); } /** * @notice Get parameters for permission array length * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app * @param _role Identifier for a group of actions in app * @return Length of the array */ function getPermissionParamsLength(address _entity, address _app, bytes32 _role) external view returns (uint) { return permissionParams[permissions[permissionHash(_entity, _app, _role)]].length; } /** * @notice Get parameter for permission * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app * @param _role Identifier for a group of actions in app * @param _index Index of parameter in the array * @return Parameter (id, op, value) */ function getPermissionParam(address _entity, address _app, bytes32 _role, uint _index) external view returns (uint8, uint8, uint240) { Param storage param = permissionParams[permissions[permissionHash(_entity, _app, _role)]][_index]; return (param.id, param.op, param.value); } /** * @dev Get manager for permission * @param _app Address of the app * @param _role Identifier for a group of actions in app * @return address of the manager for the permission */ function getPermissionManager(address _app, bytes32 _role) public view returns (address) { return permissionManager[roleHash(_app, _role)]; } /** * @dev Function called by apps to check ACL on kernel or to check permission statu * @param _who Sender of the original call * @param _where Address of the app * @param _where Identifier for a group of actions in app * @param _how Permission parameters * @return boolean indicating whether the ACL allows the role or not */ function hasPermission(address _who, address _where, bytes32 _what, bytes memory _how) public view returns (bool) { return hasPermission(_who, _where, _what, ConversionHelpers.dangerouslyCastBytesToUintArray(_how)); } function hasPermission(address _who, address _where, bytes32 _what, uint256[] memory _how) public view returns (bool) { bytes32 whoParams = permissions[permissionHash(_who, _where, _what)]; if (whoParams != NO_PERMISSION && evalParams(whoParams, _who, _where, _what, _how)) { return true; } bytes32 anyParams = permissions[permissionHash(ANY_ENTITY, _where, _what)]; if (anyParams != NO_PERMISSION && evalParams(anyParams, ANY_ENTITY, _where, _what, _how)) { return true; } return false; } function hasPermission(address _who, address _where, bytes32 _what) public view returns (bool) { uint256[] memory empty = new uint256[](0); return hasPermission(_who, _where, _what, empty); } function evalParams( bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how ) public view returns (bool) { if (_paramsHash == EMPTY_PARAM_HASH) { return true; } return _evalParam(_paramsHash, 0, _who, _where, _what, _how); } /** * @dev Internal createPermission for access inside the kernel (on instantiation) */ function _createPermission(address _entity, address _app, bytes32 _role, address _manager) internal { _setPermission(_entity, _app, _role, EMPTY_PARAM_HASH); _setPermissionManager(_manager, _app, _role); } /** * @dev Internal function called to actually save the permission */ function _setPermission(address _entity, address _app, bytes32 _role, bytes32 _paramsHash) internal { permissions[permissionHash(_entity, _app, _role)] = _paramsHash; bool entityHasPermission = _paramsHash != NO_PERMISSION; bool permissionHasParams = entityHasPermission && _paramsHash != EMPTY_PARAM_HASH; emit SetPermission(_entity, _app, _role, entityHasPermission); if (permissionHasParams) { emit SetPermissionParams(_entity, _app, _role, _paramsHash); } } function _saveParams(uint256[] _encodedParams) internal returns (bytes32) { bytes32 paramHash = keccak256(abi.encodePacked(_encodedParams)); Param[] storage params = permissionParams[paramHash]; if (params.length == 0) { // params not saved before for (uint256 i = 0; i < _encodedParams.length; i++) { uint256 encodedParam = _encodedParams[i]; Param memory param = Param(decodeParamId(encodedParam), decodeParamOp(encodedParam), uint240(encodedParam)); params.push(param); } } return paramHash; } function _evalParam( bytes32 _paramsHash, uint32 _paramId, address _who, address _where, bytes32 _what, uint256[] _how ) internal view returns (bool) { if (_paramId >= permissionParams[_paramsHash].length) { return false; // out of bounds } Param memory param = permissionParams[_paramsHash][_paramId]; if (param.id == LOGIC_OP_PARAM_ID) { return _evalLogic(param, _paramsHash, _who, _where, _what, _how); } uint256 value; uint256 comparedTo = uint256(param.value); // get value if (param.id == ORACLE_PARAM_ID) { value = checkOracle(IACLOracle(param.value), _who, _where, _what, _how) ? 1 : 0; comparedTo = 1; } else if (param.id == BLOCK_NUMBER_PARAM_ID) { value = getBlockNumber(); } else if (param.id == TIMESTAMP_PARAM_ID) { value = getTimestamp(); } else if (param.id == PARAM_VALUE_PARAM_ID) { value = uint256(param.value); } else { if (param.id >= _how.length) { return false; } value = uint256(uint240(_how[param.id])); // force lost precision } if (Op(param.op) == Op.RET) { return uint256(value) > 0; } return compare(value, Op(param.op), comparedTo); } function _evalLogic(Param _param, bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) { if (Op(_param.op) == Op.IF_ELSE) { uint32 conditionParam; uint32 successParam; uint32 failureParam; (conditionParam, successParam, failureParam) = decodeParamsList(uint256(_param.value)); bool result = _evalParam(_paramsHash, conditionParam, _who, _where, _what, _how); return _evalParam(_paramsHash, result ? successParam : failureParam, _who, _where, _what, _how); } uint32 param1; uint32 param2; (param1, param2,) = decodeParamsList(uint256(_param.value)); bool r1 = _evalParam(_paramsHash, param1, _who, _where, _what, _how); if (Op(_param.op) == Op.NOT) { return !r1; } if (r1 && Op(_param.op) == Op.OR) { return true; } if (!r1 && Op(_param.op) == Op.AND) { return false; } bool r2 = _evalParam(_paramsHash, param2, _who, _where, _what, _how); if (Op(_param.op) == Op.XOR) { return r1 != r2; } return r2; // both or and and depend on result of r2 after checks } function compare(uint256 _a, Op _op, uint256 _b) internal pure returns (bool) { if (_op == Op.EQ) return _a == _b; // solium-disable-line lbrace if (_op == Op.NEQ) return _a != _b; // solium-disable-line lbrace if (_op == Op.GT) return _a > _b; // solium-disable-line lbrace if (_op == Op.LT) return _a < _b; // solium-disable-line lbrace if (_op == Op.GTE) return _a >= _b; // solium-disable-line lbrace if (_op == Op.LTE) return _a <= _b; // solium-disable-line lbrace return false; } function checkOracle(IACLOracle _oracleAddr, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) { bytes4 sig = _oracleAddr.canPerform.selector; // a raw call is required so we can return false if the call reverts, rather than reverting bytes memory checkCalldata = abi.encodeWithSelector(sig, _who, _where, _what, _how); uint256 oracleCheckGas = ORACLE_CHECK_GAS; bool ok; assembly { ok := staticcall(oracleCheckGas, _oracleAddr, add(checkCalldata, 0x20), mload(checkCalldata), 0, 0) } if (!ok) { return false; } uint256 size; assembly { size := returndatasize } if (size != 32) { return false; } bool result; assembly { let ptr := mload(0x40) // get next free memory ptr returndatacopy(ptr, 0, size) // copy return from above `staticcall` result := mload(ptr) // read data at ptr and set it to result mstore(ptr, 0) // set pointer memory to 0 so it still is the next free ptr } return result; } /** * @dev Internal function that sets management */ function _setPermissionManager(address _newManager, address _app, bytes32 _role) internal { permissionManager[roleHash(_app, _role)] = _newManager; emit ChangePermissionManager(_app, _role, _newManager); } function roleHash(address _where, bytes32 _what) internal pure returns (bytes32) { return keccak256(abi.encodePacked("ROLE", _where, _what)); } function permissionHash(address _who, address _where, bytes32 _what) internal pure returns (bytes32) { return keccak256(abi.encodePacked("PERMISSION", _who, _where, _what)); } } // File: @aragon/os/contracts/apm/Repo.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract Repo is AragonApp { /* Hardcoded constants to save gas bytes32 public constant CREATE_VERSION_ROLE = keccak256("CREATE_VERSION_ROLE"); */ bytes32 public constant CREATE_VERSION_ROLE = 0x1f56cfecd3595a2e6cc1a7e6cb0b20df84cdbd92eff2fee554e70e4e45a9a7d8; string private constant ERROR_INVALID_BUMP = "REPO_INVALID_BUMP"; string private constant ERROR_INVALID_VERSION = "REPO_INVALID_VERSION"; string private constant ERROR_INEXISTENT_VERSION = "REPO_INEXISTENT_VERSION"; struct Version { uint16[3] semanticVersion; address contractAddress; bytes contentURI; } uint256 internal versionsNextIndex; mapping (uint256 => Version) internal versions; mapping (bytes32 => uint256) internal versionIdForSemantic; mapping (address => uint256) internal latestVersionIdForContract; event NewVersion(uint256 versionId, uint16[3] semanticVersion); /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize this Repo */ function initialize() public onlyInit { initialized(); versionsNextIndex = 1; } /** * @notice Create new version with contract `_contractAddress` and content `@fromHex(_contentURI)` * @param _newSemanticVersion Semantic version for new repo version * @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress) * @param _contentURI External URI for fetching new version's content */ function newVersion( uint16[3] _newSemanticVersion, address _contractAddress, bytes _contentURI ) public auth(CREATE_VERSION_ROLE) { address contractAddress = _contractAddress; uint256 lastVersionIndex = versionsNextIndex - 1; uint16[3] memory lastSematicVersion; if (lastVersionIndex > 0) { Version storage lastVersion = versions[lastVersionIndex]; lastSematicVersion = lastVersion.semanticVersion; if (contractAddress == address(0)) { contractAddress = lastVersion.contractAddress; } // Only allows smart contract change on major version bumps require( lastVersion.contractAddress == contractAddress || _newSemanticVersion[0] > lastVersion.semanticVersion[0], ERROR_INVALID_VERSION ); } require(isValidBump(lastSematicVersion, _newSemanticVersion), ERROR_INVALID_BUMP); uint256 versionId = versionsNextIndex++; versions[versionId] = Version(_newSemanticVersion, contractAddress, _contentURI); versionIdForSemantic[semanticVersionHash(_newSemanticVersion)] = versionId; latestVersionIdForContract[contractAddress] = versionId; emit NewVersion(versionId, _newSemanticVersion); } function getLatest() public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(versionsNextIndex - 1); } function getLatestForContractAddress(address _contractAddress) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(latestVersionIdForContract[_contractAddress]); } function getBySemanticVersion(uint16[3] _semanticVersion) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(versionIdForSemantic[semanticVersionHash(_semanticVersion)]); } function getByVersionId(uint _versionId) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { require(_versionId > 0 && _versionId < versionsNextIndex, ERROR_INEXISTENT_VERSION); Version storage version = versions[_versionId]; return (version.semanticVersion, version.contractAddress, version.contentURI); } function getVersionsCount() public view returns (uint256) { return versionsNextIndex - 1; } function isValidBump(uint16[3] _oldVersion, uint16[3] _newVersion) public pure returns (bool) { bool hasBumped; uint i = 0; while (i < 3) { if (hasBumped) { if (_newVersion[i] != 0) { return false; } } else if (_newVersion[i] != _oldVersion[i]) { if (_oldVersion[i] > _newVersion[i] || _newVersion[i] - _oldVersion[i] != 1) { return false; } hasBumped = true; } i++; } return hasBumped; } function semanticVersionHash(uint16[3] version) internal pure returns (bytes32) { return keccak256(abi.encodePacked(version[0], version[1], version[2])); } } // File: @aragon/os/contracts/apm/APMNamehash.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract APMNamehash { /* Hardcoded constants to save gas bytes32 internal constant APM_NODE = keccak256(abi.encodePacked(ETH_TLD_NODE, keccak256(abi.encodePacked("aragonpm")))); */ bytes32 internal constant APM_NODE = 0x9065c3e7f7b7ef1ef4e53d2d0b8e0cef02874ab020c1ece79d5f0d3d0111c0ba; function apmNamehash(string name) internal pure returns (bytes32) { return keccak256(abi.encodePacked(APM_NODE, keccak256(bytes(name)))); } } // File: @aragon/os/contracts/kernel/KernelStorage.sol pragma solidity 0.4.24; contract KernelStorage { // namespace => app id => address mapping (bytes32 => mapping (bytes32 => address)) public apps; bytes32 public recoveryVaultAppId; } // File: @aragon/os/contracts/lib/misc/ERCProxy.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ERCProxy { uint256 internal constant FORWARDING = 1; uint256 internal constant UPGRADEABLE = 2; function proxyType() public pure returns (uint256 proxyTypeId); function implementation() public view returns (address codeAddr); } // File: @aragon/os/contracts/common/DelegateProxy.sol pragma solidity 0.4.24; contract DelegateProxy is ERCProxy, IsContract { uint256 internal constant FWD_GAS_LIMIT = 10000; /** * @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!) * @param _dst Destination address to perform the delegatecall * @param _calldata Calldata for the delegatecall */ function delegatedFwd(address _dst, bytes _calldata) internal { require(isContract(_dst)); uint256 fwdGasLimit = FWD_GAS_LIMIT; assembly { let result := delegatecall(sub(gas, fwdGasLimit), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } // File: @aragon/os/contracts/common/DepositableDelegateProxy.sol pragma solidity 0.4.24; contract DepositableDelegateProxy is DepositableStorage, DelegateProxy { event ProxyDeposit(address sender, uint256 value); function () external payable { // send / transfer if (gasleft() < FWD_GAS_LIMIT) { require(msg.value > 0 && msg.data.length == 0); require(isDepositable()); emit ProxyDeposit(msg.sender, msg.value); } else { // all calls except for send or transfer address target = implementation(); delegatedFwd(target, msg.data); } } } // File: @aragon/os/contracts/apps/AppProxyBase.sol pragma solidity 0.4.24; contract AppProxyBase is AppStorage, DepositableDelegateProxy, KernelNamespaceConstants { /** * @dev Initialize AppProxy * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public { setKernel(_kernel); setAppId(_appId); // Implicit check that kernel is actually a Kernel // The EVM doesn't actually provide a way for us to make sure, but we can force a revert to // occur if the kernel is set to 0x0 or a non-code address when we try to call a method on // it. address appCode = getAppBase(_appId); // If initialize payload is provided, it will be executed if (_initializePayload.length > 0) { require(isContract(appCode)); // Cannot make delegatecall as a delegateproxy.delegatedFwd as it // returns ending execution context and halts contract deployment require(appCode.delegatecall(_initializePayload)); } } function getAppBase(bytes32 _appId) internal view returns (address) { return kernel().getApp(KERNEL_APP_BASES_NAMESPACE, _appId); } } // File: @aragon/os/contracts/apps/AppProxyUpgradeable.sol pragma solidity 0.4.24; contract AppProxyUpgradeable is AppProxyBase { /** * @dev Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first { // solium-disable-previous-line no-empty-blocks } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return getAppBase(appId()); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return UPGRADEABLE; } } // File: @aragon/os/contracts/apps/AppProxyPinned.sol pragma solidity 0.4.24; contract AppProxyPinned is IsContract, AppProxyBase { using UnstructuredStorage for bytes32; // keccak256("aragonOS.appStorage.pinnedCode") bytes32 internal constant PINNED_CODE_POSITION = 0xdee64df20d65e53d7f51cb6ab6d921a0a6a638a91e942e1d8d02df28e31c038e; /** * @dev Initialize AppProxyPinned (makes it an un-upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first { setPinnedCode(getAppBase(_appId)); require(isContract(pinnedCode())); } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return pinnedCode(); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return FORWARDING; } function setPinnedCode(address _pinnedCode) internal { PINNED_CODE_POSITION.setStorageAddress(_pinnedCode); } function pinnedCode() internal view returns (address) { return PINNED_CODE_POSITION.getStorageAddress(); } } // File: @aragon/os/contracts/factory/AppProxyFactory.sol pragma solidity 0.4.24; contract AppProxyFactory { event NewAppProxy(address proxy, bool isUpgradeable, bytes32 appId); /** * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyUpgradeable */ function newAppProxy(IKernel _kernel, bytes32 _appId) public returns (AppProxyUpgradeable) { return newAppProxy(_kernel, _appId, new bytes(0)); } /** * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyUpgradeable */ function newAppProxy(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyUpgradeable) { AppProxyUpgradeable proxy = new AppProxyUpgradeable(_kernel, _appId, _initializePayload); emit NewAppProxy(address(proxy), true, _appId); return proxy; } /** * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyPinned */ function newAppProxyPinned(IKernel _kernel, bytes32 _appId) public returns (AppProxyPinned) { return newAppProxyPinned(_kernel, _appId, new bytes(0)); } /** * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @param _initializePayload Proxy initialization payload * @return AppProxyPinned */ function newAppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyPinned) { AppProxyPinned proxy = new AppProxyPinned(_kernel, _appId, _initializePayload); emit NewAppProxy(address(proxy), false, _appId); return proxy; } } // File: @aragon/os/contracts/kernel/Kernel.sol pragma solidity 0.4.24; // solium-disable-next-line max-len contract Kernel is IKernel, KernelStorage, KernelAppIds, KernelNamespaceConstants, Petrifiable, IsContract, VaultRecoverable, AppProxyFactory, ACLSyntaxSugar { /* Hardcoded constants to save gas bytes32 public constant APP_MANAGER_ROLE = keccak256("APP_MANAGER_ROLE"); */ bytes32 public constant APP_MANAGER_ROLE = 0xb6d92708f3d4817afc106147d969e229ced5c46e65e0a5002a0d391287762bd0; string private constant ERROR_APP_NOT_CONTRACT = "KERNEL_APP_NOT_CONTRACT"; string private constant ERROR_INVALID_APP_CHANGE = "KERNEL_INVALID_APP_CHANGE"; string private constant ERROR_AUTH_FAILED = "KERNEL_AUTH_FAILED"; /** * @dev Constructor that allows the deployer to choose if the base instance should be petrified immediately. * @param _shouldPetrify Immediately petrify this instance so that it can never be initialized */ constructor(bool _shouldPetrify) public { if (_shouldPetrify) { petrify(); } } /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize this kernel instance along with its ACL and set `_permissionsCreator` as the entity that can create other permissions * @param _baseAcl Address of base ACL app * @param _permissionsCreator Entity that will be given permission over createPermission */ function initialize(IACL _baseAcl, address _permissionsCreator) public onlyInit { initialized(); // Set ACL base _setApp(KERNEL_APP_BASES_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, _baseAcl); // Create ACL instance and attach it as the default ACL app IACL acl = IACL(newAppProxy(this, KERNEL_DEFAULT_ACL_APP_ID)); acl.initialize(_permissionsCreator); _setApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, acl); recoveryVaultAppId = KERNEL_DEFAULT_VAULT_APP_ID; } /** * @dev Create a new instance of an app linked to this kernel * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @return AppProxy instance */ function newAppInstance(bytes32 _appId, address _appBase) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { return newAppInstance(_appId, _appBase, new bytes(0), false); } /** * @dev Create a new instance of an app linked to this kernel and set its base * implementation if it was not already set * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @param _initializePayload Payload for call made by the proxy during its construction to initialize * @param _setDefault Whether the app proxy app is the default one. * Useful when the Kernel needs to know of an instance of a particular app, * like Vault for escape hatch mechanism. * @return AppProxy instance */ function newAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase); appProxy = newAppProxy(this, _appId, _initializePayload); // By calling setApp directly and not the internal functions, we make sure the params are checked // and it will only succeed if sender has permissions to set something to the namespace. if (_setDefault) { setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy); } } /** * @dev Create a new pinned instance of an app linked to this kernel * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @return AppProxy instance */ function newPinnedAppInstance(bytes32 _appId, address _appBase) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { return newPinnedAppInstance(_appId, _appBase, new bytes(0), false); } /** * @dev Create a new pinned instance of an app linked to this kernel and set * its base implementation if it was not already set * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @param _initializePayload Payload for call made by the proxy during its construction to initialize * @param _setDefault Whether the app proxy app is the default one. * Useful when the Kernel needs to know of an instance of a particular app, * like Vault for escape hatch mechanism. * @return AppProxy instance */ function newPinnedAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase); appProxy = newAppProxyPinned(this, _appId, _initializePayload); // By calling setApp directly and not the internal functions, we make sure the params are checked // and it will only succeed if sender has permissions to set something to the namespace. if (_setDefault) { setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy); } } /** * @dev Set the resolving address of an app instance or base implementation * @notice Set the resolving address of `_appId` in namespace `_namespace` to `_app` * @param _namespace App namespace to use * @param _appId Identifier for app * @param _app Address of the app instance or base implementation * @return ID of app */ function setApp(bytes32 _namespace, bytes32 _appId, address _app) public auth(APP_MANAGER_ROLE, arr(_namespace, _appId)) { _setApp(_namespace, _appId, _app); } /** * @dev Set the default vault id for the escape hatch mechanism * @param _recoveryVaultAppId Identifier of the recovery vault app */ function setRecoveryVaultAppId(bytes32 _recoveryVaultAppId) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_ADDR_NAMESPACE, _recoveryVaultAppId)) { recoveryVaultAppId = _recoveryVaultAppId; } // External access to default app id and namespace constants to mimic default getters for constants /* solium-disable function-order, mixedcase */ function CORE_NAMESPACE() external pure returns (bytes32) { return KERNEL_CORE_NAMESPACE; } function APP_BASES_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_BASES_NAMESPACE; } function APP_ADDR_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_ADDR_NAMESPACE; } function KERNEL_APP_ID() external pure returns (bytes32) { return KERNEL_CORE_APP_ID; } function DEFAULT_ACL_APP_ID() external pure returns (bytes32) { return KERNEL_DEFAULT_ACL_APP_ID; } /* solium-enable function-order, mixedcase */ /** * @dev Get the address of an app instance or base implementation * @param _namespace App namespace to use * @param _appId Identifier for app * @return Address of the app */ function getApp(bytes32 _namespace, bytes32 _appId) public view returns (address) { return apps[_namespace][_appId]; } /** * @dev Get the address of the recovery Vault instance (to recover funds) * @return Address of the Vault */ function getRecoveryVault() public view returns (address) { return apps[KERNEL_APP_ADDR_NAMESPACE][recoveryVaultAppId]; } /** * @dev Get the installed ACL app * @return ACL app */ function acl() public view returns (IACL) { return IACL(getApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID)); } /** * @dev Function called by apps to check ACL on kernel or to check permission status * @param _who Sender of the original call * @param _where Address of the app * @param _what Identifier for a group of actions in app * @param _how Extra data for ACL auth * @return Boolean indicating whether the ACL allows the role or not. * Always returns false if the kernel hasn't been initialized yet. */ function hasPermission(address _who, address _where, bytes32 _what, bytes _how) public view returns (bool) { IACL defaultAcl = acl(); return address(defaultAcl) != address(0) && // Poor man's initialization check (saves gas) defaultAcl.hasPermission(_who, _where, _what, _how); } function _setApp(bytes32 _namespace, bytes32 _appId, address _app) internal { require(isContract(_app), ERROR_APP_NOT_CONTRACT); apps[_namespace][_appId] = _app; emit SetApp(_namespace, _appId, _app); } function _setAppIfNew(bytes32 _namespace, bytes32 _appId, address _app) internal { address app = getApp(_namespace, _appId); if (app != address(0)) { // The only way to set an app is if it passes the isContract check, so no need to check it again require(app == _app, ERROR_INVALID_APP_CHANGE); } else { _setApp(_namespace, _appId, _app); } } modifier auth(bytes32 _role, uint256[] memory _params) { require( hasPermission(msg.sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)), ERROR_AUTH_FAILED ); _; } } // File: @aragon/os/contracts/lib/ens/AbstractENS.sol // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/AbstractENS.sol pragma solidity ^0.4.15; interface AbstractENS { function owner(bytes32 _node) public constant returns (address); function resolver(bytes32 _node) public constant returns (address); function ttl(bytes32 _node) public constant returns (uint64); function setOwner(bytes32 _node, address _owner) public; function setSubnodeOwner(bytes32 _node, bytes32 label, address _owner) public; function setResolver(bytes32 _node, address _resolver) public; function setTTL(bytes32 _node, uint64 _ttl) public; // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed _node, bytes32 indexed _label, address _owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed _node, address _owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed _node, address _resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed _node, uint64 _ttl); } // File: @aragon/os/contracts/lib/ens/ENS.sol // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/ENS.sol pragma solidity ^0.4.0; /** * The ENS registry contract. */ contract ENS is AbstractENS { struct Record { address owner; address resolver; uint64 ttl; } mapping(bytes32=>Record) records; // Permits modifications only by the owner of the specified node. modifier only_owner(bytes32 node) { if (records[node].owner != msg.sender) throw; _; } /** * Constructs a new ENS registrar. */ function ENS() public { records[0].owner = msg.sender; } /** * Returns the address that owns the specified node. */ function owner(bytes32 node) public constant returns (address) { return records[node].owner; } /** * Returns the address of the resolver for the specified node. */ function resolver(bytes32 node) public constant returns (address) { return records[node].resolver; } /** * Returns the TTL of a node, and any records associated with it. */ function ttl(bytes32 node) public constant returns (uint64) { return records[node].ttl; } /** * Transfers ownership of a node to a new address. May only be called by the current * owner of the node. * @param node The node to transfer ownership of. * @param owner The address of the new owner. */ function setOwner(bytes32 node, address owner) only_owner(node) public { Transfer(node, owner); records[node].owner = owner; } /** * Transfers ownership of a subnode keccak256(node, label) to a new address. May only be * called by the owner of the parent node. * @param node The parent node. * @param label The hash of the label specifying the subnode. * @param owner The address of the new owner. */ function setSubnodeOwner(bytes32 node, bytes32 label, address owner) only_owner(node) public { var subnode = keccak256(node, label); NewOwner(node, label, owner); records[subnode].owner = owner; } /** * Sets the resolver address for the specified node. * @param node The node to update. * @param resolver The address of the resolver. */ function setResolver(bytes32 node, address resolver) only_owner(node) public { NewResolver(node, resolver); records[node].resolver = resolver; } /** * Sets the TTL for the specified node. * @param node The node to update. * @param ttl The TTL in seconds. */ function setTTL(bytes32 node, uint64 ttl) only_owner(node) public { NewTTL(node, ttl); records[node].ttl = ttl; } } // File: @aragon/os/contracts/lib/ens/PublicResolver.sol // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/PublicResolver.sol pragma solidity ^0.4.0; /** * A simple resolver anyone can use; only allows the owner of a node to set its * address. */ contract PublicResolver { bytes4 constant INTERFACE_META_ID = 0x01ffc9a7; bytes4 constant ADDR_INTERFACE_ID = 0x3b3b57de; bytes4 constant CONTENT_INTERFACE_ID = 0xd8389dc5; bytes4 constant NAME_INTERFACE_ID = 0x691f3431; bytes4 constant ABI_INTERFACE_ID = 0x2203ab56; bytes4 constant PUBKEY_INTERFACE_ID = 0xc8690233; bytes4 constant TEXT_INTERFACE_ID = 0x59d1d43c; event AddrChanged(bytes32 indexed node, address a); event ContentChanged(bytes32 indexed node, bytes32 hash); event NameChanged(bytes32 indexed node, string name); event ABIChanged(bytes32 indexed node, uint256 indexed contentType); event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y); event TextChanged(bytes32 indexed node, string indexed indexedKey, string key); struct PublicKey { bytes32 x; bytes32 y; } struct Record { address addr; bytes32 content; string name; PublicKey pubkey; mapping(string=>string) text; mapping(uint256=>bytes) abis; } AbstractENS ens; mapping(bytes32=>Record) records; modifier only_owner(bytes32 node) { if (ens.owner(node) != msg.sender) throw; _; } /** * Constructor. * @param ensAddr The ENS registrar contract. */ function PublicResolver(AbstractENS ensAddr) public { ens = ensAddr; } /** * Returns true if the resolver implements the interface specified by the provided hash. * @param interfaceID The ID of the interface to check for. * @return True if the contract implements the requested interface. */ function supportsInterface(bytes4 interfaceID) public pure returns (bool) { return interfaceID == ADDR_INTERFACE_ID || interfaceID == CONTENT_INTERFACE_ID || interfaceID == NAME_INTERFACE_ID || interfaceID == ABI_INTERFACE_ID || interfaceID == PUBKEY_INTERFACE_ID || interfaceID == TEXT_INTERFACE_ID || interfaceID == INTERFACE_META_ID; } /** * Returns the address associated with an ENS node. * @param node The ENS node to query. * @return The associated address. */ function addr(bytes32 node) public constant returns (address ret) { ret = records[node].addr; } /** * Sets the address associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param addr The address to set. */ function setAddr(bytes32 node, address addr) only_owner(node) public { records[node].addr = addr; AddrChanged(node, addr); } /** * Returns the content hash associated with an ENS node. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The ENS node to query. * @return The associated content hash. */ function content(bytes32 node) public constant returns (bytes32 ret) { ret = records[node].content; } /** * Sets the content hash associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The node to update. * @param hash The content hash to set */ function setContent(bytes32 node, bytes32 hash) only_owner(node) public { records[node].content = hash; ContentChanged(node, hash); } /** * Returns the name associated with an ENS node, for reverse records. * Defined in EIP181. * @param node The ENS node to query. * @return The associated name. */ function name(bytes32 node) public constant returns (string ret) { ret = records[node].name; } /** * Sets the name associated with an ENS node, for reverse records. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param name The name to set. */ function setName(bytes32 node, string name) only_owner(node) public { records[node].name = name; NameChanged(node, name); } /** * Returns the ABI associated with an ENS node. * Defined in EIP205. * @param node The ENS node to query * @param contentTypes A bitwise OR of the ABI formats accepted by the caller. * @return contentType The content type of the return value * @return data The ABI data */ function ABI(bytes32 node, uint256 contentTypes) public constant returns (uint256 contentType, bytes data) { var record = records[node]; for(contentType = 1; contentType <= contentTypes; contentType <<= 1) { if ((contentType & contentTypes) != 0 && record.abis[contentType].length > 0) { data = record.abis[contentType]; return; } } contentType = 0; } /** * Sets the ABI associated with an ENS node. * Nodes may have one ABI of each content type. To remove an ABI, set it to * the empty string. * @param node The node to update. * @param contentType The content type of the ABI * @param data The ABI data. */ function setABI(bytes32 node, uint256 contentType, bytes data) only_owner(node) public { // Content types must be powers of 2 if (((contentType - 1) & contentType) != 0) throw; records[node].abis[contentType] = data; ABIChanged(node, contentType); } /** * Returns the SECP256k1 public key associated with an ENS node. * Defined in EIP 619. * @param node The ENS node to query * @return x, y the X and Y coordinates of the curve point for the public key. */ function pubkey(bytes32 node) public constant returns (bytes32 x, bytes32 y) { return (records[node].pubkey.x, records[node].pubkey.y); } /** * Sets the SECP256k1 public key associated with an ENS node. * @param node The ENS node to query * @param x the X coordinate of the curve point for the public key. * @param y the Y coordinate of the curve point for the public key. */ function setPubkey(bytes32 node, bytes32 x, bytes32 y) only_owner(node) public { records[node].pubkey = PublicKey(x, y); PubkeyChanged(node, x, y); } /** * Returns the text data associated with an ENS node and key. * @param node The ENS node to query. * @param key The text data key to query. * @return The associated text data. */ function text(bytes32 node, string key) public constant returns (string ret) { ret = records[node].text[key]; } /** * Sets the text data associated with an ENS node and key. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param key The key to set. * @param value The text data value to set. */ function setText(bytes32 node, string key, string value) only_owner(node) public { records[node].text[key] = value; TextChanged(node, key, key); } } // File: @aragon/os/contracts/kernel/KernelProxy.sol pragma solidity 0.4.24; contract KernelProxy is IKernelEvents, KernelStorage, KernelAppIds, KernelNamespaceConstants, IsContract, DepositableDelegateProxy { /** * @dev KernelProxy is a proxy contract to a kernel implementation. The implementation * can update the reference, which effectively upgrades the contract * @param _kernelImpl Address of the contract used as implementation for kernel */ constructor(IKernel _kernelImpl) public { require(isContract(address(_kernelImpl))); apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID] = _kernelImpl; // Note that emitting this event is important for verifying that a KernelProxy instance // was never upgraded to a malicious Kernel logic contract over its lifespan. // This starts the "chain of trust", that can be followed through later SetApp() events // emitted during kernel upgrades. emit SetApp(KERNEL_CORE_NAMESPACE, KERNEL_CORE_APP_ID, _kernelImpl); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return UPGRADEABLE; } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID]; } } // File: @aragon/os/contracts/evmscript/ScriptHelpers.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; library ScriptHelpers { function getSpecId(bytes _script) internal pure returns (uint32) { return uint32At(_script, 0); } function uint256At(bytes _data, uint256 _location) internal pure returns (uint256 result) { assembly { result := mload(add(_data, add(0x20, _location))) } } function addressAt(bytes _data, uint256 _location) internal pure returns (address result) { uint256 word = uint256At(_data, _location); assembly { result := div(and(word, 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000), 0x1000000000000000000000000) } } function uint32At(bytes _data, uint256 _location) internal pure returns (uint32 result) { uint256 word = uint256At(_data, _location); assembly { result := div(and(word, 0xffffffff00000000000000000000000000000000000000000000000000000000), 0x100000000000000000000000000000000000000000000000000000000) } } function locationOf(bytes _data, uint256 _location) internal pure returns (uint256 result) { assembly { result := add(_data, add(0x20, _location)) } } function toBytes(bytes4 _sig) internal pure returns (bytes) { bytes memory payload = new bytes(4); assembly { mstore(add(payload, 0x20), _sig) } return payload; } } // File: @aragon/os/contracts/evmscript/EVMScriptRegistry.sol pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract EVMScriptRegistry is IEVMScriptRegistry, EVMScriptRegistryConstants, AragonApp { using ScriptHelpers for bytes; /* Hardcoded constants to save gas bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = keccak256("REGISTRY_ADD_EXECUTOR_ROLE"); bytes32 public constant REGISTRY_MANAGER_ROLE = keccak256("REGISTRY_MANAGER_ROLE"); */ bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = 0xc4e90f38eea8c4212a009ca7b8947943ba4d4a58d19b683417f65291d1cd9ed2; // WARN: Manager can censor all votes and the like happening in an org bytes32 public constant REGISTRY_MANAGER_ROLE = 0xf7a450ef335e1892cb42c8ca72e7242359d7711924b75db5717410da3f614aa3; uint256 internal constant SCRIPT_START_LOCATION = 4; string private constant ERROR_INEXISTENT_EXECUTOR = "EVMREG_INEXISTENT_EXECUTOR"; string private constant ERROR_EXECUTOR_ENABLED = "EVMREG_EXECUTOR_ENABLED"; string private constant ERROR_EXECUTOR_DISABLED = "EVMREG_EXECUTOR_DISABLED"; string private constant ERROR_SCRIPT_LENGTH_TOO_SHORT = "EVMREG_SCRIPT_LENGTH_TOO_SHORT"; struct ExecutorEntry { IEVMScriptExecutor executor; bool enabled; } uint256 private executorsNextIndex; mapping (uint256 => ExecutorEntry) public executors; event EnableExecutor(uint256 indexed executorId, address indexed executorAddress); event DisableExecutor(uint256 indexed executorId, address indexed executorAddress); modifier executorExists(uint256 _executorId) { require(_executorId > 0 && _executorId < executorsNextIndex, ERROR_INEXISTENT_EXECUTOR); _; } /** * @notice Initialize the registry */ function initialize() public onlyInit { initialized(); // Create empty record to begin executor IDs at 1 executorsNextIndex = 1; } /** * @notice Add a new script executor with address `_executor` to the registry * @param _executor Address of the IEVMScriptExecutor that will be added to the registry * @return id Identifier of the executor in the registry */ function addScriptExecutor(IEVMScriptExecutor _executor) external auth(REGISTRY_ADD_EXECUTOR_ROLE) returns (uint256 id) { uint256 executorId = executorsNextIndex++; executors[executorId] = ExecutorEntry(_executor, true); emit EnableExecutor(executorId, _executor); return executorId; } /** * @notice Disable script executor with ID `_executorId` * @param _executorId Identifier of the executor in the registry */ function disableScriptExecutor(uint256 _executorId) external authP(REGISTRY_MANAGER_ROLE, arr(_executorId)) { // Note that we don't need to check for an executor's existence in this case, as only // existing executors can be enabled ExecutorEntry storage executorEntry = executors[_executorId]; require(executorEntry.enabled, ERROR_EXECUTOR_DISABLED); executorEntry.enabled = false; emit DisableExecutor(_executorId, executorEntry.executor); } /** * @notice Enable script executor with ID `_executorId` * @param _executorId Identifier of the executor in the registry */ function enableScriptExecutor(uint256 _executorId) external authP(REGISTRY_MANAGER_ROLE, arr(_executorId)) executorExists(_executorId) { ExecutorEntry storage executorEntry = executors[_executorId]; require(!executorEntry.enabled, ERROR_EXECUTOR_ENABLED); executorEntry.enabled = true; emit EnableExecutor(_executorId, executorEntry.executor); } /** * @dev Get the script executor that can execute a particular script based on its first 4 bytes * @param _script EVMScript being inspected */ function getScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { require(_script.length >= SCRIPT_START_LOCATION, ERROR_SCRIPT_LENGTH_TOO_SHORT); uint256 id = _script.getSpecId(); // Note that we don't need to check for an executor's existence in this case, as only // existing executors can be enabled ExecutorEntry storage entry = executors[id]; return entry.enabled ? entry.executor : IEVMScriptExecutor(0); } } // File: @aragon/os/contracts/evmscript/executors/BaseEVMScriptExecutor.sol /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract BaseEVMScriptExecutor is IEVMScriptExecutor, Autopetrified { uint256 internal constant SCRIPT_START_LOCATION = 4; } // File: @aragon/os/contracts/evmscript/executors/CallsScript.sol pragma solidity 0.4.24; // Inspired by https://github.com/reverendus/tx-manager contract CallsScript is BaseEVMScriptExecutor { using ScriptHelpers for bytes; /* Hardcoded constants to save gas bytes32 internal constant EXECUTOR_TYPE = keccak256("CALLS_SCRIPT"); */ bytes32 internal constant EXECUTOR_TYPE = 0x2dc858a00f3e417be1394b87c07158e989ec681ce8cc68a9093680ac1a870302; string private constant ERROR_BLACKLISTED_CALL = "EVMCALLS_BLACKLISTED_CALL"; string private constant ERROR_INVALID_LENGTH = "EVMCALLS_INVALID_LENGTH"; /* This is manually crafted in assembly string private constant ERROR_CALL_REVERTED = "EVMCALLS_CALL_REVERTED"; */ event LogScriptCall(address indexed sender, address indexed src, address indexed dst); /** * @notice Executes a number of call scripts * @param _script [ specId (uint32) ] many calls with this structure -> * [ to (address: 20 bytes) ] [ calldataLength (uint32: 4 bytes) ] [ calldata (calldataLength bytes) ] * @param _blacklist Addresses the script cannot call to, or will revert. * @return Always returns empty byte array */ function execScript(bytes _script, bytes, address[] _blacklist) external isInitialized returns (bytes) { uint256 location = SCRIPT_START_LOCATION; // first 32 bits are spec id while (location < _script.length) { // Check there's at least address + calldataLength available require(_script.length - location >= 0x18, ERROR_INVALID_LENGTH); address contractAddress = _script.addressAt(location); // Check address being called is not blacklist for (uint256 i = 0; i < _blacklist.length; i++) { require(contractAddress != _blacklist[i], ERROR_BLACKLISTED_CALL); } // logged before execution to ensure event ordering in receipt // if failed entire execution is reverted regardless emit LogScriptCall(msg.sender, address(this), contractAddress); uint256 calldataLength = uint256(_script.uint32At(location + 0x14)); uint256 startOffset = location + 0x14 + 0x04; uint256 calldataStart = _script.locationOf(startOffset); // compute end of script / next location location = startOffset + calldataLength; require(location <= _script.length, ERROR_INVALID_LENGTH); bool success; assembly { success := call( sub(gas, 5000), // forward gas left - 5000 contractAddress, // address 0, // no value calldataStart, // calldata start calldataLength, // calldata length 0, // don't write output 0 // don't write output ) switch success case 0 { let ptr := mload(0x40) switch returndatasize case 0 { // No error data was returned, revert with "EVMCALLS_CALL_REVERTED" // See remix: doing a `revert("EVMCALLS_CALL_REVERTED")` always results in // this memory layout mstore(ptr, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(ptr, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(ptr, 0x24), 0x0000000000000000000000000000000000000000000000000000000000000016) // reason length mstore(add(ptr, 0x44), 0x45564d43414c4c535f43414c4c5f524556455254454400000000000000000000) // reason revert(ptr, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Forward the full error data returndatacopy(ptr, 0, returndatasize) revert(ptr, returndatasize) } } default { } } } // No need to allocate empty bytes for the return as this can only be called via an delegatecall // (due to the isInitialized modifier) } function executorType() external pure returns (bytes32) { return EXECUTOR_TYPE; } } // File: @aragon/os/contracts/factory/EVMScriptRegistryFactory.sol pragma solidity 0.4.24; contract EVMScriptRegistryFactory is EVMScriptRegistryConstants { EVMScriptRegistry public baseReg; IEVMScriptExecutor public baseCallScript; /** * @notice Create a new EVMScriptRegistryFactory. */ constructor() public { baseReg = new EVMScriptRegistry(); baseCallScript = IEVMScriptExecutor(new CallsScript()); } /** * @notice Install a new pinned instance of EVMScriptRegistry on `_dao`. * @param _dao Kernel * @return Installed EVMScriptRegistry */ function newEVMScriptRegistry(Kernel _dao) public returns (EVMScriptRegistry reg) { bytes memory initPayload = abi.encodeWithSelector(reg.initialize.selector); reg = EVMScriptRegistry(_dao.newPinnedAppInstance(EVMSCRIPT_REGISTRY_APP_ID, baseReg, initPayload, true)); ACL acl = ACL(_dao.acl()); acl.createPermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE(), this); reg.addScriptExecutor(baseCallScript); // spec 1 = CallsScript // Clean up the permissions acl.revokePermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE()); acl.removePermissionManager(reg, reg.REGISTRY_ADD_EXECUTOR_ROLE()); return reg; } } // File: @aragon/os/contracts/factory/DAOFactory.sol pragma solidity 0.4.24; contract DAOFactory { IKernel public baseKernel; IACL public baseACL; EVMScriptRegistryFactory public regFactory; event DeployDAO(address dao); event DeployEVMScriptRegistry(address reg); /** * @notice Create a new DAOFactory, creating DAOs with Kernels proxied to `_baseKernel`, ACLs proxied to `_baseACL`, and new EVMScriptRegistries created from `_regFactory`. * @param _baseKernel Base Kernel * @param _baseACL Base ACL * @param _regFactory EVMScriptRegistry factory */ constructor(IKernel _baseKernel, IACL _baseACL, EVMScriptRegistryFactory _regFactory) public { // No need to init as it cannot be killed by devops199 if (address(_regFactory) != address(0)) { regFactory = _regFactory; } baseKernel = _baseKernel; baseACL = _baseACL; } /** * @notice Create a new DAO with `_root` set as the initial admin * @param _root Address that will be granted control to setup DAO permissions * @return Newly created DAO */ function newDAO(address _root) public returns (Kernel) { Kernel dao = Kernel(new KernelProxy(baseKernel)); if (address(regFactory) == address(0)) { dao.initialize(baseACL, _root); } else { dao.initialize(baseACL, this); ACL acl = ACL(dao.acl()); bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE(); bytes32 appManagerRole = dao.APP_MANAGER_ROLE(); acl.grantPermission(regFactory, acl, permRole); acl.createPermission(regFactory, dao, appManagerRole, this); EVMScriptRegistry reg = regFactory.newEVMScriptRegistry(dao); emit DeployEVMScriptRegistry(address(reg)); // Clean up permissions // First, completely reset the APP_MANAGER_ROLE acl.revokePermission(regFactory, dao, appManagerRole); acl.removePermissionManager(dao, appManagerRole); // Then, make root the only holder and manager of CREATE_PERMISSIONS_ROLE acl.revokePermission(regFactory, acl, permRole); acl.revokePermission(this, acl, permRole); acl.grantPermission(_root, acl, permRole); acl.setPermissionManager(_root, acl, permRole); } emit DeployDAO(address(dao)); return dao; } } // File: @aragon/id/contracts/ens/IPublicResolver.sol pragma solidity ^0.4.0; interface IPublicResolver { function supportsInterface(bytes4 interfaceID) constant returns (bool); function addr(bytes32 node) constant returns (address ret); function setAddr(bytes32 node, address addr); function hash(bytes32 node) constant returns (bytes32 ret); function setHash(bytes32 node, bytes32 hash); } // File: @aragon/id/contracts/IFIFSResolvingRegistrar.sol pragma solidity 0.4.24; interface IFIFSResolvingRegistrar { function register(bytes32 _subnode, address _owner) external; function registerWithResolver(bytes32 _subnode, address _owner, IPublicResolver _resolver) public; } // File: @aragon/templates-shared/contracts/BaseTemplate.sol pragma solidity 0.4.24; contract BaseTemplate is APMNamehash, IsContract { using Uint256Helpers for uint256; /* Hardcoded constant to save gas * bytes32 constant internal AGENT_APP_ID = apmNamehash("agent"); // agent.aragonpm.eth * bytes32 constant internal VAULT_APP_ID = apmNamehash("vault"); // vault.aragonpm.eth * bytes32 constant internal VOTING_APP_ID = apmNamehash("voting"); // voting.aragonpm.eth * bytes32 constant internal SURVEY_APP_ID = apmNamehash("survey"); // survey.aragonpm.eth * bytes32 constant internal PAYROLL_APP_ID = apmNamehash("payroll"); // payroll.aragonpm.eth * bytes32 constant internal FINANCE_APP_ID = apmNamehash("finance"); // finance.aragonpm.eth * bytes32 constant internal TOKEN_MANAGER_APP_ID = apmNamehash("token-manager"); // token-manager.aragonpm.eth */ bytes32 constant internal AGENT_APP_ID = 0x9ac98dc5f995bf0211ed589ef022719d1487e5cb2bab505676f0d084c07cf89a; bytes32 constant internal VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; bytes32 constant internal VOTING_APP_ID = 0x9fa3927f639745e587912d4b0fea7ef9013bf93fb907d29faeab57417ba6e1d4; bytes32 constant internal PAYROLL_APP_ID = 0x463f596a96d808cb28b5d080181e4a398bc793df2c222f6445189eb801001991; bytes32 constant internal FINANCE_APP_ID = 0xbf8491150dafc5dcaee5b861414dca922de09ccffa344964ae167212e8c673ae; bytes32 constant internal TOKEN_MANAGER_APP_ID = 0x6b20a3010614eeebf2138ccec99f028a61c811b3b1a3343b6ff635985c75c91f; bytes32 constant internal SURVEY_APP_ID = 0x030b2ab880b88e228f2da5a3d19a2a31bc10dbf91fb1143776a6de489389471e; string constant private ERROR_ENS_NOT_CONTRACT = "TEMPLATE_ENS_NOT_CONTRACT"; string constant private ERROR_DAO_FACTORY_NOT_CONTRACT = "TEMPLATE_DAO_FAC_NOT_CONTRACT"; string constant private ERROR_ARAGON_ID_NOT_PROVIDED = "TEMPLATE_ARAGON_ID_NOT_PROVIDED"; string constant private ERROR_ARAGON_ID_NOT_CONTRACT = "TEMPLATE_ARAGON_ID_NOT_CONTRACT"; string constant private ERROR_MINIME_FACTORY_NOT_PROVIDED = "TEMPLATE_MINIME_FAC_NOT_PROVIDED"; string constant private ERROR_MINIME_FACTORY_NOT_CONTRACT = "TEMPLATE_MINIME_FAC_NOT_CONTRACT"; string constant private ERROR_CANNOT_CAST_VALUE_TO_ADDRESS = "TEMPLATE_CANNOT_CAST_VALUE_TO_ADDRESS"; string constant private ERROR_INVALID_ID = "TEMPLATE_INVALID_ID"; ENS internal ens; DAOFactory internal daoFactory; MiniMeTokenFactory internal miniMeFactory; IFIFSResolvingRegistrar internal aragonID; event DeployDao(address dao); event SetupDao(address dao); event DeployToken(address token); event InstalledApp(address appProxy, bytes32 appId); constructor(DAOFactory _daoFactory, ENS _ens, MiniMeTokenFactory _miniMeFactory, IFIFSResolvingRegistrar _aragonID) public { require(isContract(address(_ens)), ERROR_ENS_NOT_CONTRACT); require(isContract(address(_daoFactory)), ERROR_DAO_FACTORY_NOT_CONTRACT); ens = _ens; aragonID = _aragonID; daoFactory = _daoFactory; miniMeFactory = _miniMeFactory; } /** * @dev Create a DAO using the DAO Factory and grant the template root permissions so it has full * control during setup. Once the DAO setup has finished, it is recommended to call the * `_transferRootPermissionsFromTemplateAndFinalizeDAO()` helper to transfer the root * permissions to the end entity in control of the organization. */ function _createDAO() internal returns (Kernel dao, ACL acl) { dao = daoFactory.newDAO(this); emit DeployDao(address(dao)); acl = ACL(dao.acl()); _createPermissionForTemplate(acl, dao, dao.APP_MANAGER_ROLE()); } /* ACL */ function _createPermissions(ACL _acl, address[] memory _grantees, address _app, bytes32 _permission, address _manager) internal { _acl.createPermission(_grantees[0], _app, _permission, address(this)); for (uint256 i = 1; i < _grantees.length; i++) { _acl.grantPermission(_grantees[i], _app, _permission); } _acl.revokePermission(address(this), _app, _permission); _acl.setPermissionManager(_manager, _app, _permission); } function _createPermissionForTemplate(ACL _acl, address _app, bytes32 _permission) internal { _acl.createPermission(address(this), _app, _permission, address(this)); } function _removePermissionFromTemplate(ACL _acl, address _app, bytes32 _permission) internal { _acl.revokePermission(address(this), _app, _permission); _acl.removePermissionManager(_app, _permission); } function _transferRootPermissionsFromTemplateAndFinalizeDAO(Kernel _dao, address _to) internal { _transferRootPermissionsFromTemplateAndFinalizeDAO(_dao, _to, _to); } function _transferRootPermissionsFromTemplateAndFinalizeDAO(Kernel _dao, address _to, address _manager) internal { ACL _acl = ACL(_dao.acl()); _transferPermissionFromTemplate(_acl, _dao, _to, _dao.APP_MANAGER_ROLE(), _manager); _transferPermissionFromTemplate(_acl, _acl, _to, _acl.CREATE_PERMISSIONS_ROLE(), _manager); emit SetupDao(_dao); } function _transferPermissionFromTemplate(ACL _acl, address _app, address _to, bytes32 _permission, address _manager) internal { _acl.grantPermission(_to, _app, _permission); _acl.revokePermission(address(this), _app, _permission); _acl.setPermissionManager(_manager, _app, _permission); } /* AGENT */ function _installDefaultAgentApp(Kernel _dao) internal returns (Agent) { bytes memory initializeData = abi.encodeWithSelector(Agent(0).initialize.selector); Agent agent = Agent(_installDefaultApp(_dao, AGENT_APP_ID, initializeData)); // We assume that installing the Agent app as a default app means the DAO should have its // Vault replaced by the Agent. Thus, we also set the DAO's recovery app to the Agent. _dao.setRecoveryVaultAppId(AGENT_APP_ID); return agent; } function _installNonDefaultAgentApp(Kernel _dao) internal returns (Agent) { bytes memory initializeData = abi.encodeWithSelector(Agent(0).initialize.selector); return Agent(_installNonDefaultApp(_dao, AGENT_APP_ID, initializeData)); } function _createAgentPermissions(ACL _acl, Agent _agent, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _agent, _agent.EXECUTE_ROLE(), _manager); _acl.createPermission(_grantee, _agent, _agent.RUN_SCRIPT_ROLE(), _manager); } /* VAULT */ function _installVaultApp(Kernel _dao) internal returns (Vault) { bytes memory initializeData = abi.encodeWithSelector(Vault(0).initialize.selector); return Vault(_installDefaultApp(_dao, VAULT_APP_ID, initializeData)); } function _createVaultPermissions(ACL _acl, Vault _vault, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _vault, _vault.TRANSFER_ROLE(), _manager); } /* VOTING */ function _installVotingApp(Kernel _dao, MiniMeToken _token, uint64[3] memory _votingSettings) internal returns (Voting) { return _installVotingApp(_dao, _token, _votingSettings[0], _votingSettings[1], _votingSettings[2]); } function _installVotingApp( Kernel _dao, MiniMeToken _token, uint64 _support, uint64 _acceptance, uint64 _duration ) internal returns (Voting) { bytes memory initializeData = abi.encodeWithSelector(Voting(0).initialize.selector, _token, _support, _acceptance, _duration); return Voting(_installNonDefaultApp(_dao, VOTING_APP_ID, initializeData)); } function _createVotingPermissions( ACL _acl, Voting _voting, address _settingsGrantee, address _createVotesGrantee, address _manager ) internal { _acl.createPermission(_settingsGrantee, _voting, _voting.MODIFY_QUORUM_ROLE(), _manager); _acl.createPermission(_settingsGrantee, _voting, _voting.MODIFY_SUPPORT_ROLE(), _manager); _acl.createPermission(_createVotesGrantee, _voting, _voting.CREATE_VOTES_ROLE(), _manager); } /* SURVEY */ function _installSurveyApp(Kernel _dao, MiniMeToken _token, uint64 _minParticipationPct, uint64 _surveyTime) internal returns (Survey) { bytes memory initializeData = abi.encodeWithSelector(Survey(0).initialize.selector, _token, _minParticipationPct, _surveyTime); return Survey(_installNonDefaultApp(_dao, SURVEY_APP_ID, initializeData)); } function _createSurveyPermissions(ACL _acl, Survey _survey, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _survey, _survey.CREATE_SURVEYS_ROLE(), _manager); _acl.createPermission(_grantee, _survey, _survey.MODIFY_PARTICIPATION_ROLE(), _manager); } /* PAYROLL */ function _installPayrollApp( Kernel _dao, Finance _finance, address _denominationToken, IFeed _priceFeed, uint64 _rateExpiryTime ) internal returns (Payroll) { bytes memory initializeData = abi.encodeWithSelector( Payroll(0).initialize.selector, _finance, _denominationToken, _priceFeed, _rateExpiryTime ); return Payroll(_installNonDefaultApp(_dao, PAYROLL_APP_ID, initializeData)); } /** * @dev Internal function to configure payroll permissions. Note that we allow defining different managers for * payroll since it may be useful to have one control the payroll settings (rate expiration, price feed, * and allowed tokens), and another one to control the employee functionality (bonuses, salaries, * reimbursements, employees, etc). * @param _acl ACL instance being configured * @param _acl Payroll app being configured * @param _employeeManager Address that will receive permissions to handle employee payroll functionality * @param _settingsManager Address that will receive permissions to manage payroll settings * @param _permissionsManager Address that will be the ACL manager for the payroll permissions */ function _createPayrollPermissions( ACL _acl, Payroll _payroll, address _employeeManager, address _settingsManager, address _permissionsManager ) internal { _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_BONUS_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_EMPLOYEE_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_REIMBURSEMENT_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.TERMINATE_EMPLOYEE_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.SET_EMPLOYEE_SALARY_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MODIFY_PRICE_FEED_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MODIFY_RATE_EXPIRY_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MANAGE_ALLOWED_TOKENS_ROLE(), _permissionsManager); } function _unwrapPayrollSettings( uint256[4] memory _payrollSettings ) internal pure returns (address denominationToken, IFeed priceFeed, uint64 rateExpiryTime, address employeeManager) { denominationToken = _toAddress(_payrollSettings[0]); priceFeed = IFeed(_toAddress(_payrollSettings[1])); rateExpiryTime = _payrollSettings[2].toUint64(); employeeManager = _toAddress(_payrollSettings[3]); } /* FINANCE */ function _installFinanceApp(Kernel _dao, Vault _vault, uint64 _periodDuration) internal returns (Finance) { bytes memory initializeData = abi.encodeWithSelector(Finance(0).initialize.selector, _vault, _periodDuration); return Finance(_installNonDefaultApp(_dao, FINANCE_APP_ID, initializeData)); } function _createFinancePermissions(ACL _acl, Finance _finance, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _finance, _finance.EXECUTE_PAYMENTS_ROLE(), _manager); _acl.createPermission(_grantee, _finance, _finance.MANAGE_PAYMENTS_ROLE(), _manager); } function _createFinanceCreatePaymentsPermission(ACL _acl, Finance _finance, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _finance, _finance.CREATE_PAYMENTS_ROLE(), _manager); } function _grantCreatePaymentPermission(ACL _acl, Finance _finance, address _to) internal { _acl.grantPermission(_to, _finance, _finance.CREATE_PAYMENTS_ROLE()); } function _transferCreatePaymentManagerFromTemplate(ACL _acl, Finance _finance, address _manager) internal { _acl.setPermissionManager(_manager, _finance, _finance.CREATE_PAYMENTS_ROLE()); } /* TOKEN MANAGER */ function _installTokenManagerApp( Kernel _dao, MiniMeToken _token, bool _transferable, uint256 _maxAccountTokens ) internal returns (TokenManager) { TokenManager tokenManager = TokenManager(_installNonDefaultApp(_dao, TOKEN_MANAGER_APP_ID)); _token.changeController(tokenManager); tokenManager.initialize(_token, _transferable, _maxAccountTokens); return tokenManager; } function _createTokenManagerPermissions(ACL _acl, TokenManager _tokenManager, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _tokenManager, _tokenManager.MINT_ROLE(), _manager); _acl.createPermission(_grantee, _tokenManager, _tokenManager.BURN_ROLE(), _manager); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address[] memory _holders, uint256[] memory _stakes) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); for (uint256 i = 0; i < _holders.length; i++) { _tokenManager.mint(_holders[i], _stakes[i]); } _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address[] memory _holders, uint256 _stake) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); for (uint256 i = 0; i < _holders.length; i++) { _tokenManager.mint(_holders[i], _stake); } _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address _holder, uint256 _stake) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); _tokenManager.mint(_holder, _stake); _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } /* EVM SCRIPTS */ function _createEvmScriptsRegistryPermissions(ACL _acl, address _grantee, address _manager) internal { EVMScriptRegistry registry = EVMScriptRegistry(_acl.getEVMScriptRegistry()); _acl.createPermission(_grantee, registry, registry.REGISTRY_MANAGER_ROLE(), _manager); _acl.createPermission(_grantee, registry, registry.REGISTRY_ADD_EXECUTOR_ROLE(), _manager); } /* APPS */ function _installNonDefaultApp(Kernel _dao, bytes32 _appId) internal returns (address) { return _installNonDefaultApp(_dao, _appId, new bytes(0)); } function _installNonDefaultApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData) internal returns (address) { return _installApp(_dao, _appId, _initializeData, false); } function _installDefaultApp(Kernel _dao, bytes32 _appId) internal returns (address) { return _installDefaultApp(_dao, _appId, new bytes(0)); } function _installDefaultApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData) internal returns (address) { return _installApp(_dao, _appId, _initializeData, true); } function _installApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData, bool _setDefault) internal returns (address) { address latestBaseAppAddress = _latestVersionAppBase(_appId); address instance = address(_dao.newAppInstance(_appId, latestBaseAppAddress, _initializeData, _setDefault)); emit InstalledApp(instance, _appId); return instance; } function _latestVersionAppBase(bytes32 _appId) internal view returns (address base) { Repo repo = Repo(PublicResolver(ens.resolver(_appId)).addr(_appId)); (,base,) = repo.getLatest(); } /* TOKEN */ function _createToken(string memory _name, string memory _symbol, uint8 _decimals) internal returns (MiniMeToken) { require(address(miniMeFactory) != address(0), ERROR_MINIME_FACTORY_NOT_PROVIDED); MiniMeToken token = miniMeFactory.createCloneToken(MiniMeToken(address(0)), 0, _name, _decimals, _symbol, true); emit DeployToken(address(token)); return token; } function _ensureMiniMeFactoryIsValid(address _miniMeFactory) internal view { require(isContract(address(_miniMeFactory)), ERROR_MINIME_FACTORY_NOT_CONTRACT); } /* IDS */ function _validateId(string memory _id) internal pure { require(bytes(_id).length > 0, ERROR_INVALID_ID); } function _registerID(string memory _name, address _owner) internal { require(address(aragonID) != address(0), ERROR_ARAGON_ID_NOT_PROVIDED); aragonID.register(keccak256(abi.encodePacked(_name)), _owner); } function _ensureAragonIdIsValid(address _aragonID) internal view { require(isContract(address(_aragonID)), ERROR_ARAGON_ID_NOT_CONTRACT); } /* HELPERS */ function _toAddress(uint256 _value) private pure returns (address) { require(_value <= uint160(-1), ERROR_CANNOT_CAST_VALUE_TO_ADDRESS); return address(_value); } } // File: @ablack/fundraising-bancor-formula/contracts/interfaces/IBancorFormula.sol pragma solidity 0.4.24; /* Bancor Formula interface */ contract IBancorFormula { function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256); function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256); function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256); } // File: @ablack/fundraising-bancor-formula/contracts/utility/Utils.sol pragma solidity 0.4.24; /* Utilities & Common Modifiers */ contract Utils { /** constructor */ constructor() public { } // verifies that an amount is greater than zero modifier greaterThanZero(uint256 _amount) { require(_amount > 0); _; } // validates an address - currently only checks that it isn't null modifier validAddress(address _address) { require(_address != address(0)); _; } // verifies that the address is different than this contract address modifier notThis(address _address) { require(_address != address(this)); _; } } // File: @ablack/fundraising-bancor-formula/contracts/BancorFormula.sol pragma solidity 0.4.24; contract BancorFormula is IBancorFormula, Utils { using SafeMath for uint256; string public version = '0.3'; uint256 private constant ONE = 1; uint32 private constant MAX_WEIGHT = 1000000; uint8 private constant MIN_PRECISION = 32; uint8 private constant MAX_PRECISION = 127; /** Auto-generated via 'PrintIntScalingFactors.py' */ uint256 private constant FIXED_1 = 0x080000000000000000000000000000000; uint256 private constant FIXED_2 = 0x100000000000000000000000000000000; uint256 private constant MAX_NUM = 0x200000000000000000000000000000000; /** Auto-generated via 'PrintLn2ScalingFactors.py' */ uint256 private constant LN2_NUMERATOR = 0x3f80fe03f80fe03f80fe03f80fe03f8; uint256 private constant LN2_DENOMINATOR = 0x5b9de1d10bf4103d647b0955897ba80; /** Auto-generated via 'PrintFunctionOptimalLog.py' and 'PrintFunctionOptimalExp.py' */ uint256 private constant OPT_LOG_MAX_VAL = 0x15bf0a8b1457695355fb8ac404e7a79e3; uint256 private constant OPT_EXP_MAX_VAL = 0x800000000000000000000000000000000; /** Auto-generated via 'PrintFunctionConstructor.py' */ uint256[128] private maxExpArray; constructor() public { // maxExpArray[ 0] = 0x6bffffffffffffffffffffffffffffffff; // maxExpArray[ 1] = 0x67ffffffffffffffffffffffffffffffff; // maxExpArray[ 2] = 0x637fffffffffffffffffffffffffffffff; // maxExpArray[ 3] = 0x5f6fffffffffffffffffffffffffffffff; // maxExpArray[ 4] = 0x5b77ffffffffffffffffffffffffffffff; // maxExpArray[ 5] = 0x57b3ffffffffffffffffffffffffffffff; // maxExpArray[ 6] = 0x5419ffffffffffffffffffffffffffffff; // maxExpArray[ 7] = 0x50a2ffffffffffffffffffffffffffffff; // maxExpArray[ 8] = 0x4d517fffffffffffffffffffffffffffff; // maxExpArray[ 9] = 0x4a233fffffffffffffffffffffffffffff; // maxExpArray[ 10] = 0x47165fffffffffffffffffffffffffffff; // maxExpArray[ 11] = 0x4429afffffffffffffffffffffffffffff; // maxExpArray[ 12] = 0x415bc7ffffffffffffffffffffffffffff; // maxExpArray[ 13] = 0x3eab73ffffffffffffffffffffffffffff; // maxExpArray[ 14] = 0x3c1771ffffffffffffffffffffffffffff; // maxExpArray[ 15] = 0x399e96ffffffffffffffffffffffffffff; // maxExpArray[ 16] = 0x373fc47fffffffffffffffffffffffffff; // maxExpArray[ 17] = 0x34f9e8ffffffffffffffffffffffffffff; // maxExpArray[ 18] = 0x32cbfd5fffffffffffffffffffffffffff; // maxExpArray[ 19] = 0x30b5057fffffffffffffffffffffffffff; // maxExpArray[ 20] = 0x2eb40f9fffffffffffffffffffffffffff; // maxExpArray[ 21] = 0x2cc8340fffffffffffffffffffffffffff; // maxExpArray[ 22] = 0x2af09481ffffffffffffffffffffffffff; // maxExpArray[ 23] = 0x292c5bddffffffffffffffffffffffffff; // maxExpArray[ 24] = 0x277abdcdffffffffffffffffffffffffff; // maxExpArray[ 25] = 0x25daf6657fffffffffffffffffffffffff; // maxExpArray[ 26] = 0x244c49c65fffffffffffffffffffffffff; // maxExpArray[ 27] = 0x22ce03cd5fffffffffffffffffffffffff; // maxExpArray[ 28] = 0x215f77c047ffffffffffffffffffffffff; // maxExpArray[ 29] = 0x1fffffffffffffffffffffffffffffffff; // maxExpArray[ 30] = 0x1eaefdbdabffffffffffffffffffffffff; // maxExpArray[ 31] = 0x1d6bd8b2ebffffffffffffffffffffffff; maxExpArray[ 32] = 0x1c35fedd14ffffffffffffffffffffffff; maxExpArray[ 33] = 0x1b0ce43b323fffffffffffffffffffffff; maxExpArray[ 34] = 0x19f0028ec1ffffffffffffffffffffffff; maxExpArray[ 35] = 0x18ded91f0e7fffffffffffffffffffffff; maxExpArray[ 36] = 0x17d8ec7f0417ffffffffffffffffffffff; maxExpArray[ 37] = 0x16ddc6556cdbffffffffffffffffffffff; maxExpArray[ 38] = 0x15ecf52776a1ffffffffffffffffffffff; maxExpArray[ 39] = 0x15060c256cb2ffffffffffffffffffffff; maxExpArray[ 40] = 0x1428a2f98d72ffffffffffffffffffffff; maxExpArray[ 41] = 0x13545598e5c23fffffffffffffffffffff; maxExpArray[ 42] = 0x1288c4161ce1dfffffffffffffffffffff; maxExpArray[ 43] = 0x11c592761c666fffffffffffffffffffff; maxExpArray[ 44] = 0x110a688680a757ffffffffffffffffffff; maxExpArray[ 45] = 0x1056f1b5bedf77ffffffffffffffffffff; maxExpArray[ 46] = 0x0faadceceeff8bffffffffffffffffffff; maxExpArray[ 47] = 0x0f05dc6b27edadffffffffffffffffffff; maxExpArray[ 48] = 0x0e67a5a25da4107fffffffffffffffffff; maxExpArray[ 49] = 0x0dcff115b14eedffffffffffffffffffff; maxExpArray[ 50] = 0x0d3e7a392431239fffffffffffffffffff; maxExpArray[ 51] = 0x0cb2ff529eb71e4fffffffffffffffffff; maxExpArray[ 52] = 0x0c2d415c3db974afffffffffffffffffff; maxExpArray[ 53] = 0x0bad03e7d883f69bffffffffffffffffff; maxExpArray[ 54] = 0x0b320d03b2c343d5ffffffffffffffffff; maxExpArray[ 55] = 0x0abc25204e02828dffffffffffffffffff; maxExpArray[ 56] = 0x0a4b16f74ee4bb207fffffffffffffffff; maxExpArray[ 57] = 0x09deaf736ac1f569ffffffffffffffffff; maxExpArray[ 58] = 0x0976bd9952c7aa957fffffffffffffffff; maxExpArray[ 59] = 0x09131271922eaa606fffffffffffffffff; maxExpArray[ 60] = 0x08b380f3558668c46fffffffffffffffff; maxExpArray[ 61] = 0x0857ddf0117efa215bffffffffffffffff; maxExpArray[ 62] = 0x07ffffffffffffffffffffffffffffffff; maxExpArray[ 63] = 0x07abbf6f6abb9d087fffffffffffffffff; maxExpArray[ 64] = 0x075af62cbac95f7dfa7fffffffffffffff; maxExpArray[ 65] = 0x070d7fb7452e187ac13fffffffffffffff; maxExpArray[ 66] = 0x06c3390ecc8af379295fffffffffffffff; maxExpArray[ 67] = 0x067c00a3b07ffc01fd6fffffffffffffff; maxExpArray[ 68] = 0x0637b647c39cbb9d3d27ffffffffffffff; maxExpArray[ 69] = 0x05f63b1fc104dbd39587ffffffffffffff; maxExpArray[ 70] = 0x05b771955b36e12f7235ffffffffffffff; maxExpArray[ 71] = 0x057b3d49dda84556d6f6ffffffffffffff; maxExpArray[ 72] = 0x054183095b2c8ececf30ffffffffffffff; maxExpArray[ 73] = 0x050a28be635ca2b888f77fffffffffffff; maxExpArray[ 74] = 0x04d5156639708c9db33c3fffffffffffff; maxExpArray[ 75] = 0x04a23105873875bd52dfdfffffffffffff; maxExpArray[ 76] = 0x0471649d87199aa990756fffffffffffff; maxExpArray[ 77] = 0x04429a21a029d4c1457cfbffffffffffff; maxExpArray[ 78] = 0x0415bc6d6fb7dd71af2cb3ffffffffffff; maxExpArray[ 79] = 0x03eab73b3bbfe282243ce1ffffffffffff; maxExpArray[ 80] = 0x03c1771ac9fb6b4c18e229ffffffffffff; maxExpArray[ 81] = 0x0399e96897690418f785257fffffffffff; maxExpArray[ 82] = 0x0373fc456c53bb779bf0ea9fffffffffff; maxExpArray[ 83] = 0x034f9e8e490c48e67e6ab8bfffffffffff; maxExpArray[ 84] = 0x032cbfd4a7adc790560b3337ffffffffff; maxExpArray[ 85] = 0x030b50570f6e5d2acca94613ffffffffff; maxExpArray[ 86] = 0x02eb40f9f620fda6b56c2861ffffffffff; maxExpArray[ 87] = 0x02cc8340ecb0d0f520a6af58ffffffffff; maxExpArray[ 88] = 0x02af09481380a0a35cf1ba02ffffffffff; maxExpArray[ 89] = 0x0292c5bdd3b92ec810287b1b3fffffffff; maxExpArray[ 90] = 0x0277abdcdab07d5a77ac6d6b9fffffffff; maxExpArray[ 91] = 0x025daf6654b1eaa55fd64df5efffffffff; maxExpArray[ 92] = 0x0244c49c648baa98192dce88b7ffffffff; maxExpArray[ 93] = 0x022ce03cd5619a311b2471268bffffffff; maxExpArray[ 94] = 0x0215f77c045fbe885654a44a0fffffffff; maxExpArray[ 95] = 0x01ffffffffffffffffffffffffffffffff; maxExpArray[ 96] = 0x01eaefdbdaaee7421fc4d3ede5ffffffff; maxExpArray[ 97] = 0x01d6bd8b2eb257df7e8ca57b09bfffffff; maxExpArray[ 98] = 0x01c35fedd14b861eb0443f7f133fffffff; maxExpArray[ 99] = 0x01b0ce43b322bcde4a56e8ada5afffffff; maxExpArray[100] = 0x019f0028ec1fff007f5a195a39dfffffff; maxExpArray[101] = 0x018ded91f0e72ee74f49b15ba527ffffff; maxExpArray[102] = 0x017d8ec7f04136f4e5615fd41a63ffffff; maxExpArray[103] = 0x016ddc6556cdb84bdc8d12d22e6fffffff; maxExpArray[104] = 0x015ecf52776a1155b5bd8395814f7fffff; maxExpArray[105] = 0x015060c256cb23b3b3cc3754cf40ffffff; maxExpArray[106] = 0x01428a2f98d728ae223ddab715be3fffff; maxExpArray[107] = 0x013545598e5c23276ccf0ede68034fffff; maxExpArray[108] = 0x01288c4161ce1d6f54b7f61081194fffff; maxExpArray[109] = 0x011c592761c666aa641d5a01a40f17ffff; maxExpArray[110] = 0x0110a688680a7530515f3e6e6cfdcdffff; maxExpArray[111] = 0x01056f1b5bedf75c6bcb2ce8aed428ffff; maxExpArray[112] = 0x00faadceceeff8a0890f3875f008277fff; maxExpArray[113] = 0x00f05dc6b27edad306388a600f6ba0bfff; maxExpArray[114] = 0x00e67a5a25da41063de1495d5b18cdbfff; maxExpArray[115] = 0x00dcff115b14eedde6fc3aa5353f2e4fff; maxExpArray[116] = 0x00d3e7a3924312399f9aae2e0f868f8fff; maxExpArray[117] = 0x00cb2ff529eb71e41582cccd5a1ee26fff; maxExpArray[118] = 0x00c2d415c3db974ab32a51840c0b67edff; maxExpArray[119] = 0x00bad03e7d883f69ad5b0a186184e06bff; maxExpArray[120] = 0x00b320d03b2c343d4829abd6075f0cc5ff; maxExpArray[121] = 0x00abc25204e02828d73c6e80bcdb1a95bf; maxExpArray[122] = 0x00a4b16f74ee4bb2040a1ec6c15fbbf2df; maxExpArray[123] = 0x009deaf736ac1f569deb1b5ae3f36c130f; maxExpArray[124] = 0x00976bd9952c7aa957f5937d790ef65037; maxExpArray[125] = 0x009131271922eaa6064b73a22d0bd4f2bf; maxExpArray[126] = 0x008b380f3558668c46c91c49a2f8e967b9; maxExpArray[127] = 0x00857ddf0117efa215952912839f6473e6; } /** @dev given a token supply, connector balance, weight and a deposit amount (in the connector token), calculates the return for a given conversion (in the main token) Formula: Return = _supply * ((1 + _depositAmount / _connectorBalance) ^ (_connectorWeight / 1000000) - 1) @param _supply token total supply @param _connectorBalance total connector balance @param _connectorWeight connector weight, represented in ppm, 1-1000000 @param _depositAmount deposit amount, in connector token @return purchase return amount */ function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256) { // validate input require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT); // special case for 0 deposit amount if (_depositAmount == 0) return 0; // special case if the weight = 100% if (_connectorWeight == MAX_WEIGHT) return _supply.mul(_depositAmount) / _connectorBalance; uint256 result; uint8 precision; uint256 baseN = _depositAmount.add(_connectorBalance); (result, precision) = power(baseN, _connectorBalance, _connectorWeight, MAX_WEIGHT); uint256 temp = _supply.mul(result) >> precision; return temp - _supply; } /** @dev given a token supply, connector balance, weight and a sell amount (in the main token), calculates the return for a given conversion (in the connector token) Formula: Return = _connectorBalance * (1 - (1 - _sellAmount / _supply) ^ (1 / (_connectorWeight / 1000000))) @param _supply token total supply @param _connectorBalance total connector @param _connectorWeight constant connector Weight, represented in ppm, 1-1000000 @param _sellAmount sell amount, in the token itself @return sale return amount */ function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256) { // validate input require(_supply > 0 && _connectorBalance > 0 && _connectorWeight > 0 && _connectorWeight <= MAX_WEIGHT && _sellAmount <= _supply); // special case for 0 sell amount if (_sellAmount == 0) return 0; // special case for selling the entire supply if (_sellAmount == _supply) return _connectorBalance; // special case if the weight = 100% if (_connectorWeight == MAX_WEIGHT) return _connectorBalance.mul(_sellAmount) / _supply; uint256 result; uint8 precision; uint256 baseD = _supply - _sellAmount; (result, precision) = power(_supply, baseD, MAX_WEIGHT, _connectorWeight); uint256 temp1 = _connectorBalance.mul(result); uint256 temp2 = _connectorBalance << precision; return (temp1 - temp2) / result; } /** @dev given two connector balances/weights and a sell amount (in the first connector token), calculates the return for a conversion from the first connector token to the second connector token (in the second connector token) Formula: Return = _toConnectorBalance * (1 - (_fromConnectorBalance / (_fromConnectorBalance + _amount)) ^ (_fromConnectorWeight / _toConnectorWeight)) @param _fromConnectorBalance input connector balance @param _fromConnectorWeight input connector weight, represented in ppm, 1-1000000 @param _toConnectorBalance output connector balance @param _toConnectorWeight output connector weight, represented in ppm, 1-1000000 @param _amount input connector amount @return second connector amount */ function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256) { // validate input require(_fromConnectorBalance > 0 && _fromConnectorWeight > 0 && _fromConnectorWeight <= MAX_WEIGHT && _toConnectorBalance > 0 && _toConnectorWeight > 0 && _toConnectorWeight <= MAX_WEIGHT); // special case for equal weights if (_fromConnectorWeight == _toConnectorWeight) return _toConnectorBalance.mul(_amount) / _fromConnectorBalance.add(_amount); uint256 result; uint8 precision; uint256 baseN = _fromConnectorBalance.add(_amount); (result, precision) = power(baseN, _fromConnectorBalance, _fromConnectorWeight, _toConnectorWeight); uint256 temp1 = _toConnectorBalance.mul(result); uint256 temp2 = _toConnectorBalance << precision; return (temp1 - temp2) / result; } /** General Description: Determine a value of precision. Calculate an integer approximation of (_baseN / _baseD) ^ (_expN / _expD) * 2 ^ precision. Return the result along with the precision used. Detailed Description: Instead of calculating "base ^ exp", we calculate "e ^ (log(base) * exp)". The value of "log(base)" is represented with an integer slightly smaller than "log(base) * 2 ^ precision". The larger "precision" is, the more accurately this value represents the real value. However, the larger "precision" is, the more bits are required in order to store this value. And the exponentiation function, which takes "x" and calculates "e ^ x", is limited to a maximum exponent (maximum value of "x"). This maximum exponent depends on the "precision" used, and it is given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". Hence we need to determine the highest precision which can be used for the given input, before calling the exponentiation function. This allows us to compute "base ^ exp" with maximum accuracy and without exceeding 256 bits in any of the intermediate computations. This functions assumes that "_expN < 2 ^ 256 / log(MAX_NUM - 1)", otherwise the multiplication should be replaced with a "safeMul". */ function power(uint256 _baseN, uint256 _baseD, uint32 _expN, uint32 _expD) internal view returns (uint256, uint8) { require(_baseN < MAX_NUM); uint256 baseLog; uint256 base = _baseN * FIXED_1 / _baseD; if (base < OPT_LOG_MAX_VAL) { baseLog = optimalLog(base); } else { baseLog = generalLog(base); } uint256 baseLogTimesExp = baseLog * _expN / _expD; if (baseLogTimesExp < OPT_EXP_MAX_VAL) { return (optimalExp(baseLogTimesExp), MAX_PRECISION); } else { uint8 precision = findPositionInMaxExpArray(baseLogTimesExp); return (generalExp(baseLogTimesExp >> (MAX_PRECISION - precision), precision), precision); } } /** Compute log(x / FIXED_1) * FIXED_1. This functions assumes that "x >= FIXED_1", because the output would be negative otherwise. */ function generalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; // If x >= 2, then we compute the integer part of log2(x), which is larger than 0. if (x >= FIXED_2) { uint8 count = floorLog2(x / FIXED_1); x >>= count; // now x < 2 res = count * FIXED_1; } // If x > 1, then we compute the fraction part of log2(x), which is larger than 0. if (x > FIXED_1) { for (uint8 i = MAX_PRECISION; i > 0; --i) { x = (x * x) / FIXED_1; // now 1 < x < 4 if (x >= FIXED_2) { x >>= 1; // now 1 < x < 2 res += ONE << (i - 1); } } } return res * LN2_NUMERATOR / LN2_DENOMINATOR; } /** Compute the largest integer smaller than or equal to the binary logarithm of the input. */ function floorLog2(uint256 _n) internal pure returns (uint8) { uint8 res = 0; if (_n < 256) { // At most 8 iterations while (_n > 1) { _n >>= 1; res += 1; } } else { // Exactly 8 iterations for (uint8 s = 128; s > 0; s >>= 1) { if (_n >= (ONE << s)) { _n >>= s; res |= s; } } } return res; } /** The global "maxExpArray" is sorted in descending order, and therefore the following statements are equivalent: - This function finds the position of [the smallest value in "maxExpArray" larger than or equal to "x"] - This function finds the highest position of [a value in "maxExpArray" larger than or equal to "x"] */ function findPositionInMaxExpArray(uint256 _x) internal view returns (uint8) { uint8 lo = MIN_PRECISION; uint8 hi = MAX_PRECISION; while (lo + 1 < hi) { uint8 mid = (lo + hi) / 2; if (maxExpArray[mid] >= _x) lo = mid; else hi = mid; } if (maxExpArray[hi] >= _x) return hi; if (maxExpArray[lo] >= _x) return lo; require(false); return 0; } /** This function can be auto-generated by the script 'PrintFunctionGeneralExp.py'. It approximates "e ^ x" via maclaurin summation: "(x^0)/0! + (x^1)/1! + ... + (x^n)/n!". It returns "e ^ (x / 2 ^ precision) * 2 ^ precision", that is, the result is upshifted for accuracy. The global "maxExpArray" maps each "precision" to "((maximumExponent + 1) << (MAX_PRECISION - precision)) - 1". The maximum permitted value for "x" is therefore given by "maxExpArray[precision] >> (MAX_PRECISION - precision)". */ function generalExp(uint256 _x, uint8 _precision) internal pure returns (uint256) { uint256 xi = _x; uint256 res = 0; xi = (xi * _x) >> _precision; res += xi * 0x3442c4e6074a82f1797f72ac0000000; // add x^02 * (33! / 02!) xi = (xi * _x) >> _precision; res += xi * 0x116b96f757c380fb287fd0e40000000; // add x^03 * (33! / 03!) xi = (xi * _x) >> _precision; res += xi * 0x045ae5bdd5f0e03eca1ff4390000000; // add x^04 * (33! / 04!) xi = (xi * _x) >> _precision; res += xi * 0x00defabf91302cd95b9ffda50000000; // add x^05 * (33! / 05!) xi = (xi * _x) >> _precision; res += xi * 0x002529ca9832b22439efff9b8000000; // add x^06 * (33! / 06!) xi = (xi * _x) >> _precision; res += xi * 0x00054f1cf12bd04e516b6da88000000; // add x^07 * (33! / 07!) xi = (xi * _x) >> _precision; res += xi * 0x0000a9e39e257a09ca2d6db51000000; // add x^08 * (33! / 08!) xi = (xi * _x) >> _precision; res += xi * 0x000012e066e7b839fa050c309000000; // add x^09 * (33! / 09!) xi = (xi * _x) >> _precision; res += xi * 0x000001e33d7d926c329a1ad1a800000; // add x^10 * (33! / 10!) xi = (xi * _x) >> _precision; res += xi * 0x0000002bee513bdb4a6b19b5f800000; // add x^11 * (33! / 11!) xi = (xi * _x) >> _precision; res += xi * 0x00000003a9316fa79b88eccf2a00000; // add x^12 * (33! / 12!) xi = (xi * _x) >> _precision; res += xi * 0x0000000048177ebe1fa812375200000; // add x^13 * (33! / 13!) xi = (xi * _x) >> _precision; res += xi * 0x0000000005263fe90242dcbacf00000; // add x^14 * (33! / 14!) xi = (xi * _x) >> _precision; res += xi * 0x000000000057e22099c030d94100000; // add x^15 * (33! / 15!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000057e22099c030d9410000; // add x^16 * (33! / 16!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000052b6b54569976310000; // add x^17 * (33! / 17!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000004985f67696bf748000; // add x^18 * (33! / 18!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000003dea12ea99e498000; // add x^19 * (33! / 19!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000031880f2214b6e000; // add x^20 * (33! / 20!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000025bcff56eb36000; // add x^21 * (33! / 21!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000001b722e10ab1000; // add x^22 * (33! / 22!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000001317c70077000; // add x^23 * (33! / 23!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000cba84aafa00; // add x^24 * (33! / 24!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000082573a0a00; // add x^25 * (33! / 25!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000005035ad900; // add x^26 * (33! / 26!) xi = (xi * _x) >> _precision; res += xi * 0x000000000000000000000002f881b00; // add x^27 * (33! / 27!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000001b29340; // add x^28 * (33! / 28!) xi = (xi * _x) >> _precision; res += xi * 0x00000000000000000000000000efc40; // add x^29 * (33! / 29!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000007fe0; // add x^30 * (33! / 30!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000420; // add x^31 * (33! / 31!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000021; // add x^32 * (33! / 32!) xi = (xi * _x) >> _precision; res += xi * 0x0000000000000000000000000000001; // add x^33 * (33! / 33!) return res / 0x688589cc0e9505e2f2fee5580000000 + _x + (ONE << _precision); // divide by 33! and then add x^1 / 1! + x^0 / 0! } /** Return log(x / FIXED_1) * FIXED_1 Input range: FIXED_1 <= x <= LOG_EXP_MAX_VAL - 1 Auto-generated via 'PrintFunctionOptimalLog.py' Detailed description: - Rewrite the input as a product of natural exponents and a single residual r, such that 1 < r < 2 - The natural logarithm of each (pre-calculated) exponent is the degree of the exponent - The natural logarithm of r is calculated via Taylor series for log(1 + x), where x = r - 1 - The natural logarithm of the input is calculated by summing up the intermediate results above - For example: log(250) = log(e^4 * e^1 * e^0.5 * 1.021692859) = 4 + 1 + 0.5 + log(1 + 0.021692859) */ function optimalLog(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; uint256 w; if (x >= 0xd3094c70f034de4b96ff7d5b6f99fcd8) {res += 0x40000000000000000000000000000000; x = x * FIXED_1 / 0xd3094c70f034de4b96ff7d5b6f99fcd8;} // add 1 / 2^1 if (x >= 0xa45af1e1f40c333b3de1db4dd55f29a7) {res += 0x20000000000000000000000000000000; x = x * FIXED_1 / 0xa45af1e1f40c333b3de1db4dd55f29a7;} // add 1 / 2^2 if (x >= 0x910b022db7ae67ce76b441c27035c6a1) {res += 0x10000000000000000000000000000000; x = x * FIXED_1 / 0x910b022db7ae67ce76b441c27035c6a1;} // add 1 / 2^3 if (x >= 0x88415abbe9a76bead8d00cf112e4d4a8) {res += 0x08000000000000000000000000000000; x = x * FIXED_1 / 0x88415abbe9a76bead8d00cf112e4d4a8;} // add 1 / 2^4 if (x >= 0x84102b00893f64c705e841d5d4064bd3) {res += 0x04000000000000000000000000000000; x = x * FIXED_1 / 0x84102b00893f64c705e841d5d4064bd3;} // add 1 / 2^5 if (x >= 0x8204055aaef1c8bd5c3259f4822735a2) {res += 0x02000000000000000000000000000000; x = x * FIXED_1 / 0x8204055aaef1c8bd5c3259f4822735a2;} // add 1 / 2^6 if (x >= 0x810100ab00222d861931c15e39b44e99) {res += 0x01000000000000000000000000000000; x = x * FIXED_1 / 0x810100ab00222d861931c15e39b44e99;} // add 1 / 2^7 if (x >= 0x808040155aabbbe9451521693554f733) {res += 0x00800000000000000000000000000000; x = x * FIXED_1 / 0x808040155aabbbe9451521693554f733;} // add 1 / 2^8 z = y = x - FIXED_1; w = y * y / FIXED_1; res += z * (0x100000000000000000000000000000000 - y) / 0x100000000000000000000000000000000; z = z * w / FIXED_1; // add y^01 / 01 - y^02 / 02 res += z * (0x0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa - y) / 0x200000000000000000000000000000000; z = z * w / FIXED_1; // add y^03 / 03 - y^04 / 04 res += z * (0x099999999999999999999999999999999 - y) / 0x300000000000000000000000000000000; z = z * w / FIXED_1; // add y^05 / 05 - y^06 / 06 res += z * (0x092492492492492492492492492492492 - y) / 0x400000000000000000000000000000000; z = z * w / FIXED_1; // add y^07 / 07 - y^08 / 08 res += z * (0x08e38e38e38e38e38e38e38e38e38e38e - y) / 0x500000000000000000000000000000000; z = z * w / FIXED_1; // add y^09 / 09 - y^10 / 10 res += z * (0x08ba2e8ba2e8ba2e8ba2e8ba2e8ba2e8b - y) / 0x600000000000000000000000000000000; z = z * w / FIXED_1; // add y^11 / 11 - y^12 / 12 res += z * (0x089d89d89d89d89d89d89d89d89d89d89 - y) / 0x700000000000000000000000000000000; z = z * w / FIXED_1; // add y^13 / 13 - y^14 / 14 res += z * (0x088888888888888888888888888888888 - y) / 0x800000000000000000000000000000000; // add y^15 / 15 - y^16 / 16 return res; } /** Return e ^ (x / FIXED_1) * FIXED_1 Input range: 0 <= x <= OPT_EXP_MAX_VAL - 1 Auto-generated via 'PrintFunctionOptimalExp.py' Detailed description: - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible - The exponentiation of each binary exponent is given (pre-calculated) - The exponentiation of r is calculated via Taylor series for e^x, where x = r - The exponentiation of the input is calculated by multiplying the intermediate results above - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859 */ function optimalExp(uint256 x) internal pure returns (uint256) { uint256 res = 0; uint256 y; uint256 z; z = y = x % 0x10000000000000000000000000000000; // get the input modulo 2^(-3) z = z * y / FIXED_1; res += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!) z = z * y / FIXED_1; res += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!) z = z * y / FIXED_1; res += z * 0x0168244fdac78000; // add y^04 * (20! / 04!) z = z * y / FIXED_1; res += z * 0x004807432bc18000; // add y^05 * (20! / 05!) z = z * y / FIXED_1; res += z * 0x000c0135dca04000; // add y^06 * (20! / 06!) z = z * y / FIXED_1; res += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!) z = z * y / FIXED_1; res += z * 0x000036e0f639b800; // add y^08 * (20! / 08!) z = z * y / FIXED_1; res += z * 0x00000618fee9f800; // add y^09 * (20! / 09!) z = z * y / FIXED_1; res += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!) z = z * y / FIXED_1; res += z * 0x0000000e30dce400; // add y^11 * (20! / 11!) z = z * y / FIXED_1; res += z * 0x000000012ebd1300; // add y^12 * (20! / 12!) z = z * y / FIXED_1; res += z * 0x0000000017499f00; // add y^13 * (20! / 13!) z = z * y / FIXED_1; res += z * 0x0000000001a9d480; // add y^14 * (20! / 14!) z = z * y / FIXED_1; res += z * 0x00000000001c6380; // add y^15 * (20! / 15!) z = z * y / FIXED_1; res += z * 0x000000000001c638; // add y^16 * (20! / 16!) z = z * y / FIXED_1; res += z * 0x0000000000001ab8; // add y^17 * (20! / 17!) z = z * y / FIXED_1; res += z * 0x000000000000017c; // add y^18 * (20! / 18!) z = z * y / FIXED_1; res += z * 0x0000000000000014; // add y^19 * (20! / 19!) z = z * y / FIXED_1; res += z * 0x0000000000000001; // add y^20 * (20! / 20!) res = res / 0x21c3677c82b40000 + y + FIXED_1; // divide by 20! and then add y^1 / 1! + y^0 / 0! if ((x & 0x010000000000000000000000000000000) != 0) res = res * 0x1c3d6a24ed82218787d624d3e5eba95f9 / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^2^(-3) if ((x & 0x020000000000000000000000000000000) != 0) res = res * 0x18ebef9eac820ae8682b9793ac6d1e778 / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^2^(-2) if ((x & 0x040000000000000000000000000000000) != 0) res = res * 0x1368b2fc6f9609fe7aceb46aa619baed5 / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^2^(-1) if ((x & 0x080000000000000000000000000000000) != 0) res = res * 0x0bc5ab1b16779be3575bd8f0520a9f21e / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^2^(+0) if ((x & 0x100000000000000000000000000000000) != 0) res = res * 0x0454aaa8efe072e7f6ddbab84b40a55c5 / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^2^(+1) if ((x & 0x200000000000000000000000000000000) != 0) res = res * 0x00960aadc109e7a3bf4578099615711d7 / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^2^(+2) if ((x & 0x400000000000000000000000000000000) != 0) res = res * 0x0002bf84208204f5977f9a8cf01fdc307 / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^2^(+3) return res; } } // File: @ablack/fundraising-shared-interfaces/contracts/IAragonFundraisingController.sol pragma solidity 0.4.24; contract IAragonFundraisingController { function openTrading() external; function updateTappedAmount(address _token) external; function collateralsToBeClaimed(address _collateral) public view returns (uint256); function balanceOf(address _who, address _token) public view returns (uint256); } // File: @ablack/fundraising-batched-bancor-market-maker/contracts/BatchedBancorMarketMaker.sol pragma solidity 0.4.24; contract BatchedBancorMarketMaker is EtherTokenConstant, IsContract, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE"); bytes32 public constant UPDATE_FORMULA_ROLE = keccak256("UPDATE_FORMULA_ROLE"); bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE"); bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE"); bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE"); bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE"); */ bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4; bytes32 public constant UPDATE_FORMULA_ROLE = 0xbfb76d8d43f55efe58544ea32af187792a7bdb983850d8fed33478266eec3cbb; bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822; bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = 0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d; bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = 0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2; bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = 0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d; bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7; bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0; uint256 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18 uint32 public constant PPM = 1000000; string private constant ERROR_CONTRACT_IS_EOA = "MM_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "MM_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_BATCH_BLOCKS = "MM_INVALID_BATCH_BLOCKS"; string private constant ERROR_INVALID_PERCENTAGE = "MM_INVALID_PERCENTAGE"; string private constant ERROR_INVALID_RESERVE_RATIO = "MM_INVALID_RESERVE_RATIO"; string private constant ERROR_INVALID_TM_SETTING = "MM_INVALID_TM_SETTING"; string private constant ERROR_INVALID_COLLATERAL = "MM_INVALID_COLLATERAL"; string private constant ERROR_INVALID_COLLATERAL_VALUE = "MM_INVALID_COLLATERAL_VALUE"; string private constant ERROR_INVALID_BOND_AMOUNT = "MM_INVALID_BOND_AMOUNT"; string private constant ERROR_ALREADY_OPEN = "MM_ALREADY_OPEN"; string private constant ERROR_NOT_OPEN = "MM_NOT_OPEN"; string private constant ERROR_COLLATERAL_ALREADY_WHITELISTED = "MM_COLLATERAL_ALREADY_WHITELISTED"; string private constant ERROR_COLLATERAL_NOT_WHITELISTED = "MM_COLLATERAL_NOT_WHITELISTED"; string private constant ERROR_NOTHING_TO_CLAIM = "MM_NOTHING_TO_CLAIM"; string private constant ERROR_BATCH_NOT_OVER = "MM_BATCH_NOT_OVER"; string private constant ERROR_BATCH_CANCELLED = "MM_BATCH_CANCELLED"; string private constant ERROR_BATCH_NOT_CANCELLED = "MM_BATCH_NOT_CANCELLED"; string private constant ERROR_SLIPPAGE_EXCEEDS_LIMIT = "MM_SLIPPAGE_EXCEEDS_LIMIT"; string private constant ERROR_INSUFFICIENT_POOL_BALANCE = "MM_INSUFFICIENT_POOL_BALANCE"; string private constant ERROR_TRANSFER_FROM_FAILED = "MM_TRANSFER_FROM_FAILED"; struct Collateral { bool whitelisted; uint256 virtualSupply; uint256 virtualBalance; uint32 reserveRatio; uint256 slippage; } struct MetaBatch { bool initialized; uint256 realSupply; uint256 buyFeePct; uint256 sellFeePct; IBancorFormula formula; mapping(address => Batch) batches; } struct Batch { bool initialized; bool cancelled; uint256 supply; uint256 balance; uint32 reserveRatio; uint256 slippage; uint256 totalBuySpend; uint256 totalBuyReturn; uint256 totalSellSpend; uint256 totalSellReturn; mapping(address => uint256) buyers; mapping(address => uint256) sellers; } IAragonFundraisingController public controller; TokenManager public tokenManager; ERC20 public token; Vault public reserve; address public beneficiary; IBancorFormula public formula; uint256 public batchBlocks; uint256 public buyFeePct; uint256 public sellFeePct; bool public isOpen; uint256 public tokensToBeMinted; mapping(address => uint256) public collateralsToBeClaimed; mapping(address => Collateral) public collaterals; mapping(uint256 => MetaBatch) public metaBatches; event UpdateBeneficiary (address indexed beneficiary); event UpdateFormula (address indexed formula); event UpdateFees (uint256 buyFeePct, uint256 sellFeePct); event NewMetaBatch (uint256 indexed id, uint256 supply, uint256 buyFeePct, uint256 sellFeePct, address formula); event NewBatch ( uint256 indexed id, address indexed collateral, uint256 supply, uint256 balance, uint32 reserveRatio, uint256 slippage) ; event CancelBatch (uint256 indexed id, address indexed collateral); event AddCollateralToken ( address indexed collateral, uint256 virtualSupply, uint256 virtualBalance, uint32 reserveRatio, uint256 slippage ); event RemoveCollateralToken (address indexed collateral); event UpdateCollateralToken ( address indexed collateral, uint256 virtualSupply, uint256 virtualBalance, uint32 reserveRatio, uint256 slippage ); event Open (); event OpenBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value); event OpenSellOrder (address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount); event ClaimBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 amount); event ClaimSellOrder (address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 fee, uint256 value); event ClaimCancelledBuyOrder (address indexed buyer, uint256 indexed batchId, address indexed collateral, uint256 value); event ClaimCancelledSellOrder(address indexed seller, uint256 indexed batchId, address indexed collateral, uint256 amount); event UpdatePricing ( uint256 indexed batchId, address indexed collateral, uint256 totalBuySpend, uint256 totalBuyReturn, uint256 totalSellSpend, uint256 totalSellReturn ); /***** external function *****/ /** * @notice Initialize market maker * @param _controller The address of the controller contract * @param _tokenManager The address of the [bonded token] token manager contract * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom fees are to be sent] * @param _formula The address of the BancorFormula [computation] contract * @param _batchBlocks The number of blocks batches are to last * @param _buyFeePct The fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The fee to be deducted from sell orders [in PCT_BASE] */ function initialize( IAragonFundraisingController _controller, TokenManager _tokenManager, IBancorFormula _formula, Vault _reserve, address _beneficiary, uint256 _batchBlocks, uint256 _buyFeePct, uint256 _sellFeePct ) external onlyInit { initialized(); require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_tokenManager), ERROR_CONTRACT_IS_EOA); require(isContract(_formula), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); require(_batchBlocks > 0, ERROR_INVALID_BATCH_BLOCKS); require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE); require(_tokenManagerSettingIsValid(_tokenManager), ERROR_INVALID_TM_SETTING); controller = _controller; tokenManager = _tokenManager; token = ERC20(tokenManager.token()); formula = _formula; reserve = _reserve; beneficiary = _beneficiary; batchBlocks = _batchBlocks; buyFeePct = _buyFeePct; sellFeePct = _sellFeePct; } /* generic settings related function */ /** * @notice Open market making [enabling users to open buy and sell orders] */ function open() external auth(OPEN_ROLE) { require(!isOpen, ERROR_ALREADY_OPEN); _open(); } /** * @notice Update formula to `_formula` * @param _formula The address of the new BancorFormula [computation] contract */ function updateFormula(IBancorFormula _formula) external auth(UPDATE_FORMULA_ROLE) { require(isContract(_formula), ERROR_CONTRACT_IS_EOA); _updateFormula(_formula); } /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary [to whom fees are to be sent] */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); _updateBeneficiary(_beneficiary); } /** * @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`% * @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE] */ function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) { require(_feeIsValid(_buyFeePct) && _feeIsValid(_sellFeePct), ERROR_INVALID_PERCENTAGE); _updateFees(_buyFeePct, _sellFeePct); } /* collateral tokens related functions */ /** * @notice Add `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each batch is to be kept for that collateral token [in PCT_BASE] */ function addCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage) external auth(ADD_COLLATERAL_TOKEN_ROLE) { require(isContract(_collateral) || _collateral == ETH, ERROR_INVALID_COLLATERAL); require(!_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_ALREADY_WHITELISTED); require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO); _addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /** * @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be un-whitelisted */ function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); _removeCollateralToken(_collateral); } /** * @notice Update `_collateral.symbol(): string` collateralization settings * @param _collateral The address of the collateral token whose collateralization settings are to be updated * @param _virtualSupply The new virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The new virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM] * @param _slippage The new price slippage below which each batch is to be kept for that collateral token [in PCT_BASE] */ function updateCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage) external auth(UPDATE_COLLATERAL_TOKEN_ROLE) { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_reserveRatioIsValid(_reserveRatio), ERROR_INVALID_RESERVE_RATIO); _updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /* market making related functions */ /** * @notice Open a buy order worth `@tokenAmount(_collateral, _value)` * @param _buyer The address of the buyer * @param _collateral The address of the collateral token to be spent * @param _value The amount of collateral token to be spent */ function openBuyOrder(address _buyer, address _collateral, uint256 _value) external payable auth(OPEN_BUY_ORDER_ROLE) { require(isOpen, ERROR_NOT_OPEN); require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED); require(_collateralValueIsValid(_buyer, _collateral, _value, msg.value), ERROR_INVALID_COLLATERAL_VALUE); _openBuyOrder(_buyer, _collateral, _value); } /** * @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string` * @param _seller The address of the seller * @param _collateral The address of the collateral token to be returned * @param _amount The amount of bonded token to be spent */ function openSellOrder(address _seller, address _collateral, uint256 _amount) external auth(OPEN_SELL_ORDER_ROLE) { require(isOpen, ERROR_NOT_OPEN); require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(!_batchIsCancelled(_currentBatchId(), _collateral), ERROR_BATCH_CANCELLED); require(_bondAmountIsValid(_seller, _amount), ERROR_INVALID_BOND_AMOUNT); _openSellOrder(_seller, _collateral, _amount); } /** * @notice Claim the results of `_buyer`'s `_collateral.symbol(): string` buy orders from batch #`_batchId` * @param _buyer The address of the user whose buy orders are to be claimed * @param _batchId The id of the batch in which buy orders are to be claimed * @param _collateral The address of the collateral token against which buy orders are to be claimed */ function claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER); require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED); require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM); _claimBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the results of `_seller`'s `_collateral.symbol(): string` sell orders from batch #`_batchId` * @param _seller The address of the user whose sell orders are to be claimed * @param _batchId The id of the batch in which sell orders are to be claimed * @param _collateral The address of the collateral token against which sell orders are to be claimed */ function claimSellOrder(address _seller, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_collateralIsWhitelisted(_collateral), ERROR_COLLATERAL_NOT_WHITELISTED); require(_batchIsOver(_batchId), ERROR_BATCH_NOT_OVER); require(!_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_CANCELLED); require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM); _claimSellOrder(_seller, _batchId, _collateral); } /** * @notice Claim the investments of `_buyer`'s `_collateral.symbol(): string` buy orders from cancelled batch #`_batchId` * @param _buyer The address of the user whose cancelled buy orders are to be claimed * @param _batchId The id of the batch in which cancelled buy orders are to be claimed * @param _collateral The address of the collateral token against which cancelled buy orders are to be claimed */ function claimCancelledBuyOrder(address _buyer, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED); require(_userIsBuyer(_batchId, _collateral, _buyer), ERROR_NOTHING_TO_CLAIM); _claimCancelledBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the investments of `_seller`'s `_collateral.symbol(): string` sell orders from cancelled batch #`_batchId` * @param _seller The address of the user whose cancelled sell orders are to be claimed * @param _batchId The id of the batch in which cancelled sell orders are to be claimed * @param _collateral The address of the collateral token against which cancelled sell orders are to be claimed */ function claimCancelledSellOrder(address _seller, uint256 _batchId, address _collateral) external nonReentrant isInitialized { require(_batchIsCancelled(_batchId, _collateral), ERROR_BATCH_NOT_CANCELLED); require(_userIsSeller(_batchId, _collateral, _seller), ERROR_NOTHING_TO_CLAIM); _claimCancelledSellOrder(_seller, _batchId, _collateral); } /***** public view functions *****/ function getCurrentBatchId() public view isInitialized returns (uint256) { return _currentBatchId(); } function getCollateralToken(address _collateral) public view isInitialized returns (bool, uint256, uint256, uint32, uint256) { Collateral storage collateral = collaterals[_collateral]; return (collateral.whitelisted, collateral.virtualSupply, collateral.virtualBalance, collateral.reserveRatio, collateral.slippage); } function getBatch(uint256 _batchId, address _collateral) public view isInitialized returns (bool, bool, uint256, uint256, uint32, uint256, uint256, uint256, uint256, uint256) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return ( batch.initialized, batch.cancelled, batch.supply, batch.balance, batch.reserveRatio, batch.slippage, batch.totalBuySpend, batch.totalBuyReturn, batch.totalSellSpend, batch.totalSellReturn ); } function getStaticPricePPM(uint256 _supply, uint256 _balance, uint32 _reserveRatio) public view isInitialized returns (uint256) { return _staticPricePPM(_supply, _balance, _reserveRatio); } /***** internal functions *****/ /* computation functions */ function _staticPricePPM(uint256 _supply, uint256 _balance, uint32 _reserveRatio) internal pure returns (uint256) { return uint256(PPM).mul(uint256(PPM)).mul(_balance).div(_supply.mul(uint256(_reserveRatio))); } function _currentBatchId() internal view returns (uint256) { return (block.number.div(batchBlocks)).mul(batchBlocks); } /* check functions */ function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) { return _beneficiary != address(0); } function _feeIsValid(uint256 _fee) internal pure returns (bool) { return _fee < PCT_BASE; } function _reserveRatioIsValid(uint32 _reserveRatio) internal pure returns (bool) { return _reserveRatio <= PPM; } function _tokenManagerSettingIsValid(TokenManager _tokenManager) internal view returns (bool) { return _tokenManager.maxAccountTokens() == uint256(-1); } function _collateralValueIsValid(address _buyer, address _collateral, uint256 _value, uint256 _msgValue) internal view returns (bool) { if (_value == 0) { return false; } if (_collateral == ETH) { return _msgValue == _value; } return ( _msgValue == 0 && controller.balanceOf(_buyer, _collateral) >= _value && ERC20(_collateral).allowance(_buyer, address(this)) >= _value ); } function _bondAmountIsValid(address _seller, uint256 _amount) internal view returns (bool) { return _amount != 0 && tokenManager.spendableBalanceOf(_seller) >= _amount; } function _collateralIsWhitelisted(address _collateral) internal view returns (bool) { return collaterals[_collateral].whitelisted; } function _batchIsOver(uint256 _batchId) internal view returns (bool) { return _batchId < _currentBatchId(); } function _batchIsCancelled(uint256 _batchId, address _collateral) internal view returns (bool) { return metaBatches[_batchId].batches[_collateral].cancelled; } function _userIsBuyer(uint256 _batchId, address _collateral, address _user) internal view returns (bool) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return batch.buyers[_user] > 0; } function _userIsSeller(uint256 _batchId, address _collateral, address _user) internal view returns (bool) { Batch storage batch = metaBatches[_batchId].batches[_collateral]; return batch.sellers[_user] > 0; } function _poolBalanceIsSufficient(address _collateral) internal view returns (bool) { return controller.balanceOf(address(reserve), _collateral) >= collateralsToBeClaimed[_collateral]; } function _slippageIsValid(Batch storage _batch, address _collateral) internal view returns (bool) { uint256 staticPricePPM = _staticPricePPM(_batch.supply, _batch.balance, _batch.reserveRatio); uint256 maximumSlippage = _batch.slippage; // if static price is zero let's consider that every slippage is valid if (staticPricePPM == 0) { return true; } return _buySlippageIsValid(_batch, staticPricePPM, maximumSlippage) && _sellSlippageIsValid(_batch, staticPricePPM, maximumSlippage); } function _buySlippageIsValid(Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage) internal view returns (bool) { /** * NOTE * the case where starting price is zero is handled * in the meta function _slippageIsValid() */ /** * NOTE * slippage is valid if: * totalBuyReturn >= totalBuySpend / (startingPrice * (1 + maxSlippage)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (1 + maximumSlippage / PCT_BASE)) * totalBuyReturn >= totalBuySpend / ((startingPricePPM / PPM) * (PCT + maximumSlippage) / PCT_BASE) * totalBuyReturn * startingPrice * ( PCT + maximumSlippage) >= totalBuySpend * PCT_BASE * PPM */ if ( _batch.totalBuyReturn.mul(_startingPricePPM).mul(PCT_BASE.add(_maximumSlippage)) >= _batch.totalBuySpend.mul(PCT_BASE).mul(uint256(PPM)) ) { return true; } return false; } function _sellSlippageIsValid(Batch storage _batch, uint256 _startingPricePPM, uint256 _maximumSlippage) internal view returns (bool) { /** * NOTE * the case where starting price is zero is handled * in the meta function _slippageIsValid() */ // if allowed sell slippage >= 100% // then any sell slippage is valid if (_maximumSlippage >= PCT_BASE) { return true; } /** * NOTE * slippage is valid if * totalSellReturn >= startingPrice * (1 - maxSlippage) * totalBuySpend * totalSellReturn >= (startingPricePPM / PPM) * (1 - maximumSlippage / PCT_BASE) * totalBuySpend * totalSellReturn >= (startingPricePPM / PPM) * (PCT_BASE - maximumSlippage) * totalBuySpend / PCT_BASE * totalSellReturn * PCT_BASE * PPM = startingPricePPM * (PCT_BASE - maximumSlippage) * totalBuySpend */ if ( _batch.totalSellReturn.mul(PCT_BASE).mul(uint256(PPM)) >= _startingPricePPM.mul(PCT_BASE.sub(_maximumSlippage)).mul(_batch.totalSellSpend) ) { return true; } return false; } /* initialization functions */ function _currentBatch(address _collateral) internal returns (uint256, Batch storage) { uint256 batchId = _currentBatchId(); MetaBatch storage metaBatch = metaBatches[batchId]; Batch storage batch = metaBatch.batches[_collateral]; if (!metaBatch.initialized) { /** * NOTE * all collateral batches should be initialized with the same supply to * avoid price manipulation between different collaterals in the same meta-batch * we don't need to do the same with collateral balances as orders against one collateral * can't affect the pool's balance against another collateral and tap is a step-function * of the meta-batch duration */ /** * NOTE * realSupply(metaBatch) = totalSupply(metaBatchInitialization) + tokensToBeMinted(metaBatchInitialization) * 1. buy and sell orders incoming during the current meta-batch and affecting totalSupply or tokensToBeMinted * should not be taken into account in the price computation [they are already a part of the batched pricing computation] * 2. the only way for totalSupply to be modified during a meta-batch [outside of incoming buy and sell orders] * is for buy orders from previous meta-batches to be claimed [and tokens to be minted]: * as such totalSupply(metaBatch) + tokenToBeMinted(metaBatch) will always equal totalSupply(metaBatchInitialization) + tokenToBeMinted(metaBatchInitialization) */ metaBatch.realSupply = token.totalSupply().add(tokensToBeMinted); metaBatch.buyFeePct = buyFeePct; metaBatch.sellFeePct = sellFeePct; metaBatch.formula = formula; metaBatch.initialized = true; emit NewMetaBatch(batchId, metaBatch.realSupply, metaBatch.buyFeePct, metaBatch.sellFeePct, metaBatch.formula); } if (!batch.initialized) { /** * NOTE * supply(batch) = realSupply(metaBatch) + virtualSupply(batchInitialization) * virtualSupply can technically be updated during a batch: the on-going batch will still use * its value at the time of initialization [it's up to the updater to act wisely] */ /** * NOTE * balance(batch) = poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization) + virtualBalance(metaBatchInitialization) * 1. buy and sell orders incoming during the current batch and affecting poolBalance or collateralsToBeClaimed * should not be taken into account in the price computation [they are already a part of the batched price computation] * 2. the only way for poolBalance to be modified during a batch [outside of incoming buy and sell orders] * is for sell orders from previous meta-batches to be claimed [and collateral to be transfered] as the tap is a step-function of the meta-batch duration: * as such poolBalance(batch) - collateralsToBeClaimed(batch) will always equal poolBalance(batchInitialization) - collateralsToBeClaimed(batchInitialization) * 3. virtualBalance can technically be updated during a batch: the on-going batch will still use * its value at the time of initialization [it's up to the updater to act wisely] */ controller.updateTappedAmount(_collateral); batch.supply = metaBatch.realSupply.add(collaterals[_collateral].virtualSupply); batch.balance = controller.balanceOf(address(reserve), _collateral).add(collaterals[_collateral].virtualBalance).sub(collateralsToBeClaimed[_collateral]); batch.reserveRatio = collaterals[_collateral].reserveRatio; batch.slippage = collaterals[_collateral].slippage; batch.initialized = true; emit NewBatch(batchId, _collateral, batch.supply, batch.balance, batch.reserveRatio, batch.slippage); } return (batchId, batch); } /* state modifiying functions */ function _open() internal { isOpen = true; emit Open(); } function _updateBeneficiary(address _beneficiary) internal { beneficiary = _beneficiary; emit UpdateBeneficiary(_beneficiary); } function _updateFormula(IBancorFormula _formula) internal { formula = _formula; emit UpdateFormula(address(_formula)); } function _updateFees(uint256 _buyFeePct, uint256 _sellFeePct) internal { buyFeePct = _buyFeePct; sellFeePct = _sellFeePct; emit UpdateFees(_buyFeePct, _sellFeePct); } function _cancelCurrentBatch(address _collateral) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); if (!batch.cancelled) { batch.cancelled = true; // bought bonds are cancelled but sold bonds are due back // bought collaterals are cancelled but sold collaterals are due back tokensToBeMinted = tokensToBeMinted.sub(batch.totalBuyReturn).add(batch.totalSellSpend); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].add(batch.totalBuySpend).sub(batch.totalSellReturn); emit CancelBatch(batchId, _collateral); } } function _addCollateralToken(address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage) internal { collaterals[_collateral].whitelisted = true; collaterals[_collateral].virtualSupply = _virtualSupply; collaterals[_collateral].virtualBalance = _virtualBalance; collaterals[_collateral].reserveRatio = _reserveRatio; collaterals[_collateral].slippage = _slippage; emit AddCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } function _removeCollateralToken(address _collateral) internal { _cancelCurrentBatch(_collateral); Collateral storage collateral = collaterals[_collateral]; delete collateral.whitelisted; delete collateral.virtualSupply; delete collateral.virtualBalance; delete collateral.reserveRatio; delete collateral.slippage; emit RemoveCollateralToken(_collateral); } function _updateCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) internal { collaterals[_collateral].virtualSupply = _virtualSupply; collaterals[_collateral].virtualBalance = _virtualBalance; collaterals[_collateral].reserveRatio = _reserveRatio; collaterals[_collateral].slippage = _slippage; emit UpdateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } function _openBuyOrder(address _buyer, address _collateral, uint256 _value) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); // deduct fee uint256 fee = _value.mul(metaBatches[batchId].buyFeePct).div(PCT_BASE); uint256 value = _value.sub(fee); // collect fee and collateral if (fee > 0) { _transfer(_buyer, beneficiary, _collateral, fee); } _transfer(_buyer, address(reserve), _collateral, value); // save batch uint256 deprecatedBuyReturn = batch.totalBuyReturn; uint256 deprecatedSellReturn = batch.totalSellReturn; // update batch batch.totalBuySpend = batch.totalBuySpend.add(value); batch.buyers[_buyer] = batch.buyers[_buyer].add(value); // update pricing _updatePricing(batch, batchId, _collateral); // update the amount of tokens to be minted and collaterals to be claimed tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add(batch.totalSellReturn); // sanity checks require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT); emit OpenBuyOrder(_buyer, batchId, _collateral, fee, value); } function _openSellOrder(address _seller, address _collateral, uint256 _amount) internal { (uint256 batchId, Batch storage batch) = _currentBatch(_collateral); // burn bonds tokenManager.burn(_seller, _amount); // save batch uint256 deprecatedBuyReturn = batch.totalBuyReturn; uint256 deprecatedSellReturn = batch.totalSellReturn; // update batch batch.totalSellSpend = batch.totalSellSpend.add(_amount); batch.sellers[_seller] = batch.sellers[_seller].add(_amount); // update pricing _updatePricing(batch, batchId, _collateral); // update the amount of tokens to be minted and collaterals to be claimed tokensToBeMinted = tokensToBeMinted.sub(deprecatedBuyReturn).add(batch.totalBuyReturn); collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(deprecatedSellReturn).add(batch.totalSellReturn); // sanity checks require(_slippageIsValid(batch, _collateral), ERROR_SLIPPAGE_EXCEEDS_LIMIT); require(_poolBalanceIsSufficient(_collateral), ERROR_INSUFFICIENT_POOL_BALANCE); emit OpenSellOrder(_seller, batchId, _collateral, _amount); } function _claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 buyReturn = (batch.buyers[_buyer].mul(batch.totalBuyReturn)).div(batch.totalBuySpend); batch.buyers[_buyer] = 0; if (buyReturn > 0) { tokensToBeMinted = tokensToBeMinted.sub(buyReturn); tokenManager.mint(_buyer, buyReturn); } emit ClaimBuyOrder(_buyer, _batchId, _collateral, buyReturn); } function _claimSellOrder(address _seller, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 saleReturn = (batch.sellers[_seller].mul(batch.totalSellReturn)).div(batch.totalSellSpend); uint256 fee = saleReturn.mul(metaBatches[_batchId].sellFeePct).div(PCT_BASE); uint256 value = saleReturn.sub(fee); batch.sellers[_seller] = 0; if (value > 0) { collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(saleReturn); reserve.transfer(_collateral, _seller, value); } if (fee > 0) { reserve.transfer(_collateral, beneficiary, fee); } emit ClaimSellOrder(_seller, _batchId, _collateral, fee, value); } function _claimCancelledBuyOrder(address _buyer, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 value = batch.buyers[_buyer]; batch.buyers[_buyer] = 0; if (value > 0) { collateralsToBeClaimed[_collateral] = collateralsToBeClaimed[_collateral].sub(value); reserve.transfer(_collateral, _buyer, value); } emit ClaimCancelledBuyOrder(_buyer, _batchId, _collateral, value); } function _claimCancelledSellOrder(address _seller, uint256 _batchId, address _collateral) internal { Batch storage batch = metaBatches[_batchId].batches[_collateral]; uint256 amount = batch.sellers[_seller]; batch.sellers[_seller] = 0; if (amount > 0) { tokensToBeMinted = tokensToBeMinted.sub(amount); tokenManager.mint(_seller, amount); } emit ClaimCancelledSellOrder(_seller, _batchId, _collateral, amount); } function _updatePricing(Batch storage batch, uint256 _batchId, address _collateral) internal { // the situation where there are no buy nor sell orders can't happen [keep commented] // if (batch.totalSellSpend == 0 && batch.totalBuySpend == 0) // return; // static price is the current exact price in collateral // per token according to the initial state of the batch // [expressed in PPM for precision sake] uint256 staticPricePPM = _staticPricePPM(batch.supply, batch.balance, batch.reserveRatio); // [NOTE] // if staticPrice is zero then resultOfSell [= 0] <= batch.totalBuySpend // so totalSellReturn will be zero and totalBuyReturn will be // computed normally along the formula // 1. we want to find out if buy orders are worth more sell orders [or vice-versa] // 2. we thus check the return of sell orders at the current exact price // 3. if the return of sell orders is larger than the pending buys, // there are more sells than buys [and vice-versa] uint256 resultOfSell = batch.totalSellSpend.mul(staticPricePPM).div(uint256(PPM)); if (resultOfSell > batch.totalBuySpend) { // >> sell orders are worth more than buy orders // 1. first we execute all pending buy orders at the current exact // price because there is at least one sell order for each buy order // 2. then the final sell return is the addition of this first // matched return with the remaining bonding curve return // the number of tokens bought as a result of all buy orders matched at the // current exact price [which is less than the total amount of tokens to be sold] batch.totalBuyReturn = batch.totalBuySpend.mul(uint256(PPM)).div(staticPricePPM); // the number of tokens left over to be sold along the curve which is the difference // between the original total sell order and the result of all the buy orders uint256 remainingSell = batch.totalSellSpend.sub(batch.totalBuyReturn); // the amount of collateral generated by selling tokens left over to be sold // along the bonding curve in the batch initial state [as if the buy orders // never existed and the sell order was just smaller than originally thought] uint256 remainingSellReturn = metaBatches[_batchId].formula.calculateSaleReturn(batch.supply, batch.balance, batch.reserveRatio, remainingSell); // the total result of all sells is the original amount of buys which were matched // plus the remaining sells which were executed along the bonding curve batch.totalSellReturn = batch.totalBuySpend.add(remainingSellReturn); } else { // >> buy orders are worth more than sell orders // 1. first we execute all pending sell orders at the current exact // price because there is at least one buy order for each sell order // 2. then the final buy return is the addition of this first // matched return with the remaining bonding curve return // the number of collaterals bought as a result of all sell orders matched at the // current exact price [which is less than the total amount of collateral to be spent] batch.totalSellReturn = resultOfSell; // the number of collaterals left over to be spent along the curve which is the difference // between the original total buy order and the result of all the sell orders uint256 remainingBuy = batch.totalBuySpend.sub(resultOfSell); // the amount of tokens generated by selling collaterals left over to be spent // along the bonding curve in the batch initial state [as if the sell orders // never existed and the buy order was just smaller than originally thought] uint256 remainingBuyReturn = metaBatches[_batchId].formula.calculatePurchaseReturn(batch.supply, batch.balance, batch.reserveRatio, remainingBuy); // the total result of all buys is the original amount of buys which were matched // plus the remaining buys which were executed along the bonding curve batch.totalBuyReturn = batch.totalSellSpend.add(remainingBuyReturn); } emit UpdatePricing(_batchId, _collateral, batch.totalBuySpend, batch.totalBuyReturn, batch.totalSellSpend, batch.totalSellReturn); } function _transfer(address _from, address _to, address _collateralToken, uint256 _amount) internal { if (_collateralToken == ETH) { _to.transfer(_amount); } else { require(ERC20(_collateralToken).safeTransferFrom(_from, _to, _amount), ERROR_TRANSFER_FROM_FAILED); } } } // File: @ablack/fundraising-shared-interfaces/contracts/IPresale.sol pragma solidity 0.4.24; contract IPresale { function open() external; function close() external; function contribute(address _contributor, uint256 _value) external payable; function refund(address _contributor, uint256 _vestedPurchaseId) external; function contributionToTokens(uint256 _value) public view returns (uint256); function contributionToken() public view returns (address); } // File: @ablack/fundraising-shared-interfaces/contracts/ITap.sol pragma solidity 0.4.24; contract ITap { function updateBeneficiary(address _beneficiary) external; function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external; function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external; function addTappedToken(address _token, uint256 _rate, uint256 _floor) external; function updateTappedToken(address _token, uint256 _rate, uint256 _floor) external; function resetTappedToken(address _token) external; function updateTappedAmount(address _token) external; function withdraw(address _token) external; function getMaximumWithdrawal(address _token) public view returns (uint256); function rates(address _token) public view returns (uint256); } // File: @ablack/fundraising-aragon-fundraising/contracts/AragonFundraisingController.sol pragma solidity 0.4.24; contract AragonFundraisingController is EtherTokenConstant, IsContract, IAragonFundraisingController, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_FEES_ROLE = keccak256("UPDATE_FEES_ROLE"); bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = keccak256("ADD_COLLATERAL_TOKEN_ROLE"); bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = keccak256("REMOVE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = keccak256("UPDATE_COLLATERAL_TOKEN_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE"); bytes32 public constant ADD_TOKEN_TAP_ROLE = keccak256("ADD_TOKEN_TAP_ROLE"); bytes32 public constant UPDATE_TOKEN_TAP_ROLE = keccak256("UPDATE_TOKEN_TAP_ROLE"); bytes32 public constant OPEN_PRESALE_ROLE = keccak256("OPEN_PRESALE_ROLE"); bytes32 public constant OPEN_TRADING_ROLE = keccak256("OPEN_TRADING_ROLE"); bytes32 public constant CONTRIBUTE_ROLE = keccak256("CONTRIBUTE_ROLE"); bytes32 public constant OPEN_BUY_ORDER_ROLE = keccak256("OPEN_BUY_ORDER_ROLE"); bytes32 public constant OPEN_SELL_ORDER_ROLE = keccak256("OPEN_SELL_ORDER_ROLE"); bytes32 public constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE"); */ bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_FEES_ROLE = 0x5f9be2932ed3a723f295a763be1804c7ebfd1a41c1348fb8bdf5be1c5cdca822; bytes32 public constant ADD_COLLATERAL_TOKEN_ROLE = 0x217b79cb2bc7760defc88529853ef81ab33ae5bb315408ce9f5af09c8776662d; bytes32 public constant REMOVE_COLLATERAL_TOKEN_ROLE = 0x2044e56de223845e4be7d0a6f4e9a29b635547f16413a6d1327c58d9db438ee2; bytes32 public constant UPDATE_COLLATERAL_TOKEN_ROLE = 0xe0565c2c43e0d841e206bb36a37f12f22584b4652ccee6f9e0c071b697a2e13d; bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = 0x5d94de7e429250eee4ff97e30ab9f383bea3cd564d6780e0a9e965b1add1d207; bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = 0x57c9c67896cf0a4ffe92cbea66c2f7c34380af06bf14215dabb078cf8a6d99e1; bytes32 public constant ADD_TOKEN_TAP_ROLE = 0xbc9cb5e3f7ce81c4fd021d86a4bcb193dee9df315b540808c3ed59a81e596207; bytes32 public constant UPDATE_TOKEN_TAP_ROLE = 0xdb8c88bedbc61ea0f92e1ce46da0b7a915affbd46d1c76c4bbac9a209e4a8416; bytes32 public constant OPEN_PRESALE_ROLE = 0xf323aa41eef4850a8ae7ebd047d4c89f01ce49c781f3308be67303db9cdd48c2; bytes32 public constant OPEN_TRADING_ROLE = 0x26ce034204208c0bbca4c8a793d17b99e546009b1dd31d3c1ef761f66372caf6; bytes32 public constant CONTRIBUTE_ROLE = 0x9ccaca4edf2127f20c425fdd86af1ba178b9e5bee280cd70d88ac5f6874c4f07; bytes32 public constant OPEN_BUY_ORDER_ROLE = 0xa589c8f284b76fc8d510d9d553485c47dbef1b0745ae00e0f3fd4e28fcd77ea7; bytes32 public constant OPEN_SELL_ORDER_ROLE = 0xd68ba2b769fa37a2a7bd4bed9241b448bc99eca41f519ef037406386a8f291c0; bytes32 public constant WITHDRAW_ROLE = 0x5d8e12c39142ff96d79d04d15d1ba1269e4fe57bb9d26f43523628b34ba108ec; uint256 public constant TO_RESET_CAP = 10; string private constant ERROR_CONTRACT_IS_EOA = "FUNDRAISING_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_TOKENS = "FUNDRAISING_INVALID_TOKENS"; IPresale public presale; BatchedBancorMarketMaker public marketMaker; Agent public reserve; ITap public tap; address[] public toReset; /***** external functions *****/ /** * @notice Initialize Aragon Fundraising controller * @param _presale The address of the presale contract * @param _marketMaker The address of the market maker contract * @param _reserve The address of the reserve [pool] contract * @param _tap The address of the tap contract * @param _toReset The addresses of the tokens whose tap timestamps are to be reset [when presale is closed and trading is open] */ function initialize( IPresale _presale, BatchedBancorMarketMaker _marketMaker, Agent _reserve, ITap _tap, address[] _toReset ) external onlyInit { require(isContract(_presale), ERROR_CONTRACT_IS_EOA); require(isContract(_marketMaker), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(isContract(_tap), ERROR_CONTRACT_IS_EOA); require(_toReset.length < TO_RESET_CAP, ERROR_INVALID_TOKENS); initialized(); presale = _presale; marketMaker = _marketMaker; reserve = _reserve; tap = _tap; for (uint256 i = 0; i < _toReset.length; i++) { require(_tokenIsContractOrETH(_toReset[i]), ERROR_INVALID_TOKENS); toReset.push(_toReset[i]); } } /* generic settings related function */ /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { marketMaker.updateBeneficiary(_beneficiary); tap.updateBeneficiary(_beneficiary); } /** * @notice Update fees deducted from buy and sell orders to respectively `@formatPct(_buyFeePct)`% and `@formatPct(_sellFeePct)`% * @param _buyFeePct The new fee to be deducted from buy orders [in PCT_BASE] * @param _sellFeePct The new fee to be deducted from sell orders [in PCT_BASE] */ function updateFees(uint256 _buyFeePct, uint256 _sellFeePct) external auth(UPDATE_FEES_ROLE) { marketMaker.updateFees(_buyFeePct, _sellFeePct); } /* presale related functions */ /** * @notice Open presale */ function openPresale() external auth(OPEN_PRESALE_ROLE) { presale.open(); } /** * @notice Close presale and open trading */ function closePresale() external isInitialized { presale.close(); } /** * @notice Contribute to the presale up to `@tokenAmount(self.contributionToken(): address, _value)` * @param _value The amount of contribution token to be spent */ function contribute(uint256 _value) external payable auth(CONTRIBUTE_ROLE) { presale.contribute.value(msg.value)(msg.sender, _value); } /** * @notice Refund `_contributor`'s presale contribution #`_vestedPurchaseId` * @param _contributor The address of the contributor whose presale contribution is to be refunded * @param _vestedPurchaseId The id of the contribution to be refunded */ function refund(address _contributor, uint256 _vestedPurchaseId) external isInitialized { presale.refund(_contributor, _vestedPurchaseId); } /* market making related functions */ /** * @notice Open trading [enabling users to open buy and sell orders] */ function openTrading() external auth(OPEN_TRADING_ROLE) { for (uint256 i = 0; i < toReset.length; i++) { if (tap.rates(toReset[i]) != uint256(0)) { tap.resetTappedToken(toReset[i]); } } marketMaker.open(); } /** * @notice Open a buy order worth `@tokenAmount(_collateral, _value)` * @param _collateral The address of the collateral token to be spent * @param _value The amount of collateral token to be spent */ function openBuyOrder(address _collateral, uint256 _value) external payable auth(OPEN_BUY_ORDER_ROLE) { marketMaker.openBuyOrder.value(msg.value)(msg.sender, _collateral, _value); } /** * @notice Open a sell order worth `@tokenAmount(self.token(): address, _amount)` against `_collateral.symbol(): string` * @param _collateral The address of the collateral token to be returned * @param _amount The amount of bonded token to be spent */ function openSellOrder(address _collateral, uint256 _amount) external auth(OPEN_SELL_ORDER_ROLE) { marketMaker.openSellOrder(msg.sender, _collateral, _amount); } /** * @notice Claim the results of `_collateral.symbol(): string` buy orders from batch #`_batchId` * @param _buyer The address of the user whose buy orders are to be claimed * @param _batchId The id of the batch in which buy orders are to be claimed * @param _collateral The address of the collateral token against which buy orders are to be claimed */ function claimBuyOrder(address _buyer, uint256 _batchId, address _collateral) external isInitialized { marketMaker.claimBuyOrder(_buyer, _batchId, _collateral); } /** * @notice Claim the results of `_collateral.symbol(): string` sell orders from batch #`_batchId` * @param _seller The address of the user whose sell orders are to be claimed * @param _batchId The id of the batch in which sell orders are to be claimed * @param _collateral The address of the collateral token against which sell orders are to be claimed */ function claimSellOrder(address _seller, uint256 _batchId, address _collateral) external isInitialized { marketMaker.claimSellOrder(_seller, _batchId, _collateral); } /* collateral tokens related functions */ /** * @notice Add `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE] * @param _rate The rate at which that token is to be tapped [in wei / block] * @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function addCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage, uint256 _rate, uint256 _floor ) external auth(ADD_COLLATERAL_TOKEN_ROLE) { marketMaker.addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); if (_collateral != ETH) { reserve.addProtectedToken(_collateral); } if (_rate > 0) { tap.addTappedToken(_collateral, _rate, _floor); } } /** * @notice Re-add `_collateral.symbol(): string` as a whitelisted collateral token [if it has been un-whitelisted in the past] * @param _collateral The address of the collateral token to be whitelisted * @param _virtualSupply The virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The reserve ratio to be used for that collateral token [in PPM] * @param _slippage The price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE] */ function reAddCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) external auth(ADD_COLLATERAL_TOKEN_ROLE) { marketMaker.addCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /** * @notice Remove `_collateral.symbol(): string` as a whitelisted collateral token * @param _collateral The address of the collateral token to be un-whitelisted */ function removeCollateralToken(address _collateral) external auth(REMOVE_COLLATERAL_TOKEN_ROLE) { marketMaker.removeCollateralToken(_collateral); // the token should still be tapped to avoid being locked // the token should still be protected to avoid being spent } /** * @notice Update `_collateral.symbol(): string` collateralization settings * @param _collateral The address of the collateral token whose collateralization settings are to be updated * @param _virtualSupply The new virtual supply to be used for that collateral token [in wei] * @param _virtualBalance The new virtual balance to be used for that collateral token [in wei] * @param _reserveRatio The new reserve ratio to be used for that collateral token [in PPM] * @param _slippage The new price slippage below which each market making batch is to be kept for that collateral token [in PCT_BASE] */ function updateCollateralToken( address _collateral, uint256 _virtualSupply, uint256 _virtualBalance, uint32 _reserveRatio, uint256 _slippage ) external auth(UPDATE_COLLATERAL_TOKEN_ROLE) { marketMaker.updateCollateralToken(_collateral, _virtualSupply, _virtualBalance, _reserveRatio, _slippage); } /* tap related functions */ /** * @notice Update maximum tap rate increase percentage to `@formatPct(_maximumTapRateIncreasePct)`% * @param _maximumTapRateIncreasePct The new maximum tap rate increase percentage to be allowed [in PCT_BASE] */ function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external auth(UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE) { tap.updateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct); } /** * @notice Update maximum tap floor decrease percentage to `@formatPct(_maximumTapFloorDecreasePct)`% * @param _maximumTapFloorDecreasePct The new maximum tap floor decrease percentage to be allowed [in PCT_BASE] */ function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external auth(UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE) { tap.updateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct); } /** * @notice Add tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token to be tapped * @param _rate The rate at which that token is to be tapped [in wei / block] * @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function addTokenTap(address _token, uint256 _rate, uint256 _floor) external auth(ADD_TOKEN_TAP_ROLE) { tap.addTappedToken(_token, _rate, _floor); } /** * @notice Update tap for `_token.symbol(): string` with a rate of about `@tokenAmount(_token, 4 * 60 * 24 * 30 * _rate)` per month and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token whose tap is to be updated * @param _rate The new rate at which that token is to be tapped [in wei / block] * @param _floor The new floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function updateTokenTap(address _token, uint256 _rate, uint256 _floor) external auth(UPDATE_TOKEN_TAP_ROLE) { tap.updateTappedToken(_token, _rate, _floor); } /** * @notice Update tapped amount for `_token.symbol(): string` * @param _token The address of the token whose tapped amount is to be updated */ function updateTappedAmount(address _token) external { tap.updateTappedAmount(_token); } /** * @notice Transfer about `@tokenAmount(_token, self.getMaximumWithdrawal(_token): uint256)` from the reserve to the beneficiary * @param _token The address of the token to be transfered from the reserve to the beneficiary */ function withdraw(address _token) external auth(WITHDRAW_ROLE) { tap.withdraw(_token); } /***** public view functions *****/ function token() public view isInitialized returns (address) { return marketMaker.token(); } function contributionToken() public view isInitialized returns (address) { return presale.contributionToken(); } function getMaximumWithdrawal(address _token) public view isInitialized returns (uint256) { return tap.getMaximumWithdrawal(_token); } function collateralsToBeClaimed(address _collateral) public view isInitialized returns (uint256) { return marketMaker.collateralsToBeClaimed(_collateral); } function balanceOf(address _who, address _token) public view isInitialized returns (uint256) { uint256 balance = _token == ETH ? _who.balance : ERC20(_token).staticBalanceOf(_who); if (_who == address(reserve)) { return balance.sub(tap.getMaximumWithdrawal(_token)); } else { return balance; } } /***** internal functions *****/ function _tokenIsContractOrETH(address _token) internal view returns (bool) { return isContract(_token) || _token == ETH; } } // File: @ablack/fundraising-presale/contracts/Presale.sol pragma solidity ^0.4.24; contract Presale is IPresale, EtherTokenConstant, IsContract, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; using SafeMath64 for uint64; /** Hardcoded constants to save gas bytes32 public constant OPEN_ROLE = keccak256("OPEN_ROLE"); bytes32 public constant CONTRIBUTE_ROLE = keccak256("CONTRIBUTE_ROLE"); */ bytes32 public constant OPEN_ROLE = 0xefa06053e2ca99a43c97c4a4f3d8a394ee3323a8ff237e625fba09fe30ceb0a4; bytes32 public constant CONTRIBUTE_ROLE = 0x9ccaca4edf2127f20c425fdd86af1ba178b9e5bee280cd70d88ac5f6874c4f07; uint256 public constant PPM = 1000000; // 0% = 0 * 10 ** 4; 1% = 1 * 10 ** 4; 100% = 100 * 10 ** 4 string private constant ERROR_CONTRACT_IS_EOA = "PRESALE_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "PRESALE_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_CONTRIBUTE_TOKEN = "PRESALE_INVALID_CONTRIBUTE_TOKEN"; string private constant ERROR_INVALID_GOAL = "PRESALE_INVALID_GOAL"; string private constant ERROR_INVALID_EXCHANGE_RATE = "PRESALE_INVALID_EXCHANGE_RATE"; string private constant ERROR_INVALID_TIME_PERIOD = "PRESALE_INVALID_TIME_PERIOD"; string private constant ERROR_INVALID_PCT = "PRESALE_INVALID_PCT"; string private constant ERROR_INVALID_STATE = "PRESALE_INVALID_STATE"; string private constant ERROR_INVALID_CONTRIBUTE_VALUE = "PRESALE_INVALID_CONTRIBUTE_VALUE"; string private constant ERROR_INSUFFICIENT_BALANCE = "PRESALE_INSUFFICIENT_BALANCE"; string private constant ERROR_INSUFFICIENT_ALLOWANCE = "PRESALE_INSUFFICIENT_ALLOWANCE"; string private constant ERROR_NOTHING_TO_REFUND = "PRESALE_NOTHING_TO_REFUND"; string private constant ERROR_TOKEN_TRANSFER_REVERTED = "PRESALE_TOKEN_TRANSFER_REVERTED"; enum State { Pending, // presale is idle and pending to be started Funding, // presale has started and contributors can purchase tokens Refunding, // presale has not reached goal within period and contributors can claim refunds GoalReached, // presale has reached goal within period and trading is ready to be open Closed // presale has reached goal within period, has been closed and trading has been open } IAragonFundraisingController public controller; TokenManager public tokenManager; ERC20 public token; address public reserve; address public beneficiary; address public contributionToken; uint256 public goal; uint64 public period; uint256 public exchangeRate; uint64 public vestingCliffPeriod; uint64 public vestingCompletePeriod; uint256 public supplyOfferedPct; uint256 public fundingForBeneficiaryPct; uint64 public openDate; bool public isClosed; uint64 public vestingCliffDate; uint64 public vestingCompleteDate; uint256 public totalRaised; mapping(address => mapping(uint256 => uint256)) public contributions; // contributor => (vestedPurchaseId => tokensSpent) event SetOpenDate (uint64 date); event Close (); event Contribute (address indexed contributor, uint256 value, uint256 amount, uint256 vestedPurchaseId); event Refund (address indexed contributor, uint256 value, uint256 amount, uint256 vestedPurchaseId); /***** external function *****/ /** * @notice Initialize presale * @param _controller The address of the controller contract * @param _tokenManager The address of the [bonded] token manager contract * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom a percentage of the raised funds is be to be sent] * @param _contributionToken The address of the token to be used to contribute * @param _goal The goal to be reached by the end of that presale [in contribution token wei] * @param _period The period within which to accept contribution for that presale * @param _exchangeRate The exchangeRate [= 1/price] at which [bonded] tokens are to be purchased for that presale [in PPM] * @param _vestingCliffPeriod The period during which purchased [bonded] tokens are to be cliffed * @param _vestingCompletePeriod The complete period during which purchased [bonded] tokens are to be vested * @param _supplyOfferedPct The percentage of the initial supply of [bonded] tokens to be offered during that presale [in PPM] * @param _fundingForBeneficiaryPct The percentage of the raised contribution tokens to be sent to the beneficiary [instead of the fundraising reserve] when that presale is closed [in PPM] * @param _openDate The date upon which that presale is to be open [ignored if 0] */ function initialize( IAragonFundraisingController _controller, TokenManager _tokenManager, address _reserve, address _beneficiary, address _contributionToken, uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate ) external onlyInit { require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_tokenManager), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiary != address(0), ERROR_INVALID_BENEFICIARY); require(isContract(_contributionToken) || _contributionToken == ETH, ERROR_INVALID_CONTRIBUTE_TOKEN); require(_goal > 0, ERROR_INVALID_GOAL); require(_period > 0, ERROR_INVALID_TIME_PERIOD); require(_exchangeRate > 0, ERROR_INVALID_EXCHANGE_RATE); require(_vestingCliffPeriod > _period, ERROR_INVALID_TIME_PERIOD); require(_vestingCompletePeriod > _vestingCliffPeriod, ERROR_INVALID_TIME_PERIOD); require(_supplyOfferedPct > 0 && _supplyOfferedPct <= PPM, ERROR_INVALID_PCT); require(_fundingForBeneficiaryPct >= 0 && _fundingForBeneficiaryPct <= PPM, ERROR_INVALID_PCT); initialized(); controller = _controller; tokenManager = _tokenManager; token = ERC20(_tokenManager.token()); reserve = _reserve; beneficiary = _beneficiary; contributionToken = _contributionToken; goal = _goal; period = _period; exchangeRate = _exchangeRate; vestingCliffPeriod = _vestingCliffPeriod; vestingCompletePeriod = _vestingCompletePeriod; supplyOfferedPct = _supplyOfferedPct; fundingForBeneficiaryPct = _fundingForBeneficiaryPct; if (_openDate != 0) { _setOpenDate(_openDate); } } /** * @notice Open presale [enabling users to contribute] */ function open() external auth(OPEN_ROLE) { require(state() == State.Pending, ERROR_INVALID_STATE); require(openDate == 0, ERROR_INVALID_STATE); _open(); } /** * @notice Contribute to the presale up to `@tokenAmount(self.contributionToken(): address, _value)` * @param _contributor The address of the contributor * @param _value The amount of contribution token to be spent */ function contribute(address _contributor, uint256 _value) external payable nonReentrant auth(CONTRIBUTE_ROLE) { require(state() == State.Funding, ERROR_INVALID_STATE); require(_value != 0, ERROR_INVALID_CONTRIBUTE_VALUE); if (contributionToken == ETH) { require(msg.value == _value, ERROR_INVALID_CONTRIBUTE_VALUE); } else { require(msg.value == 0, ERROR_INVALID_CONTRIBUTE_VALUE); } _contribute(_contributor, _value); } /** * @notice Refund `_contributor`'s presale contribution #`_vestedPurchaseId` * @param _contributor The address of the contributor whose presale contribution is to be refunded * @param _vestedPurchaseId The id of the contribution to be refunded */ function refund(address _contributor, uint256 _vestedPurchaseId) external nonReentrant isInitialized { require(state() == State.Refunding, ERROR_INVALID_STATE); _refund(_contributor, _vestedPurchaseId); } /** * @notice Close presale and open trading */ function close() external nonReentrant isInitialized { require(state() == State.GoalReached, ERROR_INVALID_STATE); _close(); } /***** public view functions *****/ /** * @notice Computes the amount of [bonded] tokens that would be purchased for `@tokenAmount(self.contributionToken(): address, _value)` * @param _value The amount of contribution tokens to be used in that computation */ function contributionToTokens(uint256 _value) public view isInitialized returns (uint256) { return _value.mul(exchangeRate).div(PPM); } function contributionToken() public view isInitialized returns (address) { return contributionToken; } /** * @notice Returns the current state of that presale */ function state() public view isInitialized returns (State) { if (openDate == 0 || openDate > getTimestamp64()) { return State.Pending; } if (totalRaised >= goal) { if (isClosed) { return State.Closed; } else { return State.GoalReached; } } if (_timeSinceOpen() < period) { return State.Funding; } else { return State.Refunding; } } /***** internal functions *****/ function _timeSinceOpen() internal view returns (uint64) { if (openDate == 0) { return 0; } else { return getTimestamp64().sub(openDate); } } function _setOpenDate(uint64 _date) internal { require(_date >= getTimestamp64(), ERROR_INVALID_TIME_PERIOD); openDate = _date; _setVestingDatesWhenOpenDateIsKnown(); emit SetOpenDate(_date); } function _setVestingDatesWhenOpenDateIsKnown() internal { vestingCliffDate = openDate.add(vestingCliffPeriod); vestingCompleteDate = openDate.add(vestingCompletePeriod); } function _open() internal { _setOpenDate(getTimestamp64()); } function _contribute(address _contributor, uint256 _value) internal { uint256 value = totalRaised.add(_value) > goal ? goal.sub(totalRaised) : _value; if (contributionToken == ETH && _value > value) { msg.sender.transfer(_value.sub(value)); } // (contributor) ~~~> contribution tokens ~~~> (presale) if (contributionToken != ETH) { require(ERC20(contributionToken).balanceOf(_contributor) >= value, ERROR_INSUFFICIENT_BALANCE); require(ERC20(contributionToken).allowance(_contributor, address(this)) >= value, ERROR_INSUFFICIENT_ALLOWANCE); _transfer(contributionToken, _contributor, address(this), value); } // (mint ✨) ~~~> project tokens ~~~> (contributor) uint256 tokensToSell = contributionToTokens(value); tokenManager.issue(tokensToSell); uint256 vestedPurchaseId = tokenManager.assignVested( _contributor, tokensToSell, openDate, vestingCliffDate, vestingCompleteDate, true /* revokable */ ); totalRaised = totalRaised.add(value); // register contribution tokens spent in this purchase for a possible upcoming refund contributions[_contributor][vestedPurchaseId] = value; emit Contribute(_contributor, value, tokensToSell, vestedPurchaseId); } function _refund(address _contributor, uint256 _vestedPurchaseId) internal { // recall how much contribution tokens are to be refund for this purchase uint256 tokensToRefund = contributions[_contributor][_vestedPurchaseId]; require(tokensToRefund > 0, ERROR_NOTHING_TO_REFUND); contributions[_contributor][_vestedPurchaseId] = 0; // (presale) ~~~> contribution tokens ~~~> (contributor) _transfer(contributionToken, address(this), _contributor, tokensToRefund); /** * NOTE * the following lines assume that _contributor has not transfered any of its vested tokens * for now TokenManager does not handle switching the transferrable status of its underlying token * there is thus no way to enforce non-transferrability during the presale phase only * this will be updated in a later version */ // (contributor) ~~~> project tokens ~~~> (token manager) (uint256 tokensSold,,,,) = tokenManager.getVesting(_contributor, _vestedPurchaseId); tokenManager.revokeVesting(_contributor, _vestedPurchaseId); // (token manager) ~~~> project tokens ~~~> (burn 💥) tokenManager.burn(address(tokenManager), tokensSold); emit Refund(_contributor, tokensToRefund, tokensSold, _vestedPurchaseId); } function _close() internal { isClosed = true; // (presale) ~~~> contribution tokens ~~~> (beneficiary) uint256 fundsForBeneficiary = totalRaised.mul(fundingForBeneficiaryPct).div(PPM); if (fundsForBeneficiary > 0) { _transfer(contributionToken, address(this), beneficiary, fundsForBeneficiary); } // (presale) ~~~> contribution tokens ~~~> (reserve) uint256 tokensForReserve = contributionToken == ETH ? address(this).balance : ERC20(contributionToken).balanceOf(address(this)); _transfer(contributionToken, address(this), reserve, tokensForReserve); // (mint ✨) ~~~> project tokens ~~~> (beneficiary) uint256 tokensForBeneficiary = token.totalSupply().mul(PPM.sub(supplyOfferedPct)).div(supplyOfferedPct); tokenManager.issue(tokensForBeneficiary); tokenManager.assignVested( beneficiary, tokensForBeneficiary, openDate, vestingCliffDate, vestingCompleteDate, false /* revokable */ ); // open trading controller.openTrading(); emit Close(); } function _transfer(address _token, address _from, address _to, uint256 _amount) internal { if (_token == ETH) { require(_from == address(this), ERROR_TOKEN_TRANSFER_REVERTED); require(_to != address(this), ERROR_TOKEN_TRANSFER_REVERTED); _to.transfer(_amount); } else { if (_from == address(this)) { require(ERC20(_token).safeTransfer(_to, _amount), ERROR_TOKEN_TRANSFER_REVERTED); } else { require(ERC20(_token).safeTransferFrom(_from, _to, _amount), ERROR_TOKEN_TRANSFER_REVERTED); } } } } // File: @ablack/fundraising-tap/contracts/Tap.sol pragma solidity 0.4.24; contract Tap is ITap, TimeHelpers, EtherTokenConstant, IsContract, AragonApp { using SafeERC20 for ERC20; using SafeMath for uint256; /** Hardcoded constants to save gas bytes32 public constant UPDATE_CONTROLLER_ROLE = keccak256("UPDATE_CONTROLLER_ROLE"); bytes32 public constant UPDATE_RESERVE_ROLE = keccak256("UPDATE_RESERVE_ROLE"); bytes32 public constant UPDATE_BENEFICIARY_ROLE = keccak256("UPDATE_BENEFICIARY_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE"); bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = keccak256("UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE"); bytes32 public constant ADD_TAPPED_TOKEN_ROLE = keccak256("ADD_TAPPED_TOKEN_ROLE"); bytes32 public constant REMOVE_TAPPED_TOKEN_ROLE = keccak256("REMOVE_TAPPED_TOKEN_ROLE"); bytes32 public constant UPDATE_TAPPED_TOKEN_ROLE = keccak256("UPDATE_TAPPED_TOKEN_ROLE"); bytes32 public constant RESET_TAPPED_TOKEN_ROLE = keccak256("RESET_TAPPED_TOKEN_ROLE"); bytes32 public constant WITHDRAW_ROLE = keccak256("WITHDRAW_ROLE"); */ bytes32 public constant UPDATE_CONTROLLER_ROLE = 0x454b5d0dbb74f012faf1d3722ea441689f97dc957dd3ca5335b4969586e5dc30; bytes32 public constant UPDATE_RESERVE_ROLE = 0x7984c050833e1db850f5aa7476710412fd2983fcec34da049502835ad7aed4f7; bytes32 public constant UPDATE_BENEFICIARY_ROLE = 0xf7ea2b80c7b6a2cab2c11d2290cb005c3748397358a25e17113658c83b732593; bytes32 public constant UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE = 0x5d94de7e429250eee4ff97e30ab9f383bea3cd564d6780e0a9e965b1add1d207; bytes32 public constant UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE = 0x57c9c67896cf0a4ffe92cbea66c2f7c34380af06bf14215dabb078cf8a6d99e1; bytes32 public constant ADD_TAPPED_TOKEN_ROLE = 0x5bc3b608e6be93b75a1c472a4a5bea3d31eabae46bf968e4bc4c7701562114dc; bytes32 public constant REMOVE_TAPPED_TOKEN_ROLE = 0xd76960be78bfedc5b40ce4fa64a2f8308f39dd2cbb1f9676dbc4ce87b817befd; bytes32 public constant UPDATE_TAPPED_TOKEN_ROLE = 0x83201394534c53ae0b4696fd49a933082d3e0525aa5a3d0a14a2f51e12213288; bytes32 public constant RESET_TAPPED_TOKEN_ROLE = 0x294bf52c518669359157a9fe826e510dfc3dbd200d44bf77ec9536bff34bc29e; bytes32 public constant WITHDRAW_ROLE = 0x5d8e12c39142ff96d79d04d15d1ba1269e4fe57bb9d26f43523628b34ba108ec; uint256 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10 ** 16; 100% = 10 ** 18 string private constant ERROR_CONTRACT_IS_EOA = "TAP_CONTRACT_IS_EOA"; string private constant ERROR_INVALID_BENEFICIARY = "TAP_INVALID_BENEFICIARY"; string private constant ERROR_INVALID_BATCH_BLOCKS = "TAP_INVALID_BATCH_BLOCKS"; string private constant ERROR_INVALID_FLOOR_DECREASE_PCT = "TAP_INVALID_FLOOR_DECREASE_PCT"; string private constant ERROR_INVALID_TOKEN = "TAP_INVALID_TOKEN"; string private constant ERROR_INVALID_TAP_RATE = "TAP_INVALID_TAP_RATE"; string private constant ERROR_INVALID_TAP_UPDATE = "TAP_INVALID_TAP_UPDATE"; string private constant ERROR_TOKEN_ALREADY_TAPPED = "TAP_TOKEN_ALREADY_TAPPED"; string private constant ERROR_TOKEN_NOT_TAPPED = "TAP_TOKEN_NOT_TAPPED"; string private constant ERROR_WITHDRAWAL_AMOUNT_ZERO = "TAP_WITHDRAWAL_AMOUNT_ZERO"; IAragonFundraisingController public controller; Vault public reserve; address public beneficiary; uint256 public batchBlocks; uint256 public maximumTapRateIncreasePct; uint256 public maximumTapFloorDecreasePct; mapping (address => uint256) public tappedAmounts; mapping (address => uint256) public rates; mapping (address => uint256) public floors; mapping (address => uint256) public lastTappedAmountUpdates; // batch ids [block numbers] mapping (address => uint256) public lastTapUpdates; // timestamps event UpdateBeneficiary (address indexed beneficiary); event UpdateMaximumTapRateIncreasePct (uint256 maximumTapRateIncreasePct); event UpdateMaximumTapFloorDecreasePct(uint256 maximumTapFloorDecreasePct); event AddTappedToken (address indexed token, uint256 rate, uint256 floor); event RemoveTappedToken (address indexed token); event UpdateTappedToken (address indexed token, uint256 rate, uint256 floor); event ResetTappedToken (address indexed token); event UpdateTappedAmount (address indexed token, uint256 tappedAmount); event Withdraw (address indexed token, uint256 amount); /***** external functions *****/ /** * @notice Initialize tap * @param _controller The address of the controller contract * @param _reserve The address of the reserve [pool] contract * @param _beneficiary The address of the beneficiary [to whom funds are to be withdrawn] * @param _batchBlocks The number of blocks batches are to last * @param _maximumTapRateIncreasePct The maximum tap rate increase percentage allowed [in PCT_BASE] * @param _maximumTapFloorDecreasePct The maximum tap floor decrease percentage allowed [in PCT_BASE] */ function initialize( IAragonFundraisingController _controller, Vault _reserve, address _beneficiary, uint256 _batchBlocks, uint256 _maximumTapRateIncreasePct, uint256 _maximumTapFloorDecreasePct ) external onlyInit { require(isContract(_controller), ERROR_CONTRACT_IS_EOA); require(isContract(_reserve), ERROR_CONTRACT_IS_EOA); require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); require(_batchBlocks != 0, ERROR_INVALID_BATCH_BLOCKS); require(_maximumTapFloorDecreasePctIsValid(_maximumTapFloorDecreasePct), ERROR_INVALID_FLOOR_DECREASE_PCT); initialized(); controller = _controller; reserve = _reserve; beneficiary = _beneficiary; batchBlocks = _batchBlocks; maximumTapRateIncreasePct = _maximumTapRateIncreasePct; maximumTapFloorDecreasePct = _maximumTapFloorDecreasePct; } /** * @notice Update beneficiary to `_beneficiary` * @param _beneficiary The address of the new beneficiary [to whom funds are to be withdrawn] */ function updateBeneficiary(address _beneficiary) external auth(UPDATE_BENEFICIARY_ROLE) { require(_beneficiaryIsValid(_beneficiary), ERROR_INVALID_BENEFICIARY); _updateBeneficiary(_beneficiary); } /** * @notice Update maximum tap rate increase percentage to `@formatPct(_maximumTapRateIncreasePct)`% * @param _maximumTapRateIncreasePct The new maximum tap rate increase percentage to be allowed [in PCT_BASE] */ function updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) external auth(UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE) { _updateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct); } /** * @notice Update maximum tap floor decrease percentage to `@formatPct(_maximumTapFloorDecreasePct)`% * @param _maximumTapFloorDecreasePct The new maximum tap floor decrease percentage to be allowed [in PCT_BASE] */ function updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) external auth(UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE) { require(_maximumTapFloorDecreasePctIsValid(_maximumTapFloorDecreasePct), ERROR_INVALID_FLOOR_DECREASE_PCT); _updateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct); } /** * @notice Add tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token to be tapped * @param _rate The rate at which that token is to be tapped [in wei / block] * @param _floor The floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function addTappedToken(address _token, uint256 _rate, uint256 _floor) external auth(ADD_TAPPED_TOKEN_ROLE) { require(_tokenIsContractOrETH(_token), ERROR_INVALID_TOKEN); require(!_tokenIsTapped(_token), ERROR_TOKEN_ALREADY_TAPPED); require(_tapRateIsValid(_rate), ERROR_INVALID_TAP_RATE); _addTappedToken(_token, _rate, _floor); } /** * @notice Remove tap for `_token.symbol(): string` * @param _token The address of the token to be un-tapped */ function removeTappedToken(address _token) external auth(REMOVE_TAPPED_TOKEN_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); _removeTappedToken(_token); } /** * @notice Update tap for `_token.symbol(): string` with a rate of `@tokenAmount(_token, _rate)` per block and a floor of `@tokenAmount(_token, _floor)` * @param _token The address of the token whose tap is to be updated * @param _rate The new rate at which that token is to be tapped [in wei / block] * @param _floor The new floor above which the reserve [pool] balance for that token is to be kept [in wei] */ function updateTappedToken(address _token, uint256 _rate, uint256 _floor) external auth(UPDATE_TAPPED_TOKEN_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); require(_tapRateIsValid(_rate), ERROR_INVALID_TAP_RATE); require(_tapUpdateIsValid(_token, _rate, _floor), ERROR_INVALID_TAP_UPDATE); _updateTappedToken(_token, _rate, _floor); } /** * @notice Reset tap timestamps for `_token.symbol(): string` * @param _token The address of the token whose tap timestamps are to be reset */ function resetTappedToken(address _token) external auth(RESET_TAPPED_TOKEN_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); _resetTappedToken(_token); } /** * @notice Update tapped amount for `_token.symbol(): string` * @param _token The address of the token whose tapped amount is to be updated */ function updateTappedAmount(address _token) external { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); _updateTappedAmount(_token); } /** * @notice Transfer about `@tokenAmount(_token, self.getMaximalWithdrawal(_token): uint256)` from `self.reserve()` to `self.beneficiary()` * @param _token The address of the token to be transfered */ function withdraw(address _token) external auth(WITHDRAW_ROLE) { require(_tokenIsTapped(_token), ERROR_TOKEN_NOT_TAPPED); uint256 amount = _updateTappedAmount(_token); require(amount > 0, ERROR_WITHDRAWAL_AMOUNT_ZERO); _withdraw(_token, amount); } /***** public view functions *****/ function getMaximumWithdrawal(address _token) public view isInitialized returns (uint256) { return _tappedAmount(_token); } function rates(address _token) public view isInitialized returns (uint256) { return rates[_token]; } /***** internal functions *****/ /* computation functions */ function _currentBatchId() internal view returns (uint256) { return (block.number.div(batchBlocks)).mul(batchBlocks); } function _tappedAmount(address _token) internal view returns (uint256) { uint256 toBeKept = controller.collateralsToBeClaimed(_token).add(floors[_token]); uint256 balance = _token == ETH ? address(reserve).balance : ERC20(_token).staticBalanceOf(reserve); uint256 flow = (_currentBatchId().sub(lastTappedAmountUpdates[_token])).mul(rates[_token]); uint256 tappedAmount = tappedAmounts[_token].add(flow); /** * whatever happens enough collateral should be * kept in the reserve pool to guarantee that * its balance is kept above the floor once * all pending sell orders are claimed */ /** * the reserve's balance is already below the balance to be kept * the tapped amount should be reset to zero */ if (balance <= toBeKept) { return 0; } /** * the reserve's balance minus the upcoming tap flow would be below the balance to be kept * the flow should be reduced to balance - toBeKept */ if (balance <= toBeKept.add(tappedAmount)) { return balance.sub(toBeKept); } /** * the reserve's balance minus the upcoming flow is above the balance to be kept * the flow can be added to the tapped amount */ return tappedAmount; } /* check functions */ function _beneficiaryIsValid(address _beneficiary) internal pure returns (bool) { return _beneficiary != address(0); } function _maximumTapFloorDecreasePctIsValid(uint256 _maximumTapFloorDecreasePct) internal pure returns (bool) { return _maximumTapFloorDecreasePct <= PCT_BASE; } function _tokenIsContractOrETH(address _token) internal view returns (bool) { return isContract(_token) || _token == ETH; } function _tokenIsTapped(address _token) internal view returns (bool) { return rates[_token] != uint256(0); } function _tapRateIsValid(uint256 _rate) internal pure returns (bool) { return _rate != 0; } function _tapUpdateIsValid(address _token, uint256 _rate, uint256 _floor) internal view returns (bool) { return _tapRateUpdateIsValid(_token, _rate) && _tapFloorUpdateIsValid(_token, _floor); } function _tapRateUpdateIsValid(address _token, uint256 _rate) internal view returns (bool) { uint256 rate = rates[_token]; if (_rate <= rate) { return true; } if (getTimestamp() < lastTapUpdates[_token] + 30 days) { return false; } if (_rate.mul(PCT_BASE) <= rate.mul(PCT_BASE.add(maximumTapRateIncreasePct))) { return true; } return false; } function _tapFloorUpdateIsValid(address _token, uint256 _floor) internal view returns (bool) { uint256 floor = floors[_token]; if (_floor >= floor) { return true; } if (getTimestamp() < lastTapUpdates[_token] + 30 days) { return false; } if (maximumTapFloorDecreasePct >= PCT_BASE) { return true; } if (_floor.mul(PCT_BASE) >= floor.mul(PCT_BASE.sub(maximumTapFloorDecreasePct))) { return true; } return false; } /* state modifying functions */ function _updateTappedAmount(address _token) internal returns (uint256) { uint256 tappedAmount = _tappedAmount(_token); lastTappedAmountUpdates[_token] = _currentBatchId(); tappedAmounts[_token] = tappedAmount; emit UpdateTappedAmount(_token, tappedAmount); return tappedAmount; } function _updateBeneficiary(address _beneficiary) internal { beneficiary = _beneficiary; emit UpdateBeneficiary(_beneficiary); } function _updateMaximumTapRateIncreasePct(uint256 _maximumTapRateIncreasePct) internal { maximumTapRateIncreasePct = _maximumTapRateIncreasePct; emit UpdateMaximumTapRateIncreasePct(_maximumTapRateIncreasePct); } function _updateMaximumTapFloorDecreasePct(uint256 _maximumTapFloorDecreasePct) internal { maximumTapFloorDecreasePct = _maximumTapFloorDecreasePct; emit UpdateMaximumTapFloorDecreasePct(_maximumTapFloorDecreasePct); } function _addTappedToken(address _token, uint256 _rate, uint256 _floor) internal { /** * NOTE * 1. if _token is tapped in the middle of a batch it will * reach the next batch faster than what it normally takes * to go through a batch [e.g. one block later] * 2. this will allow for a higher withdrawal than expected * a few blocks after _token is tapped * 3. this is not a problem because this extra amount is * static [at most rates[_token] * batchBlocks] and does * not increase in time */ rates[_token] = _rate; floors[_token] = _floor; lastTappedAmountUpdates[_token] = _currentBatchId(); lastTapUpdates[_token] = getTimestamp(); emit AddTappedToken(_token, _rate, _floor); } function _removeTappedToken(address _token) internal { delete tappedAmounts[_token]; delete rates[_token]; delete floors[_token]; delete lastTappedAmountUpdates[_token]; delete lastTapUpdates[_token]; emit RemoveTappedToken(_token); } function _updateTappedToken(address _token, uint256 _rate, uint256 _floor) internal { /** * NOTE * withdraw before updating to keep the reserve * actual balance [balance - virtual withdrawal] * continuous in time [though a floor update can * still break this continuity] */ uint256 amount = _updateTappedAmount(_token); if (amount > 0) { _withdraw(_token, amount); } rates[_token] = _rate; floors[_token] = _floor; lastTapUpdates[_token] = getTimestamp(); emit UpdateTappedToken(_token, _rate, _floor); } function _resetTappedToken(address _token) internal { tappedAmounts[_token] = 0; lastTappedAmountUpdates[_token] = _currentBatchId(); lastTapUpdates[_token] = getTimestamp(); emit ResetTappedToken(_token); } function _withdraw(address _token, uint256 _amount) internal { tappedAmounts[_token] = tappedAmounts[_token].sub(_amount); reserve.transfer(_token, beneficiary, _amount); // vault contract's transfer method already reverts on error emit Withdraw(_token, _amount); } } // File: contracts/AavegotchiTBCTemplate.sol pragma solidity 0.4.24; contract AavegotchiTBCTemplate is EtherTokenConstant, BaseTemplate { string private constant ERROR_BAD_SETTINGS = "FM_BAD_SETTINGS"; string private constant ERROR_MISSING_CACHE = "FM_MISSING_CACHE"; bool private constant BOARD_TRANSFERABLE = false; uint8 private constant BOARD_TOKEN_DECIMALS = uint8(0); uint256 private constant BOARD_MAX_PER_ACCOUNT = uint256(1); bool private constant SHARE_TRANSFERABLE = true; uint8 private constant SHARE_TOKEN_DECIMALS = uint8(18); uint256 private constant SHARE_MAX_PER_ACCOUNT = uint256(0); uint64 private constant DEFAULT_FINANCE_PERIOD = uint64(30 days); uint256 private constant BUY_FEE_PCT = 0; uint256 private constant SELL_FEE_PCT = 0; uint32 private constant DAI_RESERVE_RATIO = 333333; // 33% uint32 private constant ANT_RESERVE_RATIO = 10000; // 1% bytes32 private constant BANCOR_FORMULA_ID = 0xd71dde5e4bea1928026c1779bde7ed27bd7ef3d0ce9802e4117631eb6fa4ed7d; bytes32 private constant PRESALE_ID = 0x5de9bbdeaf6584c220c7b7f1922383bcd8bbcd4b48832080afd9d5ebf9a04df5; bytes32 private constant MARKET_MAKER_ID = 0xc2bb88ab974c474221f15f691ed9da38be2f5d37364180cec05403c656981bf0; bytes32 private constant ARAGON_FUNDRAISING_ID = 0x668ac370eed7e5861234d1c0a1e512686f53594fcb887e5bcecc35675a4becac; bytes32 private constant TAP_ID = 0x82967efab7144b764bc9bca2f31a721269b6618c0ff4e50545737700a5e9c9dc; struct Cache { address dao; address boardTokenManager; address boardVoting; address vault; address finance; address shareVoting; address shareTokenManager; address reserve; address presale; address marketMaker; address tap; address controller; } address[] public collaterals; mapping (address => Cache) private cache; constructor( DAOFactory _daoFactory, ENS _ens, MiniMeTokenFactory _miniMeFactory, IFIFSResolvingRegistrar _aragonID, address _dai, address _ant ) BaseTemplate(_daoFactory, _ens, _miniMeFactory, _aragonID) public { _ensureAragonIdIsValid(_aragonID); _ensureMiniMeFactoryIsValid(_miniMeFactory); require(isContract(_dai), ERROR_BAD_SETTINGS); require(isContract(_ant), ERROR_BAD_SETTINGS); require(_dai != _ant, ERROR_BAD_SETTINGS); collaterals.push(_dai); collaterals.push(_ant); } /***** external functions *****/ function prepareInstance( string _boardTokenName, string _boardTokenSymbol, address[] _boardMembers, uint64[3] _boardVotingSettings, uint64 _financePeriod ) external { require(_boardMembers.length > 0, ERROR_BAD_SETTINGS); require(_boardVotingSettings.length == 3, ERROR_BAD_SETTINGS); // deploy DAO (Kernel dao, ACL acl) = _createDAO(); // deploy board token MiniMeToken boardToken = _createToken(_boardTokenName, _boardTokenSymbol, BOARD_TOKEN_DECIMALS); // install board apps TokenManager tm = _installBoardApps(dao, boardToken, _boardVotingSettings, _financePeriod); // mint board tokens _mintTokens(acl, tm, _boardMembers, 1); // cache DAO _cacheDao(dao); } function installShareApps( string _shareTokenName, string _shareTokenSymbol, uint64[3] _shareVotingSettings ) external { require(_shareVotingSettings.length == 3, ERROR_BAD_SETTINGS); _ensureBoardAppsCache(); Kernel dao = _daoCache(); // deploy share token MiniMeToken shareToken = _createToken(_shareTokenName, _shareTokenSymbol, SHARE_TOKEN_DECIMALS); // install share apps _installShareApps(dao, shareToken, _shareVotingSettings); // setup board apps permissions [now that share apps have been installed] _setupBoardPermissions(dao); } function installFundraisingApps( uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate, uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct ) external { _ensureShareAppsCache(); Kernel dao = _daoCache(); // install fundraising apps _installFundraisingApps( dao, _goal, _period, _exchangeRate, _vestingCliffPeriod, _vestingCompletePeriod, _supplyOfferedPct, _fundingForBeneficiaryPct, _openDate, _batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct ); // setup share apps permissions [now that fundraising apps have been installed] _setupSharePermissions(dao); // setup fundraising apps permissions _setupFundraisingPermissions(dao); } function finalizeInstance( string _id, uint256[2] _virtualSupplies, uint256[2] _virtualBalances, uint256[2] _slippages, uint256 _rateDAI, uint256 _floorDAI ) external { require(bytes(_id).length > 0, ERROR_BAD_SETTINGS); require(_virtualSupplies.length == 2, ERROR_BAD_SETTINGS); require(_virtualBalances.length == 2, ERROR_BAD_SETTINGS); require(_slippages.length == 2, ERROR_BAD_SETTINGS); _ensureFundraisingAppsCache(); Kernel dao = _daoCache(); ACL acl = ACL(dao.acl()); (, Voting shareVoting) = _shareAppsCache(); // setup collaterals _setupCollaterals(dao, _virtualSupplies, _virtualBalances, _slippages, _rateDAI, _floorDAI); // setup EVM script registry permissions _createEvmScriptsRegistryPermissions(acl, shareVoting, shareVoting); // clear DAO permissions _transferRootPermissionsFromTemplateAndFinalizeDAO(dao, shareVoting, shareVoting); // register id _registerID(_id, address(dao)); // clear cache _clearCache(); } /***** internal apps installation functions *****/ function _installBoardApps(Kernel _dao, MiniMeToken _token, uint64[3] _votingSettings, uint64 _financePeriod) internal returns (TokenManager) { TokenManager tm = _installTokenManagerApp(_dao, _token, BOARD_TRANSFERABLE, BOARD_MAX_PER_ACCOUNT); Voting voting = _installVotingApp(_dao, _token, _votingSettings); Vault vault = _installVaultApp(_dao); Finance finance = _installFinanceApp(_dao, vault, _financePeriod == 0 ? DEFAULT_FINANCE_PERIOD : _financePeriod); _cacheBoardApps(tm, voting, vault, finance); return tm; } function _installShareApps(Kernel _dao, MiniMeToken _shareToken, uint64[3] _shareVotingSettings) internal { TokenManager tm = _installTokenManagerApp(_dao, _shareToken, SHARE_TRANSFERABLE, SHARE_MAX_PER_ACCOUNT); Voting voting = _installVotingApp(_dao, _shareToken, _shareVotingSettings); _cacheShareApps(tm, voting); } function _installFundraisingApps( Kernel _dao, uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate, uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct ) internal { _proxifyFundraisingApps(_dao); _initializePresale( _goal, _period, _exchangeRate, _vestingCliffPeriod, _vestingCompletePeriod, _supplyOfferedPct, _fundingForBeneficiaryPct, _openDate ); _initializeMarketMaker(_batchBlocks); _initializeTap(_batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct); _initializeController(); } function _proxifyFundraisingApps(Kernel _dao) internal { Agent reserve = _installNonDefaultAgentApp(_dao); Presale presale = Presale(_registerApp(_dao, PRESALE_ID)); BatchedBancorMarketMaker marketMaker = BatchedBancorMarketMaker(_registerApp(_dao, MARKET_MAKER_ID)); Tap tap = Tap(_registerApp(_dao, TAP_ID)); AragonFundraisingController controller = AragonFundraisingController(_registerApp(_dao, ARAGON_FUNDRAISING_ID)); _cacheFundraisingApps(reserve, presale, marketMaker, tap, controller); } /***** internal apps initialization functions *****/ function _initializePresale( uint256 _goal, uint64 _period, uint256 _exchangeRate, uint64 _vestingCliffPeriod, uint64 _vestingCompletePeriod, uint256 _supplyOfferedPct, uint256 _fundingForBeneficiaryPct, uint64 _openDate ) internal { _presaleCache().initialize( _controllerCache(), _shareTMCache(), _reserveCache(), _vaultCache(), collaterals[0], _goal, _period, _exchangeRate, _vestingCliffPeriod, _vestingCompletePeriod, _supplyOfferedPct, _fundingForBeneficiaryPct, _openDate ); } function _initializeMarketMaker(uint256 _batchBlocks) internal { IBancorFormula bancorFormula = IBancorFormula(_latestVersionAppBase(BANCOR_FORMULA_ID)); (,, Vault beneficiary,) = _boardAppsCache(); (TokenManager shareTM,) = _shareAppsCache(); (Agent reserve,, BatchedBancorMarketMaker marketMaker,, AragonFundraisingController controller) = _fundraisingAppsCache(); marketMaker.initialize(controller, shareTM, bancorFormula, reserve, beneficiary, _batchBlocks, BUY_FEE_PCT, SELL_FEE_PCT); } function _initializeTap(uint256 _batchBlocks, uint256 _maxTapRateIncreasePct, uint256 _maxTapFloorDecreasePct) internal { (,, Vault beneficiary,) = _boardAppsCache(); (Agent reserve,,, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache(); tap.initialize(controller, reserve, beneficiary, _batchBlocks, _maxTapRateIncreasePct, _maxTapFloorDecreasePct); } function _initializeController() internal { (Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache(); address[] memory toReset = new address[](1); toReset[0] = collaterals[0]; controller.initialize(presale, marketMaker, reserve, tap, toReset); } /***** internal setup functions *****/ function _setupCollaterals( Kernel _dao, uint256[2] _virtualSupplies, uint256[2] _virtualBalances, uint256[2] _slippages, uint256 _rateDAI, uint256 _floorDAI ) internal { ACL acl = ACL(_dao.acl()); (, Voting shareVoting) = _shareAppsCache(); (,,,, AragonFundraisingController controller) = _fundraisingAppsCache(); // create and grant ADD_COLLATERAL_TOKEN_ROLE to this template _createPermissionForTemplate(acl, address(controller), controller.ADD_COLLATERAL_TOKEN_ROLE()); // add DAI both as a protected collateral and a tapped token controller.addCollateralToken( collaterals[0], _virtualSupplies[0], _virtualBalances[0], DAI_RESERVE_RATIO, _slippages[0], _rateDAI, _floorDAI ); // add ANT as a protected collateral [but not as a tapped token] controller.addCollateralToken( collaterals[1], _virtualSupplies[1], _virtualBalances[1], ANT_RESERVE_RATIO, _slippages[1], 0, 0 ); // transfer ADD_COLLATERAL_TOKEN_ROLE _transferPermissionFromTemplate(acl, controller, shareVoting, controller.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting); } /***** internal permissions functions *****/ function _setupBoardPermissions(Kernel _dao) internal { ACL acl = ACL(_dao.acl()); (TokenManager boardTM, Voting boardVoting, Vault vault, Finance finance) = _boardAppsCache(); (, Voting shareVoting) = _shareAppsCache(); // token manager _createTokenManagerPermissions(acl, boardTM, boardVoting, shareVoting); // voting _createVotingPermissions(acl, boardVoting, boardVoting, boardTM, shareVoting); // vault _createVaultPermissions(acl, vault, finance, shareVoting); // finance _createFinancePermissions(acl, finance, boardVoting, shareVoting); _createFinanceCreatePaymentsPermission(acl, finance, boardVoting, shareVoting); } function _setupSharePermissions(Kernel _dao) internal { ACL acl = ACL(_dao.acl()); (TokenManager boardTM,,,) = _boardAppsCache(); (TokenManager shareTM, Voting shareVoting) = _shareAppsCache(); (, Presale presale, BatchedBancorMarketMaker marketMaker,,) = _fundraisingAppsCache(); // token manager address[] memory grantees = new address[](2); grantees[0] = address(marketMaker); grantees[1] = address(presale); acl.createPermission(marketMaker, shareTM, shareTM.MINT_ROLE(),shareVoting); acl.createPermission(presale, shareTM, shareTM.ISSUE_ROLE(),shareVoting); acl.createPermission(presale, shareTM, shareTM.ASSIGN_ROLE(),shareVoting); acl.createPermission(presale, shareTM, shareTM.REVOKE_VESTINGS_ROLE(), shareVoting); _createPermissions(acl, grantees, shareTM, shareTM.BURN_ROLE(), shareVoting); // voting _createVotingPermissions(acl, shareVoting, shareVoting, boardTM, shareVoting); } function _setupFundraisingPermissions(Kernel _dao) internal { ACL acl = ACL(_dao.acl()); (, Voting boardVoting,,) = _boardAppsCache(); (, Voting shareVoting) = _shareAppsCache(); (Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller) = _fundraisingAppsCache(); // reserve address[] memory grantees = new address[](2); grantees[0] = address(tap); grantees[1] = address(marketMaker); acl.createPermission(shareVoting, reserve, reserve.SAFE_EXECUTE_ROLE(), shareVoting); acl.createPermission(controller, reserve, reserve.ADD_PROTECTED_TOKEN_ROLE(), shareVoting); _createPermissions(acl, grantees, reserve, reserve.TRANSFER_ROLE(), shareVoting); // presale acl.createPermission(controller, presale, presale.OPEN_ROLE(), shareVoting); acl.createPermission(controller, presale, presale.CONTRIBUTE_ROLE(), shareVoting); // market maker acl.createPermission(controller, marketMaker, marketMaker.OPEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.UPDATE_BENEFICIARY_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.UPDATE_FEES_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.REMOVE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.UPDATE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.OPEN_BUY_ORDER_ROLE(), shareVoting); acl.createPermission(controller, marketMaker, marketMaker.OPEN_SELL_ORDER_ROLE(), shareVoting); // tap acl.createPermission(controller, tap, tap.UPDATE_BENEFICIARY_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.ADD_TAPPED_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.UPDATE_TAPPED_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.RESET_TAPPED_TOKEN_ROLE(), shareVoting); acl.createPermission(controller, tap, tap.WITHDRAW_ROLE(), shareVoting); // controller // ADD_COLLATERAL_TOKEN_ROLE is handled later [after collaterals have been added] acl.createPermission(shareVoting, controller, controller.UPDATE_BENEFICIARY_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_FEES_ROLE(), shareVoting); // acl.createPermission(shareVoting, controller, controller.ADD_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.REMOVE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_COLLATERAL_TOKEN_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_MAXIMUM_TAP_RATE_INCREASE_PCT_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_MAXIMUM_TAP_FLOOR_DECREASE_PCT_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.ADD_TOKEN_TAP_ROLE(), shareVoting); acl.createPermission(shareVoting, controller, controller.UPDATE_TOKEN_TAP_ROLE(), shareVoting); acl.createPermission(boardVoting, controller, controller.OPEN_PRESALE_ROLE(), shareVoting); acl.createPermission(presale, controller, controller.OPEN_TRADING_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.CONTRIBUTE_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.OPEN_BUY_ORDER_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.OPEN_SELL_ORDER_ROLE(), shareVoting); acl.createPermission(address(-1), controller, controller.WITHDRAW_ROLE(), shareVoting); } /***** internal cache functions *****/ function _cacheDao(Kernel _dao) internal { Cache storage c = cache[msg.sender]; c.dao = address(_dao); } function _cacheBoardApps(TokenManager _boardTM, Voting _boardVoting, Vault _vault, Finance _finance) internal { Cache storage c = cache[msg.sender]; c.boardTokenManager = address(_boardTM); c.boardVoting = address(_boardVoting); c.vault = address(_vault); c.finance = address(_finance); } function _cacheShareApps(TokenManager _shareTM, Voting _shareVoting) internal { Cache storage c = cache[msg.sender]; c.shareTokenManager = address(_shareTM); c.shareVoting = address(_shareVoting); } function _cacheFundraisingApps(Agent _reserve, Presale _presale, BatchedBancorMarketMaker _marketMaker, Tap _tap, AragonFundraisingController _controller) internal { Cache storage c = cache[msg.sender]; c.reserve = address(_reserve); c.presale = address(_presale); c.marketMaker = address(_marketMaker); c.tap = address(_tap); c.controller = address(_controller); } function _daoCache() internal view returns (Kernel dao) { Cache storage c = cache[msg.sender]; dao = Kernel(c.dao); } function _boardAppsCache() internal view returns (TokenManager boardTM, Voting boardVoting, Vault vault, Finance finance) { Cache storage c = cache[msg.sender]; boardTM = TokenManager(c.boardTokenManager); boardVoting = Voting(c.boardVoting); vault = Vault(c.vault); finance = Finance(c.finance); } function _shareAppsCache() internal view returns (TokenManager shareTM, Voting shareVoting) { Cache storage c = cache[msg.sender]; shareTM = TokenManager(c.shareTokenManager); shareVoting = Voting(c.shareVoting); } function _fundraisingAppsCache() internal view returns ( Agent reserve, Presale presale, BatchedBancorMarketMaker marketMaker, Tap tap, AragonFundraisingController controller ) { Cache storage c = cache[msg.sender]; reserve = Agent(c.reserve); presale = Presale(c.presale); marketMaker = BatchedBancorMarketMaker(c.marketMaker); tap = Tap(c.tap); controller = AragonFundraisingController(c.controller); } function _clearCache() internal { Cache storage c = cache[msg.sender]; delete c.dao; delete c.boardTokenManager; delete c.boardVoting; delete c.vault; delete c.finance; delete c.shareVoting; delete c.shareTokenManager; delete c.reserve; delete c.presale; delete c.marketMaker; delete c.tap; delete c.controller; } /** * NOTE * the following functions are only needed for the presale * initialization function [which we can't compile otherwise * because of a `stack too deep` error] */ function _vaultCache() internal view returns (Vault vault) { Cache storage c = cache[msg.sender]; vault = Vault(c.vault); } function _shareTMCache() internal view returns (TokenManager shareTM) { Cache storage c = cache[msg.sender]; shareTM = TokenManager(c.shareTokenManager); } function _reserveCache() internal view returns (Agent reserve) { Cache storage c = cache[msg.sender]; reserve = Agent(c.reserve); } function _presaleCache() internal view returns (Presale presale) { Cache storage c = cache[msg.sender]; presale = Presale(c.presale); } function _controllerCache() internal view returns (AragonFundraisingController controller) { Cache storage c = cache[msg.sender]; controller = AragonFundraisingController(c.controller); } /***** internal check functions *****/ function _ensureBoardAppsCache() internal view { Cache storage c = cache[msg.sender]; require( c.boardTokenManager != address(0) && c.boardVoting != address(0) && c.vault != address(0) && c.finance != address(0), ERROR_MISSING_CACHE ); } function _ensureShareAppsCache() internal view { Cache storage c = cache[msg.sender]; require( c.shareTokenManager != address(0) && c.shareVoting != address(0), ERROR_MISSING_CACHE ); } function _ensureFundraisingAppsCache() internal view { Cache storage c = cache[msg.sender]; require( c.reserve != address(0) && c.presale != address(0) && c.marketMaker != address(0) && c.tap != address(0) && c.controller != address(0), ERROR_MISSING_CACHE ); } /***** internal utils functions *****/ function _registerApp(Kernel _dao, bytes32 _appId) internal returns (address) { address proxy = _dao.newAppInstance(_appId, _latestVersionAppBase(_appId)); emit InstalledApp(proxy, _appId); return proxy; } }
ERC897, the address the proxy would delegate calls to/
function implementation() public view returns (address) { return pinnedCode(); }
451,381
// Sources flattened with hardhat v2.6.1 https://hardhat.org // File @openzeppelin/contracts/utils/Context.sol@v4.3.0 // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File @openzeppelin/contracts/access/Ownable.sol@v4.3.0 pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File @openzeppelin/contracts/utils/Strings.sol@v4.3.0 pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File @openzeppelin/contracts/utils/Address.sol@v4.3.0 pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/utils/math/SafeMath.sol@v4.3.0 pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File @openzeppelin/contracts/utils/structs/EnumerableSet.sol@v4.3.0 pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // File @openzeppelin/contracts/utils/structs/EnumerableMap.sol@v4.3.0 pragma solidity ^0.8.0; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { using EnumerableSet for EnumerableSet.Bytes32Set; // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct Map { // Storage of keys EnumerableSet.Bytes32Set _keys; mapping(bytes32 => bytes32) _values; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set( Map storage map, bytes32 key, bytes32 value ) private returns (bool) { map._values[key] = value; return map._keys.add(key); } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { delete map._values[key]; return map._keys.remove(key); } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._keys.contains(key); } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._keys.length(); } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { bytes32 key = map._keys.at(index); return (key, map._values[key]); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { bytes32 value = map._values[key]; if (value == bytes32(0)) { return (_contains(map, key), bytes32(0)); } else { return (true, value); } } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key"); return value; } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get( Map storage map, bytes32 key, string memory errorMessage ) private view returns (bytes32) { bytes32 value = map._values[key]; require(value != 0 || _contains(map, key), errorMessage); return value; } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set( UintToAddressMap storage map, uint256 key, address value ) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element stored at position `index` in the set. O(1). * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get( UintToAddressMap storage map, uint256 key, string memory errorMessage ) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // File @openzeppelin/contracts/utils/introspection/IERC165.sol@v4.3.0 pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts/token/ERC721/IERC721.sol@v4.3.0 pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol@v4.3.0 pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File contracts/ERC165.sol pragma solidity ^0.8.7; contract ERC165 is IERC165 { bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; mapping(bytes4 => bool) private _supportedInterfaces; constructor () { _registerInterface(_INTERFACE_ID_ERC165); } function supportsInterface(bytes4 interfaceId) public view override returns (bool) { return _supportedInterfaces[interfaceId]; } function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // File contracts/Drrt.sol pragma solidity ^0.8.7; interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); } interface IERC721Receiver { function onERC721Received(address operator, address from, uint tokenIndex, bytes calldata data) external returns (bytes4); } contract Drrt is Context, ERC165, Ownable, IERC721Metadata { using SafeMath for uint; using Strings for uint; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x93254542; bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; uint public constant MAX_TOKENS_MINT_AT_ONCE = 10; uint public constant MAX_TOKENS_SUPPLY = 9090; uint public constant TOKEN_PRICE = 60000000000000000; uint public constant TOKEN_REDUCED_PRICE = 50000000000000000; uint private constant MAX_GIVEAWAY_TOKENS = 110; string private constant NAME = 'DRRT'; string private constant SYMBOL = 'DRRT'; uint private _saleStart; string private _baseURI; uint private _givenTokens; EnumerableMap.UintToAddressMap private _tokenOwners; mapping (address => EnumerableSet.UintSet) private _holderTokens; mapping (uint => address) private _tokenApprovals; mapping (address => mapping (address => bool)) private _operatorApprovals; constructor() { _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev Gets the balance of the specified address. * @param tokenOowner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address tokenOowner) external view override returns (uint) { require(tokenOowner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[tokenOowner].length(); } /** * @dev Gets the owner of the specified token ID. * @param tokenIndex uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint tokenIndex) public view override returns (address) { return _tokenOwners.get(tokenIndex, "ERC721: owner query for nonexistent token"); } /** * @dev A descriptive name for a collection of NFTs in this contract * * @return descriptive name. */ function name() external pure override returns (string memory) { return NAME; } /** * @dev An abbreviated name for NFTs in this contract * * @return abbreviated name (symbol). */ function symbol() external pure override returns (string memory) { return SYMBOL; } /** * @dev function to set the base URI of the collection * * @param baseURI base URI string. */ function setBaseURI(string memory baseURI) external onlyOwner { _baseURI = baseURI; } /** * @dev Returns the NFT index owned by the user * * @param tokenOowner address. * @param index Index in the list of owned tokens by address. * * @return token index in the collection. */ function tokenOfOwnerByIndex(address tokenOowner, uint index) external view returns (uint) { return _holderTokens[tokenOowner].at(index); } /** * @dev Returns the total amount of tokens stored by the contract. * * @return total amount of tokens. */ function totalSupply() public view returns (uint) { return _tokenOwners.length(); } /** * @dev Starts the sale of NFTs */ function startSale() external onlyOwner { require(_saleStart == 0, "Sale already started"); _saleStart = block.timestamp; } /** * @dev Function checks if the sale already started * * @return true if sale started or false if sale not started. */ function isSaleStarted() external view returns (bool) { return _saleStart > 0; } /** * @dev Function mints one giveaway NFT and sends to the address * * @param to address of NFT reciever. */ function mintGiveaway(address to) external onlyOwner { require(_givenTokens <= MAX_GIVEAWAY_TOKENS, "Giveaway limit exceeded"); _givenTokens++; _safeMint(to, totalSupply()); } /** * @dev Function mints the amount of NFTs and sends them to the executor's address * * @param tokenAmount amount of NFTs for minting. */ function mint(uint tokenAmount) external payable { require(_saleStart != 0, "Sale is not started"); require(tokenAmount > 0, "Tokens amount cannot be 0"); require(totalSupply().add(tokenAmount) - _givenTokens <= MAX_TOKENS_SUPPLY - MAX_GIVEAWAY_TOKENS, "Purchase would exceed max supply"); require(tokenAmount <= MAX_TOKENS_MINT_AT_ONCE, "Can only mint 10 tokens per request"); uint price; if (block.timestamp < _saleStart + 86400) { price = TOKEN_REDUCED_PRICE * tokenAmount; } else { price = TOKEN_PRICE * tokenAmount; } require(msg.value >= price, "Ether value sent is not correct"); for (uint i = 0; i < tokenAmount; i++) { _safeMint(_msgSender(), totalSupply()); } if (msg.value - price > 0) { payable(_msgSender()).transfer(msg.value - price); } } /** * @dev Returns the URI for a given token ID. May return an empty string. * * If the token's URI is non-empty and a base URI was set (via * {_setBaseURI}), it will be added to the token ID's URI as a prefix. * * Reverts if the token ID does not exist. * @param tokenIndex uint256 ID of the token */ function tokenURI(uint tokenIndex) external view returns (string memory) { require(_exists(tokenIndex), "Token does not exist"); return bytes(_baseURI).length != 0 ? string(abi.encodePacked(_baseURI, tokenIndex.toString())) : ""; } /** * @dev Transfers all founds to the owner's address * Can only be called by the owner of the contract. */ function withdraw() onlyOwner external { uint balance = address(this).balance; if (balance > 0) { payable(_msgSender()).transfer(balance); } } /** * @dev Approves another address to transfer the given token ID * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenIndex uint256 ID of the token to be approved */ function approve(address to, uint tokenIndex) external virtual override { address tokenOowner = ownerOf(tokenIndex); require(to != tokenOowner, "ERC721: approval to current owner"); require(_msgSender() == tokenOowner || isApprovedForAll(tokenOowner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenIndex); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenIndex uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint tokenIndex) public view override returns (address) { require(_exists(tokenIndex), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenIndex]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param operator operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param tokenOowner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address tokenOowner, address operator) public view override returns (bool) { return _operatorApprovals[tokenOowner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use `safeTransferFrom` whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenIndex uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint tokenIndex) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenIndex), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenIndex); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenIndex uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint tokenIndex) public virtual override { safeTransferFrom(from, to, tokenIndex, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenIndex uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint tokenIndex, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenIndex), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenIndex, _data); } /** * @dev Internal function for safe transfer * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenIndex uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function _safeTransfer(address from, address to, uint tokenIndex, bytes memory _data) internal virtual { _transfer(from, to, tokenIndex); require(_checkOnERC721Received(from, to, tokenIndex, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenIndex uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint tokenIndex) internal view returns (bool) { return _tokenOwners.contains(tokenIndex); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenIndex uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint tokenIndex) internal view returns (bool) { require(_exists(tokenIndex), "ERC721: operator query for nonexistent token"); address tokenOowner = ownerOf(tokenIndex); return (spender == tokenOowner || getApproved(tokenIndex) == spender || isApprovedForAll(tokenOowner, spender)); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenIndex uint256 ID of the token to be minted */ function _safeMint(address to, uint tokenIndex) internal virtual { _safeMint(to, tokenIndex, ""); } /** * @dev Internal function to safely mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenIndex uint256 ID of the token to be minted * @param _data bytes data to send along with a safe transfer check */ function _safeMint(address to, uint tokenIndex, bytes memory _data) internal virtual { _mint(to, tokenIndex); require(_checkOnERC721Received(address(0), to, tokenIndex, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenIndex uint256 ID of the token to be minted */ function _mint(address to, uint tokenIndex) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenIndex), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenIndex); _holderTokens[to].add(tokenIndex); _tokenOwners.set(tokenIndex, to); emit Transfer(address(0), to, tokenIndex); } /** * @dev Internal function for transfer * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenIndex uint256 ID of the token to be transferred */ function _transfer(address from, address to, uint tokenIndex) internal virtual { require(ownerOf(tokenIndex) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenIndex); _approve(address(0), tokenIndex); _holderTokens[from].remove(tokenIndex); _holderTokens[to].add(tokenIndex); _tokenOwners.set(tokenIndex, to); emit Transfer(from, to, tokenIndex); } /** * @dev Internal function to invoke `onERC721Received` on a target address. * The call is not executed if the target address is not a contract. * * This function is deprecated. * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenIndex uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint tokenIndex, bytes memory _data) private returns (bool) { if (!to.isContract()) return true; bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenIndex, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Internal function for approve another address to transfer the given token ID * @param to address to be approved for the given token ID * @param tokenIndex uint256 ID of the token to be approved */ function _approve(address to, uint tokenIndex) private { _tokenApprovals[tokenIndex] = to; emit Approval(ownerOf(tokenIndex), to, tokenIndex); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint tokenIndex) internal virtual {} }
Approves another address to transfer the given token ID Can only be called by the token owner or an approved operator. to address to be approved for the given token ID tokenIndex uint256 ID of the token to be approved/
function approve(address to, uint tokenIndex) external virtual override { address tokenOowner = ownerOf(tokenIndex); require(to != tokenOowner, "ERC721: approval to current owner"); require(_msgSender() == tokenOowner || isApprovedForAll(tokenOowner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenIndex); }
1,335,361
./full_match/314/0x7b7f1f85F599b63432F5D782041c25Dad354f999/sources/node_modules/@openzeppelin/contracts/governance/extensions/GovernorTimelockAccess.sol
Returns bucket and subindex for reading manager data from the packed array mapping./
function _getManagerDataIndices(uint256 index) private pure returns (uint256 bucket, uint256 subindex) { }
8,083,834
pragma solidity 0.4.24; /** * @title SafeMath * @notice Math operations with safety checks that throw on error */ library SafeMath { /** * @notice Multiplies two numbers, throws on overflow. * @param a Multiplier * @param b Multiplicand * @return {"result" : "Returns product"} */ function mul(uint256 a, uint256 b) internal pure returns (uint256 result) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "Error: Unsafe multiplication operation!"); return c; } /** * @notice Integer division of two numbers, truncating the quotient. * @param a Dividend * @param b Divisor * @return {"result" : "Returns quotient"} */ function div(uint256 a, uint256 b) internal pure returns (uint256 result) { // @dev require(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // @dev require(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @notice Subtracts two numbers, throws on underflow. * @param a Subtrahend * @param b Minuend * @return {"result" : "Returns difference"} */ function sub(uint256 a, uint256 b) internal pure returns (uint256 result) { // @dev throws on overflow (i.e. if subtrahend is greater than minuend) require(b <= a, "Error: Unsafe subtraction operation!"); return a - b; } /** * @notice Adds two numbers, throws on overflow. * @param a First addend * @param b Second addend * @return {"result" : "Returns summation"} */ function add(uint256 a, uint256 b) internal pure returns (uint256 result) { uint256 c = a + b; require(c >= a, "Error: Unsafe addition operation!"); return c; } } /** COPYRIGHT 2018 Token, Inc. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. @title Ownable @dev The Ownable contract has an owner address, and provides basic authorization control functions, this simplifies the implementation of "user permissions". */ contract Ownable { mapping(address => bool) public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event AllowOwnership(address indexed allowedAddress); event RevokeOwnership(address indexed allowedAddress); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner[msg.sender] = true; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner[msg.sender], "Error: Transaction sender is not allowed by the contract."); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. * @return {"success" : "Returns true when successfully transferred ownership"} */ function transferOwnership(address newOwner) public onlyOwner returns (bool success) { require(newOwner != address(0), "Error: newOwner cannot be null!"); emit OwnershipTransferred(msg.sender, newOwner); owner[newOwner] = true; owner[msg.sender] = false; return true; } /** * @dev Allows interface contracts and accounts to access contract methods (e.g. Storage contract) * @param allowedAddress The address of new owner * @return {"success" : "Returns true when successfully allowed ownership"} */ function allowOwnership(address allowedAddress) public onlyOwner returns (bool success) { owner[allowedAddress] = true; emit AllowOwnership(allowedAddress); return true; } /** * @dev Disallows interface contracts and accounts to access contract methods (e.g. Storage contract) * @param allowedAddress The address to disallow ownership * @return {"success" : "Returns true when successfully allowed ownership"} */ function removeOwnership(address allowedAddress) public onlyOwner returns (bool success) { owner[allowedAddress] = false; emit RevokeOwnership(allowedAddress); return true; } } /** COPYRIGHT 2018 Token, Inc. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. @title TokenIOStorage - Serves as derived contract for TokenIO contract and is used to upgrade interfaces in the event of deprecating the main contract. @author Ryan Tate <ryan.tate@token.io>, Sean Pollock <sean.pollock@token.io> @notice Storage contract @dev In the event that the main contract becomes deprecated, the upgraded contract will be set as the owner of this contract, and use this contract's storage to maintain data consistency between contract. @notice NOTE: This contract is based on the RocketPool Storage Contract, found here: https://github.com/rocket-pool/rocketpool/blob/master/contracts/RocketStorage.sol And this medium article: https://medium.com/rocket-pool/upgradable-solidity-contract-design-54789205276d Changes: - setting primitive mapping view to internal; - setting method views to public; @dev NOTE: When deprecating the main TokenIO contract, the upgraded contract must take ownership of the TokenIO contract, it will require using the public methods to update changes to the underlying data. The updated contract must use a standard call to original TokenIO contract such that the request is made from the upgraded contract and not the transaction origin (tx.origin) of the signing account. @dev NOTE: The reasoning for using the storage contract is to abstract the interface from the data of the contract on chain, limiting the need to migrate data to new contracts. */ contract TokenIOStorage is Ownable { /// @dev mapping for Primitive Data Types; /// @notice primitive data mappings have `internal` view; /// @dev only the derived contract can use the internal methods; /// @dev key == `keccak256(param1, param2...)` /// @dev Nested mapping can be achieved using multiple params in keccak256 hash; mapping(bytes32 => uint256) internal uIntStorage; mapping(bytes32 => string) internal stringStorage; mapping(bytes32 => address) internal addressStorage; mapping(bytes32 => bytes) internal bytesStorage; mapping(bytes32 => bool) internal boolStorage; mapping(bytes32 => int256) internal intStorage; constructor() public { /// @notice owner is set to msg.sender by default /// @dev consider removing in favor of setting ownership in inherited /// contract owner[msg.sender] = true; } /// @dev Set Key Methods /** * @notice Set value for Address associated with bytes32 id key * @param _key Pointer identifier for value in storage * @param _value The Address value to be set * @return { "success" : "Returns true when successfully called from another contract" } */ function setAddress(bytes32 _key, address _value) public onlyOwner returns (bool success) { addressStorage[_key] = _value; return true; } /** * @notice Set value for Uint associated with bytes32 id key * @param _key Pointer identifier for value in storage * @param _value The Uint value to be set * @return { "success" : "Returns true when successfully called from another contract" } */ function setUint(bytes32 _key, uint _value) public onlyOwner returns (bool success) { uIntStorage[_key] = _value; return true; } /** * @notice Set value for String associated with bytes32 id key * @param _key Pointer identifier for value in storage * @param _value The String value to be set * @return { "success" : "Returns true when successfully called from another contract" } */ function setString(bytes32 _key, string _value) public onlyOwner returns (bool success) { stringStorage[_key] = _value; return true; } /** * @notice Set value for Bytes associated with bytes32 id key * @param _key Pointer identifier for value in storage * @param _value The Bytes value to be set * @return { "success" : "Returns true when successfully called from another contract" } */ function setBytes(bytes32 _key, bytes _value) public onlyOwner returns (bool success) { bytesStorage[_key] = _value; return true; } /** * @notice Set value for Bool associated with bytes32 id key * @param _key Pointer identifier for value in storage * @param _value The Bool value to be set * @return { "success" : "Returns true when successfully called from another contract" } */ function setBool(bytes32 _key, bool _value) public onlyOwner returns (bool success) { boolStorage[_key] = _value; return true; } /** * @notice Set value for Int associated with bytes32 id key * @param _key Pointer identifier for value in storage * @param _value The Int value to be set * @return { "success" : "Returns true when successfully called from another contract" } */ function setInt(bytes32 _key, int _value) public onlyOwner returns (bool success) { intStorage[_key] = _value; return true; } /// @dev Delete Key Methods /// @dev delete methods may be unnecessary; Use set methods to set values /// to default? /** * @notice Delete value for Address associated with bytes32 id key * @param _key Pointer identifier for value in storage * @return { "success" : "Returns true when successfully called from another contract" } */ function deleteAddress(bytes32 _key) public onlyOwner returns (bool success) { delete addressStorage[_key]; return true; } /** * @notice Delete value for Uint associated with bytes32 id key * @param _key Pointer identifier for value in storage * @return { "success" : "Returns true when successfully called from another contract" } */ function deleteUint(bytes32 _key) public onlyOwner returns (bool success) { delete uIntStorage[_key]; return true; } /** * @notice Delete value for String associated with bytes32 id key * @param _key Pointer identifier for value in storage * @return { "success" : "Returns true when successfully called from another contract" } */ function deleteString(bytes32 _key) public onlyOwner returns (bool success) { delete stringStorage[_key]; return true; } /** * @notice Delete value for Bytes associated with bytes32 id key * @param _key Pointer identifier for value in storage * @return { "success" : "Returns true when successfully called from another contract" } */ function deleteBytes(bytes32 _key) public onlyOwner returns (bool success) { delete bytesStorage[_key]; return true; } /** * @notice Delete value for Bool associated with bytes32 id key * @param _key Pointer identifier for value in storage * @return { "success" : "Returns true when successfully called from another contract" } */ function deleteBool(bytes32 _key) public onlyOwner returns (bool success) { delete boolStorage[_key]; return true; } /** * @notice Delete value for Int associated with bytes32 id key * @param _key Pointer identifier for value in storage * @return { "success" : "Returns true when successfully called from another contract" } */ function deleteInt(bytes32 _key) public onlyOwner returns (bool success) { delete intStorage[_key]; return true; } /// @dev Get Key Methods /** * @notice Get value for Address associated with bytes32 id key * @param _key Pointer identifier for value in storage * @return { "_value" : "Returns the Address value associated with the id key" } */ function getAddress(bytes32 _key) public view returns (address _value) { return addressStorage[_key]; } /** * @notice Get value for Uint associated with bytes32 id key * @param _key Pointer identifier for value in storage * @return { "_value" : "Returns the Uint value associated with the id key" } */ function getUint(bytes32 _key) public view returns (uint _value) { return uIntStorage[_key]; } /** * @notice Get value for String associated with bytes32 id key * @param _key Pointer identifier for value in storage * @return { "_value" : "Returns the String value associated with the id key" } */ function getString(bytes32 _key) public view returns (string _value) { return stringStorage[_key]; } /** * @notice Get value for Bytes associated with bytes32 id key * @param _key Pointer identifier for value in storage * @return { "_value" : "Returns the Bytes value associated with the id key" } */ function getBytes(bytes32 _key) public view returns (bytes _value) { return bytesStorage[_key]; } /** * @notice Get value for Bool associated with bytes32 id key * @param _key Pointer identifier for value in storage * @return { "_value" : "Returns the Bool value associated with the id key" } */ function getBool(bytes32 _key) public view returns (bool _value) { return boolStorage[_key]; } /** * @notice Get value for Int associated with bytes32 id key * @param _key Pointer identifier for value in storage * @return { "_value" : "Returns the Int value associated with the id key" } */ function getInt(bytes32 _key) public view returns (int _value) { return intStorage[_key]; } } /** COPYRIGHT 2018 Token, Inc. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. @title TokenIOLib @author Ryan Tate <ryan.tate@token.io>, Sean Pollock <sean.pollock@token.io> @notice This library proxies the TokenIOStorage contract for the interface contract, allowing the library and the interfaces to remain stateless, and share a universally available storage contract between interfaces. */ library TokenIOLib { /// @dev all math operating are using SafeMath methods to check for overflow/underflows using SafeMath for uint; /// @dev the Data struct uses the Storage contract for stateful setters struct Data { TokenIOStorage Storage; } /// @notice Not using `Log` prefix for events to be consistent with ERC20 named events; event Approval(address indexed owner, address indexed spender, uint amount); event Deposit(string currency, address indexed account, uint amount, string issuerFirm); event Withdraw(string currency, address indexed account, uint amount, string issuerFirm); event Transfer(string currency, address indexed from, address indexed to, uint amount, bytes data); event KYCApproval(address indexed account, bool status, string issuerFirm); event AccountStatus(address indexed account, bool status, string issuerFirm); event FxSwap(string tokenASymbol,string tokenBSymbol,uint tokenAValue,uint tokenBValue, uint expiration, bytes32 transactionHash); event AccountForward(address indexed originalAccount, address indexed forwardedAccount); event NewAuthority(address indexed authority, string issuerFirm); /** * @notice Set the token name for Token interfaces * @dev This method must be set by the token interface's setParams() method * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @param tokenName Name of the token contract * @return {"success" : "Returns true when successfully called from another contract"} */ function setTokenName(Data storage self, string tokenName) internal returns (bool success) { bytes32 id = keccak256(abi.encodePacked('token.name', address(this))); require( self.Storage.setString(id, tokenName), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); return true; } /** * @notice Set the token symbol for Token interfaces * @dev This method must be set by the token interface's setParams() method * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @param tokenSymbol Symbol of the token contract * @return {"success" : "Returns true when successfully called from another contract"} */ function setTokenSymbol(Data storage self, string tokenSymbol) internal returns (bool success) { bytes32 id = keccak256(abi.encodePacked('token.symbol', address(this))); require( self.Storage.setString(id, tokenSymbol), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); return true; } /** * @notice Set the token three letter abreviation (TLA) for Token interfaces * @dev This method must be set by the token interface's setParams() method * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @param tokenTLA TLA of the token contract * @return {"success" : "Returns true when successfully called from another contract"} */ function setTokenTLA(Data storage self, string tokenTLA) internal returns (bool success) { bytes32 id = keccak256(abi.encodePacked('token.tla', address(this))); require( self.Storage.setString(id, tokenTLA), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); return true; } /** * @notice Set the token version for Token interfaces * @dev This method must be set by the token interface's setParams() method * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @param tokenVersion Semantic (vMAJOR.MINOR.PATCH | e.g. v0.1.0) version of the token contract * @return {"success" : "Returns true when successfully called from another contract"} */ function setTokenVersion(Data storage self, string tokenVersion) internal returns (bool success) { bytes32 id = keccak256(abi.encodePacked('token.version', address(this))); require( self.Storage.setString(id, tokenVersion), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); return true; } /** * @notice Set the token decimals for Token interfaces * @dev This method must be set by the token interface's setParams() method * @dev | This method has an `internal` view * @dev This method is not set to the address of the contract, rather is maped to currency * @dev To derive decimal value, divide amount by 10^decimal representation (e.g. 10132 / 10**2 == 101.32) * @param self Internal storage proxying TokenIOStorage contract * @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx) * @param tokenDecimals Decimal representation of the token contract unit amount * @return {"success" : "Returns true when successfully called from another contract"} */ function setTokenDecimals(Data storage self, string currency, uint tokenDecimals) internal returns (bool success) { bytes32 id = keccak256(abi.encodePacked('token.decimals', currency)); require( self.Storage.setUint(id, tokenDecimals), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); return true; } /** * @notice Set basis point fee for contract interface * @dev Transaction fees can be set by the TokenIOFeeContract * @dev Fees vary by contract interface specified `feeContract` * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @param feeBPS Basis points fee for interface contract transactions * @return {"success" : "Returns true when successfully called from another contract"} */ function setFeeBPS(Data storage self, uint feeBPS) internal returns (bool success) { bytes32 id = keccak256(abi.encodePacked('fee.bps', address(this))); require( self.Storage.setUint(id, feeBPS), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); return true; } /** * @notice Set minimum fee for contract interface * @dev Transaction fees can be set by the TokenIOFeeContract * @dev Fees vary by contract interface specified `feeContract` * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @param feeMin Minimum fee for interface contract transactions * @return {"success" : "Returns true when successfully called from another contract"} */ function setFeeMin(Data storage self, uint feeMin) internal returns (bool success) { bytes32 id = keccak256(abi.encodePacked('fee.min', address(this))); require( self.Storage.setUint(id, feeMin), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); return true; } /** * @notice Set maximum fee for contract interface * @dev Transaction fees can be set by the TokenIOFeeContract * @dev Fees vary by contract interface specified `feeContract` * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @param feeMax Maximum fee for interface contract transactions * @return {"success" : "Returns true when successfully called from another contract"} */ function setFeeMax(Data storage self, uint feeMax) internal returns (bool success) { bytes32 id = keccak256(abi.encodePacked('fee.max', address(this))); require( self.Storage.setUint(id, feeMax), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); return true; } /** * @notice Set flat fee for contract interface * @dev Transaction fees can be set by the TokenIOFeeContract * @dev Fees vary by contract interface specified `feeContract` * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @param feeFlat Flat fee for interface contract transactions * @return {"success" : "Returns true when successfully called from another contract"} */ function setFeeFlat(Data storage self, uint feeFlat) internal returns (bool success) { bytes32 id = keccak256(abi.encodePacked('fee.flat', address(this))); require( self.Storage.setUint(id, feeFlat), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); return true; } /** * @notice Set fee message for contract interface * @dev Default fee messages can be set by the TokenIOFeeContract (e.g. "tx_fees") * @dev Fee messages vary by contract interface specified `feeContract` * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @param feeMsg Fee message included in a transaction with fees * @return {"success" : "Returns true when successfully called from another contract"} */ function setFeeMsg(Data storage self, bytes feeMsg) internal returns (bool success) { bytes32 id = keccak256(abi.encodePacked('fee.msg', address(this))); require( self.Storage.setBytes(id, feeMsg), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); return true; } /** * @notice Set fee contract for a contract interface * @dev feeContract must be a TokenIOFeeContract storage approved contract * @dev Fees vary by contract interface specified `feeContract` * @dev | This method has an `internal` view * @dev | This must be called directly from the interface contract * @param self Internal storage proxying TokenIOStorage contract * @param feeContract Set the fee contract for `this` contract address interface * @return {"success" : "Returns true when successfully called from another contract"} */ function setFeeContract(Data storage self, address feeContract) internal returns (bool success) { bytes32 id = keccak256(abi.encodePacked('fee.account', address(this))); require( self.Storage.setAddress(id, feeContract), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); return true; } /** * @notice Set contract interface associated with a given TokenIO currency symbol (e.g. USDx) * @dev | This should only be called once from a token interface contract; * @dev | This method has an `internal` view * @dev | This method is experimental and may be deprecated/refactored * @param self Internal storage proxying TokenIOStorage contract * @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx) * @return {"success" : "Returns true when successfully called from another contract"} */ function setTokenNameSpace(Data storage self, string currency) internal returns (bool success) { bytes32 id = keccak256(abi.encodePacked('token.namespace', currency)); require( self.Storage.setAddress(id, address(this)), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); return true; } /** * @notice Set the KYC approval status (true/false) for a given account * @dev | This method has an `internal` view * @dev | Every account must be KYC'd to be able to use transfer() & transferFrom() methods * @dev | To gain approval for an account, register at https://tsm.token.io/sign-up * @param self Internal storage proxying TokenIOStorage contract * @param account Ethereum address of account holder * @param isApproved Boolean (true/false) KYC approval status for a given account * @param issuerFirm Firm name for issuing KYC approval * @return {"success" : "Returns true when successfully called from another contract"} */ function setKYCApproval(Data storage self, address account, bool isApproved, string issuerFirm) internal returns (bool success) { bytes32 id = keccak256(abi.encodePacked('account.kyc', getForwardedAccount(self, account))); require( self.Storage.setBool(id, isApproved), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); /// @dev NOTE: Issuer is logged for setting account KYC status emit KYCApproval(account, isApproved, issuerFirm); return true; } /** * @notice Set the global approval status (true/false) for a given account * @dev | This method has an `internal` view * @dev | Every account must be permitted to be able to use transfer() & transferFrom() methods * @dev | To gain approval for an account, register at https://tsm.token.io/sign-up * @param self Internal storage proxying TokenIOStorage contract * @param account Ethereum address of account holder * @param isAllowed Boolean (true/false) global status for a given account * @param issuerFirm Firm name for issuing approval * @return {"success" : "Returns true when successfully called from another contract"} */ function setAccountStatus(Data storage self, address account, bool isAllowed, string issuerFirm) internal returns (bool success) { bytes32 id = keccak256(abi.encodePacked('account.allowed', getForwardedAccount(self, account))); require( self.Storage.setBool(id, isAllowed), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); /// @dev NOTE: Issuer is logged for setting account status emit AccountStatus(account, isAllowed, issuerFirm); return true; } /** * @notice Set a forwarded address for an account. * @dev | This method has an `internal` view * @dev | Forwarded accounts must be set by an authority in case of account recovery; * @dev | Additionally, the original owner can set a forwarded account (e.g. add a new device, spouse, dependent, etc) * @dev | All transactions will be logged under the same KYC information as the original account holder; * @param self Internal storage proxying TokenIOStorage contract * @param originalAccount Original registered Ethereum address of the account holder * @param forwardedAccount Forwarded Ethereum address of the account holder * @return {"success" : "Returns true when successfully called from another contract"} */ function setForwardedAccount(Data storage self, address originalAccount, address forwardedAccount) internal returns (bool success) { bytes32 id = keccak256(abi.encodePacked('master.account', forwardedAccount)); require( self.Storage.setAddress(id, originalAccount), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); return true; } /** * @notice Get the original address for a forwarded account * @dev | This method has an `internal` view * @dev | Will return the registered account for the given forwarded account * @param self Internal storage proxying TokenIOStorage contract * @param account Ethereum address of account holder * @return { "registeredAccount" : "Will return the original account of a forwarded account or the account itself if no account found"} */ function getForwardedAccount(Data storage self, address account) internal view returns (address registeredAccount) { bytes32 id = keccak256(abi.encodePacked('master.account', account)); address originalAccount = self.Storage.getAddress(id); if (originalAccount != 0x0) { return originalAccount; } else { return account; } } /** * @notice Get KYC approval status for the account holder * @dev | This method has an `internal` view * @dev | All forwarded accounts will use the original account's status * @param self Internal storage proxying TokenIOStorage contract * @param account Ethereum address of account holder * @return { "status" : "Returns the KYC approval status for an account holder" } */ function getKYCApproval(Data storage self, address account) internal view returns (bool status) { bytes32 id = keccak256(abi.encodePacked('account.kyc', getForwardedAccount(self, account))); return self.Storage.getBool(id); } /** * @notice Get global approval status for the account holder * @dev | This method has an `internal` view * @dev | All forwarded accounts will use the original account's status * @param self Internal storage proxying TokenIOStorage contract * @param account Ethereum address of account holder * @return { "status" : "Returns the global approval status for an account holder" } */ function getAccountStatus(Data storage self, address account) internal view returns (bool status) { bytes32 id = keccak256(abi.encodePacked('account.allowed', getForwardedAccount(self, account))); return self.Storage.getBool(id); } /** * @notice Get the contract interface address associated with token symbol * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx) * @return { "contractAddress" : "Returns the contract interface address for a symbol" } */ function getTokenNameSpace(Data storage self, string currency) internal view returns (address contractAddress) { bytes32 id = keccak256(abi.encodePacked('token.namespace', currency)); return self.Storage.getAddress(id); } /** * @notice Get the token name for Token interfaces * @dev This method must be set by the token interface's setParams() method * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @param contractAddress Contract address of the queryable interface * @return {"tokenName" : "Name of the token contract"} */ function getTokenName(Data storage self, address contractAddress) internal view returns (string tokenName) { bytes32 id = keccak256(abi.encodePacked('token.name', contractAddress)); return self.Storage.getString(id); } /** * @notice Get the token symbol for Token interfaces * @dev This method must be set by the token interface's setParams() method * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @param contractAddress Contract address of the queryable interface * @return {"tokenSymbol" : "Symbol of the token contract"} */ function getTokenSymbol(Data storage self, address contractAddress) internal view returns (string tokenSymbol) { bytes32 id = keccak256(abi.encodePacked('token.symbol', contractAddress)); return self.Storage.getString(id); } /** * @notice Get the token Three letter abbreviation (TLA) for Token interfaces * @dev This method must be set by the token interface's setParams() method * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @param contractAddress Contract address of the queryable interface * @return {"tokenTLA" : "TLA of the token contract"} */ function getTokenTLA(Data storage self, address contractAddress) internal view returns (string tokenTLA) { bytes32 id = keccak256(abi.encodePacked('token.tla', contractAddress)); return self.Storage.getString(id); } /** * @notice Get the token version for Token interfaces * @dev This method must be set by the token interface's setParams() method * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @param contractAddress Contract address of the queryable interface * @return {"tokenVersion" : "Semantic version of the token contract"} */ function getTokenVersion(Data storage self, address contractAddress) internal view returns (string) { bytes32 id = keccak256(abi.encodePacked('token.version', contractAddress)); return self.Storage.getString(id); } /** * @notice Get the token decimals for Token interfaces * @dev This method must be set by the token interface's setParams() method * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx) * @return {"tokenDecimals" : "Decimals of the token contract"} */ function getTokenDecimals(Data storage self, string currency) internal view returns (uint tokenDecimals) { bytes32 id = keccak256(abi.encodePacked('token.decimals', currency)); return self.Storage.getUint(id); } /** * @notice Get the basis points fee of the contract address; typically TokenIOFeeContract * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @param contractAddress Contract address of the queryable interface * @return { "feeBps" : "Returns the basis points fees associated with the contract address"} */ function getFeeBPS(Data storage self, address contractAddress) internal view returns (uint feeBps) { bytes32 id = keccak256(abi.encodePacked('fee.bps', contractAddress)); return self.Storage.getUint(id); } /** * @notice Get the minimum fee of the contract address; typically TokenIOFeeContract * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @param contractAddress Contract address of the queryable interface * @return { "feeMin" : "Returns the minimum fees associated with the contract address"} */ function getFeeMin(Data storage self, address contractAddress) internal view returns (uint feeMin) { bytes32 id = keccak256(abi.encodePacked('fee.min', contractAddress)); return self.Storage.getUint(id); } /** * @notice Get the maximum fee of the contract address; typically TokenIOFeeContract * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @param contractAddress Contract address of the queryable interface * @return { "feeMax" : "Returns the maximum fees associated with the contract address"} */ function getFeeMax(Data storage self, address contractAddress) internal view returns (uint feeMax) { bytes32 id = keccak256(abi.encodePacked('fee.max', contractAddress)); return self.Storage.getUint(id); } /** * @notice Get the flat fee of the contract address; typically TokenIOFeeContract * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @param contractAddress Contract address of the queryable interface * @return { "feeFlat" : "Returns the flat fees associated with the contract address"} */ function getFeeFlat(Data storage self, address contractAddress) internal view returns (uint feeFlat) { bytes32 id = keccak256(abi.encodePacked('fee.flat', contractAddress)); return self.Storage.getUint(id); } /** * @notice Get the flat message of the contract address; typically TokenIOFeeContract * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @param contractAddress Contract address of the queryable interface * @return { "feeMsg" : "Returns the fee message (bytes) associated with the contract address"} */ function getFeeMsg(Data storage self, address contractAddress) internal view returns (bytes feeMsg) { bytes32 id = keccak256(abi.encodePacked('fee.msg', contractAddress)); return self.Storage.getBytes(id); } /** * @notice Set the master fee contract used as the default fee contract when none is provided * @dev | This method has an `internal` view * @dev | This value is set in the TokenIOAuthority contract * @param self Internal storage proxying TokenIOStorage contract * @param contractAddress Contract address of the queryable interface * @return { "success" : "Returns true when successfully called from another contract"} */ function setMasterFeeContract(Data storage self, address contractAddress) internal returns (bool success) { bytes32 id = keccak256(abi.encodePacked('fee.contract.master')); require( self.Storage.setAddress(id, contractAddress), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); return true; } /** * @notice Get the master fee contract set via the TokenIOAuthority contract * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @return { "masterFeeContract" : "Returns the master fee contract set for TSM."} */ function getMasterFeeContract(Data storage self) internal view returns (address masterFeeContract) { bytes32 id = keccak256(abi.encodePacked('fee.contract.master')); return self.Storage.getAddress(id); } /** * @notice Get the fee contract set for a contract interface * @dev | This method has an `internal` view * @dev | Custom fee pricing can be set by assigning a fee contract to transactional contract interfaces * @dev | If a fee contract has not been set by an interface contract, then the master fee contract will be returned * @param self Internal storage proxying TokenIOStorage contract * @param contractAddress Contract address of the queryable interface * @return { "feeContract" : "Returns the fee contract associated with a contract interface"} */ function getFeeContract(Data storage self, address contractAddress) internal view returns (address feeContract) { bytes32 id = keccak256(abi.encodePacked('fee.account', contractAddress)); address feeAccount = self.Storage.getAddress(id); if (feeAccount == 0x0) { return getMasterFeeContract(self); } else { return feeAccount; } } /** * @notice Get the token supply for a given TokenIO TSM currency symbol (e.g. USDx) * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx) * @return { "supply" : "Returns the token supply of the given currency"} */ function getTokenSupply(Data storage self, string currency) internal view returns (uint supply) { bytes32 id = keccak256(abi.encodePacked('token.supply', currency)); return self.Storage.getUint(id); } /** * @notice Get the token spender allowance for a given account * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @param account Ethereum address of account holder * @param spender Ethereum address of spender * @return { "allowance" : "Returns the allowance of a given spender for a given account"} */ function getTokenAllowance(Data storage self, string currency, address account, address spender) internal view returns (uint allowance) { bytes32 id = keccak256(abi.encodePacked('token.allowance', currency, getForwardedAccount(self, account), getForwardedAccount(self, spender))); return self.Storage.getUint(id); } /** * @notice Get the token balance for a given account * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx) * @param account Ethereum address of account holder * @return { "balance" : "Return the balance of a given account for a specified currency"} */ function getTokenBalance(Data storage self, string currency, address account) internal view returns (uint balance) { bytes32 id = keccak256(abi.encodePacked('token.balance', currency, getForwardedAccount(self, account))); return self.Storage.getUint(id); } /** * @notice Get the frozen token balance for a given account * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx) * @param account Ethereum address of account holder * @return { "frozenBalance" : "Return the frozen balance of a given account for a specified currency"} */ function getTokenFrozenBalance(Data storage self, string currency, address account) internal view returns (uint frozenBalance) { bytes32 id = keccak256(abi.encodePacked('token.frozen', currency, getForwardedAccount(self, account))); return self.Storage.getUint(id); } /** * @notice Set the frozen token balance for a given account * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx) * @param account Ethereum address of account holder * @param amount Amount of tokens to freeze for account * @return { "success" : "Return true if successfully called from another contract"} */ function setTokenFrozenBalance(Data storage self, string currency, address account, uint amount) internal returns (bool success) { bytes32 id = keccak256(abi.encodePacked('token.frozen', currency, getForwardedAccount(self, account))); require( self.Storage.setUint(id, amount), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract." ); return true; } /** * @notice Set the frozen token balance for a given account * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @param contractAddress Contract address of the fee contract * @param amount Transaction value * @return { "calculatedFees" : "Return the calculated transaction fees for a given amount and fee contract" } */ function calculateFees(Data storage self, address contractAddress, uint amount) internal view returns (uint calculatedFees) { uint maxFee = self.Storage.getUint(keccak256(abi.encodePacked('fee.max', contractAddress))); uint minFee = self.Storage.getUint(keccak256(abi.encodePacked('fee.min', contractAddress))); uint bpsFee = self.Storage.getUint(keccak256(abi.encodePacked('fee.bps', contractAddress))); uint flatFee = self.Storage.getUint(keccak256(abi.encodePacked('fee.flat', contractAddress))); uint fees = ((amount.mul(bpsFee)).div(10000)).add(flatFee); if (fees > maxFee) { return maxFee; } else if (fees < minFee) { return minFee; } else { return fees; } } /** * @notice Verified KYC and global status for two accounts and return true or throw if either account is not verified * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @param accountA Ethereum address of first account holder to verify * @param accountB Ethereum address of second account holder to verify * @return { "verified" : "Returns true if both accounts are successfully verified" } */ function verifyAccounts(Data storage self, address accountA, address accountB) internal view returns (bool verified) { require( verifyAccount(self, accountA), "Error: Account is not verified for operation. Please ensure account has been KYC approved." ); require( verifyAccount(self, accountB), "Error: Account is not verified for operation. Please ensure account has been KYC approved." ); return true; } /** * @notice Verified KYC and global status for a single account and return true or throw if account is not verified * @dev | This method has an `internal` view * @param self Internal storage proxying TokenIOStorage contract * @param account Ethereum address of account holder to verify * @return { "verified" : "Returns true if account is successfully verified" } */ function verifyAccount(Data storage self, address account) internal view returns (bool verified) { require( getKYCApproval(self, account), "Error: Account does not have KYC approval." ); require( getAccountStatus(self, account), "Error: Account status is `false`. Account status must be `true`." ); return true; } /** * @notice Transfer an amount of currency token from msg.sender account to another specified account * @dev This function is called by an interface that is accessible directly to the account holder * @dev | This method has an `internal` view * @dev | This method uses `forceTransfer()` low-level api * @param self Internal storage proxying TokenIOStorage contract * @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx) * @param to Ethereum address of account to send currency amount to * @param amount Value of currency to transfer * @param data Arbitrary bytes data to include with the transaction * @return { "success" : "Return true if successfully called from another contract" } */ function transfer(Data storage self, string currency, address to, uint amount, bytes data) internal returns (bool success) { require(address(to) != 0x0, "Error: `to` address cannot be null." ); require(amount > 0, "Error: `amount` must be greater than zero"); address feeContract = getFeeContract(self, address(this)); uint fees = calculateFees(self, feeContract, amount); require( setAccountSpendingAmount(self, msg.sender, getFxUSDAmount(self, currency, amount)), "Error: Unable to set spending amount for account."); require( forceTransfer(self, currency, msg.sender, to, amount, data), "Error: Unable to transfer funds to account."); // @dev transfer fees to fee contract require( forceTransfer(self, currency, msg.sender, feeContract, fees, getFeeMsg(self, feeContract)), "Error: Unable to transfer fees to fee contract."); return true; } /** * @notice Transfer an amount of currency token from account to another specified account via an approved spender account * @dev This function is called by an interface that is accessible directly to the account spender * @dev | This method has an `internal` view * @dev | Transactions will fail if the spending amount exceeds the daily limit * @dev | This method uses `forceTransfer()` low-level api * @dev | This method implements ERC20 transferFrom() method with approved spender behavior * @dev | msg.sender == spender; `updateAllowance()` reduces approved limit for account spender * @param self Internal storage proxying TokenIOStorage contract * @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx) * @param from Ethereum address of account to send currency amount from * @param to Ethereum address of account to send currency amount to * @param amount Value of currency to transfer * @param data Arbitrary bytes data to include with the transaction * @return { "success" : "Return true if successfully called from another contract" } */ function transferFrom(Data storage self, string currency, address from, address to, uint amount, bytes data) internal returns (bool success) { require( address(to) != 0x0, "Error: `to` address must not be null." ); address feeContract = getFeeContract(self, address(this)); uint fees = calculateFees(self, feeContract, amount); /// @dev NOTE: This transaction will fail if the spending amount exceeds the daily limit require( setAccountSpendingAmount(self, from, getFxUSDAmount(self, currency, amount)), "Error: Unable to set account spending amount." ); /// @dev Attempt to transfer the amount require( forceTransfer(self, currency, from, to, amount, data), "Error: Unable to transfer funds to account." ); // @dev transfer fees to fee contract require( forceTransfer(self, currency, from, feeContract, fees, getFeeMsg(self, feeContract)), "Error: Unable to transfer fees to fee contract." ); /// @dev Attempt to update the spender allowance /// @notice this will throw if the allowance has not been set. require( updateAllowance(self, currency, from, amount), "Error: Unable to update allowance for spender." ); return true; } /** * @notice Low-level transfer method * @dev | This method has an `internal` view * @dev | This method does not include fees or approved allowances. * @dev | This method is only for authorized interfaces to use (e.g. TokenIOFX) * @param self Internal storage proxying TokenIOStorage contract * @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx) * @param from Ethereum address of account to send currency amount from * @param to Ethereum address of account to send currency amount to * @param amount Value of currency to transfer * @param data Arbitrary bytes data to include with the transaction * @return { "success" : "Return true if successfully called from another contract" } */ function forceTransfer(Data storage self, string currency, address from, address to, uint amount, bytes data) internal returns (bool success) { require( address(to) != 0x0, "Error: `to` address must not be null." ); bytes32 id_a = keccak256(abi.encodePacked('token.balance', currency, getForwardedAccount(self, from))); bytes32 id_b = keccak256(abi.encodePacked('token.balance', currency, getForwardedAccount(self, to))); require( self.Storage.setUint(id_a, self.Storage.getUint(id_a).sub(amount)), "Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract." ); require( self.Storage.setUint(id_b, self.Storage.getUint(id_b).add(amount)), "Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract." ); emit Transfer(currency, from, to, amount, data); return true; } /** * @notice Low-level method to update spender allowance for account * @dev | This method is called inside the `transferFrom()` method * @dev | msg.sender == spender address * @param self Internal storage proxying TokenIOStorage contract * @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx) * @param account Ethereum address of account holder * @param amount Value to reduce allowance by (i.e. the amount spent) * @return { "success" : "Return true if successfully called from another contract" } */ function updateAllowance(Data storage self, string currency, address account, uint amount) internal returns (bool success) { bytes32 id = keccak256(abi.encodePacked('token.allowance', currency, getForwardedAccount(self, account), getForwardedAccount(self, msg.sender))); require( self.Storage.setUint(id, self.Storage.getUint(id).sub(amount)), "Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract." ); return true; } /** * @notice Low-level method to set the allowance for a spender * @dev | This method is called inside the `approve()` ERC20 method * @dev | msg.sender == account holder * @param self Internal storage proxying TokenIOStorage contract * @param spender Ethereum address of account spender * @param amount Value to set for spender allowance * @return { "success" : "Return true if successfully called from another contract" } */ function approveAllowance(Data storage self, address spender, uint amount) internal returns (bool success) { require(spender != 0x0, "Error: `spender` address cannot be null."); string memory currency = getTokenSymbol(self, address(this)); require( getTokenFrozenBalance(self, currency, getForwardedAccount(self, spender)) == 0, "Error: Spender must not have a frozen balance directly"); bytes32 id_a = keccak256(abi.encodePacked('token.allowance', currency, getForwardedAccount(self, msg.sender), getForwardedAccount(self, spender))); bytes32 id_b = keccak256(abi.encodePacked('token.balance', currency, getForwardedAccount(self, msg.sender))); require( self.Storage.getUint(id_a) == 0 || amount == 0, "Error: Allowance must be zero (0) before setting an updated allowance for spender."); require( self.Storage.getUint(id_b) >= amount, "Error: Allowance cannot exceed msg.sender token balance."); require( self.Storage.setUint(id_a, amount), "Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract."); emit Approval(msg.sender, spender, amount); return true; } /** * @notice Deposit an amount of currency into the Ethereum account holder * @dev | The total supply of the token increases only when new funds are deposited 1:1 * @dev | This method should only be called by authorized issuer firms * @param self Internal storage proxying TokenIOStorage contract * @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx) * @param account Ethereum address of account holder to deposit funds for * @param amount Value of currency to deposit for account * @param issuerFirm Name of the issuing firm authorizing the deposit * @return { "success" : "Return true if successfully called from another contract" } */ function deposit(Data storage self, string currency, address account, uint amount, string issuerFirm) internal returns (bool success) { bytes32 id_a = keccak256(abi.encodePacked('token.balance', currency, getForwardedAccount(self, account))); bytes32 id_b = keccak256(abi.encodePacked('token.issued', currency, issuerFirm)); bytes32 id_c = keccak256(abi.encodePacked('token.supply', currency)); require(self.Storage.setUint(id_a, self.Storage.getUint(id_a).add(amount)), "Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract."); require(self.Storage.setUint(id_b, self.Storage.getUint(id_b).add(amount)), "Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract."); require(self.Storage.setUint(id_c, self.Storage.getUint(id_c).add(amount)), "Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract."); emit Deposit(currency, account, amount, issuerFirm); return true; } /** * @notice Withdraw an amount of currency from the Ethereum account holder * @dev | The total supply of the token decreases only when new funds are withdrawn 1:1 * @dev | This method should only be called by authorized issuer firms * @param self Internal storage proxying TokenIOStorage contract * @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx) * @param account Ethereum address of account holder to deposit funds for * @param amount Value of currency to withdraw for account * @param issuerFirm Name of the issuing firm authorizing the withdraw * @return { "success" : "Return true if successfully called from another contract" } */ function withdraw(Data storage self, string currency, address account, uint amount, string issuerFirm) internal returns (bool success) { bytes32 id_a = keccak256(abi.encodePacked('token.balance', currency, getForwardedAccount(self, account))); bytes32 id_b = keccak256(abi.encodePacked('token.issued', currency, issuerFirm)); // possible for issuer to go negative bytes32 id_c = keccak256(abi.encodePacked('token.supply', currency)); require( self.Storage.setUint(id_a, self.Storage.getUint(id_a).sub(amount)), "Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract."); require( self.Storage.setUint(id_b, self.Storage.getUint(id_b).sub(amount)), "Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract."); require( self.Storage.setUint(id_c, self.Storage.getUint(id_c).sub(amount)), "Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract."); emit Withdraw(currency, account, amount, issuerFirm); return true; } /** * @notice Method for setting a registered issuer firm * @dev | Only Token, Inc. and other authorized institutions may set a registered firm * @dev | The TokenIOAuthority.sol interface wraps this method * @dev | If the registered firm is unapproved; all authorized addresses of that firm will also be unapproved * @param self Internal storage proxying TokenIOStorage contract * @param issuerFirm Name of the firm to be registered * @param approved Approval status to set for the firm (true/false) * @return { "success" : "Return true if successfully called from another contract" } */ function setRegisteredFirm(Data storage self, string issuerFirm, bool approved) internal returns (bool success) { bytes32 id = keccak256(abi.encodePacked('registered.firm', issuerFirm)); require( self.Storage.setBool(id, approved), "Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract." ); return true; } /** * @notice Method for setting a registered issuer firm authority * @dev | Only Token, Inc. and other approved institutions may set a registered firm * @dev | The TokenIOAuthority.sol interface wraps this method * @dev | Authority can only be set for a registered issuer firm * @param self Internal storage proxying TokenIOStorage contract * @param issuerFirm Name of the firm to be registered to authority * @param authorityAddress Ethereum address of the firm authority to be approved * @param approved Approval status to set for the firm authority (true/false) * @return { "success" : "Return true if successfully called from another contract" } */ function setRegisteredAuthority(Data storage self, string issuerFirm, address authorityAddress, bool approved) internal returns (bool success) { require( isRegisteredFirm(self, issuerFirm), "Error: `issuerFirm` must be registered."); bytes32 id_a = keccak256(abi.encodePacked('registered.authority', issuerFirm, authorityAddress)); bytes32 id_b = keccak256(abi.encodePacked('registered.authority.firm', authorityAddress)); require( self.Storage.setBool(id_a, approved), "Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract."); require( self.Storage.setString(id_b, issuerFirm), "Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract."); return true; } /** * @notice Get the issuer firm registered to the authority Ethereum address * @dev | Only one firm can be registered per authority * @param self Internal storage proxying TokenIOStorage contract * @param authorityAddress Ethereum address of the firm authority to query * @return { "issuerFirm" : "Name of the firm registered to authority" } */ function getFirmFromAuthority(Data storage self, address authorityAddress) internal view returns (string issuerFirm) { bytes32 id = keccak256(abi.encodePacked('registered.authority.firm', getForwardedAccount(self, authorityAddress))); return self.Storage.getString(id); } /** * @notice Return the boolean (true/false) registration status for an issuer firm * @param self Internal storage proxying TokenIOStorage contract * @param issuerFirm Name of the issuer firm * @return { "registered" : "Return if the issuer firm has been registered" } */ function isRegisteredFirm(Data storage self, string issuerFirm) internal view returns (bool registered) { bytes32 id = keccak256(abi.encodePacked('registered.firm', issuerFirm)); return self.Storage.getBool(id); } /** * @notice Return the boolean (true/false) status if an authority is registered to an issuer firm * @param self Internal storage proxying TokenIOStorage contract * @param issuerFirm Name of the issuer firm * @param authorityAddress Ethereum address of the firm authority to query * @return { "registered" : "Return if the authority is registered with the issuer firm" } */ function isRegisteredToFirm(Data storage self, string issuerFirm, address authorityAddress) internal view returns (bool registered) { bytes32 id = keccak256(abi.encodePacked('registered.authority', issuerFirm, getForwardedAccount(self, authorityAddress))); return self.Storage.getBool(id); } /** * @notice Return if an authority address is registered * @dev | This also checks the status of the registered issuer firm * @param self Internal storage proxying TokenIOStorage contract * @param authorityAddress Ethereum address of the firm authority to query * @return { "registered" : "Return if the authority is registered" } */ function isRegisteredAuthority(Data storage self, address authorityAddress) internal view returns (bool registered) { bytes32 id = keccak256(abi.encodePacked('registered.authority', getFirmFromAuthority(self, getForwardedAccount(self, authorityAddress)), getForwardedAccount(self, authorityAddress))); return self.Storage.getBool(id); } /** * @notice Return boolean transaction status if the transaction has been used * @param self Internal storage proxying TokenIOStorage contract * @param txHash keccak256 ABI tightly packed encoded hash digest of tx params * @return {"txStatus": "Returns true if the tx hash has already been set using `setTxStatus()` method"} */ function getTxStatus(Data storage self, bytes32 txHash) internal view returns (bool txStatus) { bytes32 id = keccak256(abi.encodePacked('tx.status', txHash)); return self.Storage.getBool(id); } /** * @notice Set transaction status if the transaction has been used * @param self Internal storage proxying TokenIOStorage contract * @param txHash keccak256 ABI tightly packed encoded hash digest of tx params * @return { "success" : "Return true if successfully called from another contract" } */ function setTxStatus(Data storage self, bytes32 txHash) internal returns (bool success) { bytes32 id = keccak256(abi.encodePacked('tx.status', txHash)); /// @dev Ensure transaction has not yet been used; require(!getTxStatus(self, txHash), "Error: Transaction status must be false before setting the transaction status."); /// @dev Update the status of the transaction; require(self.Storage.setBool(id, true), "Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract."); return true; } /** * @notice Accepts a signed fx request to swap currency pairs at a given amount; * @dev | This method can be called directly between peers * @dev | This method does not take transaction fees from the swap * @param self Internal storage proxying TokenIOStorage contract * @param requester address Requester is the orginator of the offer and must * match the signature of the payload submitted by the fulfiller * @param symbolA Symbol of the currency desired * @param symbolB Symbol of the currency offered * @param valueA Amount of the currency desired * @param valueB Amount of the currency offered * @param sigV Ethereum secp256k1 signature V value; used by ecrecover() * @param sigR Ethereum secp256k1 signature R value; used by ecrecover() * @param sigS Ethereum secp256k1 signature S value; used by ecrecover() * @param expiration Expiration of the offer; Offer is good until expired * @return {"success" : "Returns true if successfully called from another contract"} */ function execSwap( Data storage self, address requester, string symbolA, string symbolB, uint valueA, uint valueB, uint8 sigV, bytes32 sigR, bytes32 sigS, uint expiration ) internal returns (bool success) { bytes32 fxTxHash = keccak256(abi.encodePacked(requester, symbolA, symbolB, valueA, valueB, expiration)); /// @notice check that sender and requester accounts are verified /// @notice Only verified accounts can perform currency swaps require( verifyAccounts(self, msg.sender, requester), "Error: Only verified accounts can perform currency swaps."); /// @dev Immediately set this transaction to be confirmed before updating any params; require( setTxStatus(self, fxTxHash), "Error: Failed to set transaction status to fulfilled."); /// @dev Ensure contract has not yet expired; require(expiration >= now, "Error: Transaction has expired!"); /// @dev Recover the address of the signature from the hashed digest; /// @dev Ensure it equals the requester's address require( ecrecover(fxTxHash, sigV, sigR, sigS) == requester, "Error: Address derived from transaction signature does not match the requester address"); /// @dev Transfer funds from each account to another. require( forceTransfer(self, symbolA, msg.sender, requester, valueA, "0x0"), "Error: Unable to transfer funds to account."); require( forceTransfer(self, symbolB, requester, msg.sender, valueB, "0x0"), "Error: Unable to transfer funds to account."); emit FxSwap(symbolA, symbolB, valueA, valueB, expiration, fxTxHash); return true; } /** * @notice Deprecate a contract interface * @dev | This is a low-level method to deprecate a contract interface. * @dev | This is useful if the interface needs to be updated or becomes out of date * @param self Internal storage proxying TokenIOStorage contract * @param contractAddress Ethereum address of the contract interface * @return {"success" : "Returns true if successfully called from another contract"} */ function setDeprecatedContract(Data storage self, address contractAddress) internal returns (bool success) { require(contractAddress != 0x0, "Error: cannot deprecate a null address."); bytes32 id = keccak256(abi.encodePacked('depcrecated', contractAddress)); require(self.Storage.setBool(id, true), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract."); return true; } /** * @notice Return the deprecation status of a contract * @param self Internal storage proxying TokenIOStorage contract * @param contractAddress Ethereum address of the contract interface * @return {"status" : "Return deprecation status (true/false) of the contract interface"} */ function isContractDeprecated(Data storage self, address contractAddress) internal view returns (bool status) { bytes32 id = keccak256(abi.encodePacked('depcrecated', contractAddress)); return self.Storage.getBool(id); } /** * @notice Set the Account Spending Period Limit as UNIX timestamp * @dev | Each account has it's own daily spending limit * @param self Internal storage proxying TokenIOStorage contract * @param account Ethereum address of the account holder * @param period Unix timestamp of the spending period * @return {"success" : "Returns true is successfully called from a contract"} */ function setAccountSpendingPeriod(Data storage self, address account, uint period) internal returns (bool success) { bytes32 id = keccak256(abi.encodePacked('limit.spending.period', account)); require(self.Storage.setUint(id, period), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract."); return true; } /** * @notice Get the Account Spending Period Limit as UNIX timestamp * @dev | Each account has it's own daily spending limit * @dev | If the current spending period has expired, it will be set upon next `transfer()` * or `transferFrom()` request * @param self Internal storage proxying TokenIOStorage contract * @param account Ethereum address of the account holder * @return {"period" : "Returns Unix timestamp of the current spending period"} */ function getAccountSpendingPeriod(Data storage self, address account) internal view returns (uint period) { bytes32 id = keccak256(abi.encodePacked('limit.spending.period', account)); return self.Storage.getUint(id); } /** * @notice Set the account spending limit amount * @dev | Each account has it's own daily spending limit * @param self Internal storage proxying TokenIOStorage contract * @param account Ethereum address of the account holder * @param limit Spending limit amount * @return {"success" : "Returns true is successfully called from a contract"} */ function setAccountSpendingLimit(Data storage self, address account, uint limit) internal returns (bool success) { bytes32 id = keccak256(abi.encodePacked('account.spending.limit', account)); require(self.Storage.setUint(id, limit), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract."); return true; } /** * @notice Get the account spending limit amount * @dev | Each account has it's own daily spending limit * @param self Internal storage proxying TokenIOStorage contract * @param account Ethereum address of the account holder * @return {"limit" : "Returns the account spending limit amount"} */ function getAccountSpendingLimit(Data storage self, address account) internal view returns (uint limit) { bytes32 id = keccak256(abi.encodePacked('account.spending.limit', account)); return self.Storage.getUint(id); } /** * @notice Set the account spending amount for the daily period * @dev | Each account has it's own daily spending limit * @dev | This transaction will throw if the new spending amount is greater than the limit * @dev | This method is called in the `transfer()` and `transferFrom()` methods * @param self Internal storage proxying TokenIOStorage contract * @param account Ethereum address of the account holder * @param amount Set the amount spent for the daily period * @return {"success" : "Returns true is successfully called from a contract"} */ function setAccountSpendingAmount(Data storage self, address account, uint amount) internal returns (bool success) { /// @dev NOTE: Always ensure the period is current when checking the daily spend limit require(updateAccountSpendingPeriod(self, account), "Error: Unable to update account spending period."); uint updatedAmount = getAccountSpendingAmount(self, account).add(amount); /// @dev Ensure the spend limit is greater than the amount spend for the period require( getAccountSpendingLimit(self, account) >= updatedAmount, "Error: Account cannot exceed its daily spend limit."); /// @dev Update the spending period amount if within limit bytes32 id = keccak256(abi.encodePacked('account.spending.amount', account, getAccountSpendingPeriod(self, account))); require(self.Storage.setUint(id, updatedAmount), "Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract."); return true; } /** * @notice Low-level API to ensure the account spending period is always current * @dev | This method is internally called by `setAccountSpendingAmount()` to ensure * spending period is always the most current daily period. * @param self Internal storage proxying TokenIOStorage contract * @param account Ethereum address of the account holder * @return {"success" : "Returns true is successfully called from a contract"} */ function updateAccountSpendingPeriod(Data storage self, address account) internal returns (bool success) { uint begDate = getAccountSpendingPeriod(self, account); if (begDate > now) { return true; } else { uint duration = 86400; // 86400 seconds in a day require( setAccountSpendingPeriod(self, account, begDate.add(((now.sub(begDate)).div(duration).add(1)).mul(duration))), "Error: Unable to update account spending period."); return true; } } /** * @notice Return the amount spent during the current period * @dev | Each account has it's own daily spending limit * @param self Internal storage proxying TokenIOStorage contract * @param account Ethereum address of the account holder * @return {"amount" : "Returns the amount spent by the account during the current period"} */ function getAccountSpendingAmount(Data storage self, address account) internal view returns (uint amount) { bytes32 id = keccak256(abi.encodePacked('account.spending.amount', account, getAccountSpendingPeriod(self, account))); return self.Storage.getUint(id); } /** * @notice Return the amount remaining during the current period * @dev | Each account has it's own daily spending limit * @param self Internal storage proxying TokenIOStorage contract * @param account Ethereum address of the account holder * @return {"amount" : "Returns the amount remaining by the account during the current period"} */ function getAccountSpendingRemaining(Data storage self, address account) internal view returns (uint remainingLimit) { return getAccountSpendingLimit(self, account).sub(getAccountSpendingAmount(self, account)); } /** * @notice Set the foreign currency exchange rate to USD in basis points * @dev | This value should always be relative to USD pair; e.g. JPY/USD, GBP/USD, etc. * @param self Internal storage proxying TokenIOStorage contract * @param currency The TokenIO currency symbol (e.g. USDx, JPYx, GBPx) * @param bpsRate Basis point rate of foreign currency exchange rate to USD * @return { "success": "Returns true if successfully called from another contract"} */ function setFxUSDBPSRate(Data storage self, string currency, uint bpsRate) internal returns (bool success) { bytes32 id = keccak256(abi.encodePacked('fx.usd.rate', currency)); require( self.Storage.setUint(id, bpsRate), "Error: Unable to update account spending period."); return true; } /** * @notice Return the foreign currency USD exchanged amount in basis points * @param self Internal storage proxying TokenIOStorage contract * @param currency The TokenIO currency symbol (e.g. USDx, JPYx, GBPx) * @return {"usdAmount" : "Returns the foreign currency amount in USD"} */ function getFxUSDBPSRate(Data storage self, string currency) internal view returns (uint bpsRate) { bytes32 id = keccak256(abi.encodePacked('fx.usd.rate', currency)); return self.Storage.getUint(id); } /** * @notice Return the foreign currency USD exchanged amount * @param self Internal storage proxying TokenIOStorage contract * @param currency The TokenIO currency symbol (e.g. USDx, JPYx, GBPx) * @param fxAmount Amount of foreign currency to exchange into USD * @return {"amount" : "Returns the foreign currency amount in USD"} */ function getFxUSDAmount(Data storage self, string currency, uint fxAmount) internal view returns (uint amount) { uint usdDecimals = getTokenDecimals(self, 'USDx'); uint fxDecimals = getTokenDecimals(self, currency); /// @dev ensure decimal precision is normalized to USD decimals uint usdAmount = ((fxAmount.mul(getFxUSDBPSRate(self, currency)).div(10000)).mul(10**usdDecimals)).div(10**fxDecimals); return usdAmount; } } /* COPYRIGHT 2018 Token, Inc. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. @title ERC20 Compliant Smart Contract for Token, Inc. @author Ryan Tate <ryan.tate@token.io>, Sean Pollock <sean.pollock@token.io> @notice Contract uses generalized storage contract, `TokenIOStorage`, for upgradeability of interface contract. @dev In the event that the main contract becomes deprecated, the upgraded contract will be set as the owner of this contract, and use this contract's storage to maintain data consistency between contract. */ contract TokenIOERC20FeesApply is Ownable { using SafeMath for uint; //// @dev Set reference to TokenIOLib interface which proxies to TokenIOStorage using TokenIOLib for TokenIOLib.Data; TokenIOLib.Data lib; event Transfer(address indexed from, address indexed to, uint256 amount); /** * @notice Constructor method for ERC20 contract * @param _storageContract address of TokenIOStorage contract */ constructor(address _storageContract) public { //// @dev Set the storage contract for the interface //// @dev This contract will be unable to use the storage constract until //// @dev contract address is authorized with the storage contract //// @dev Once authorized, Use the `setParams` method to set storage values lib.Storage = TokenIOStorage(_storageContract); //// @dev set owner to contract initiator owner[msg.sender] = true; } /** @notice Sets erc20 globals and fee paramters @param _name Full token name 'USD by token.io' @param _symbol Symbol name 'USDx' @param _tla Three letter abbreviation 'USD' @param _version Release version 'v0.0.1' @param _decimals Decimal precision @param _feeContract Address of fee contract @return { "success" : "Returns true if successfully called from another contract"} */ function setParams( string _name, string _symbol, string _tla, string _version, uint _decimals, address _feeContract, uint _fxUSDBPSRate ) onlyOwner public returns (bool success) { require(lib.setTokenName(_name), "Error: Unable to set token name. Please check arguments."); require(lib.setTokenSymbol(_symbol), "Error: Unable to set token symbol. Please check arguments."); require(lib.setTokenTLA(_tla), "Error: Unable to set token TLA. Please check arguments."); require(lib.setTokenVersion(_version), "Error: Unable to set token version. Please check arguments."); require(lib.setTokenDecimals(_symbol, _decimals), "Error: Unable to set token decimals. Please check arguments."); require(lib.setFeeContract(_feeContract), "Error: Unable to set fee contract. Please check arguments."); require(lib.setFxUSDBPSRate(_symbol, _fxUSDBPSRate), "Error: Unable to set fx USD basis points rate. Please check arguments."); return true; } /** * @notice Gets name of token * @return {"_name" : "Returns name of token"} */ function name() public view returns (string _name) { return lib.getTokenName(address(this)); } /** * @notice Gets symbol of token * @return {"_symbol" : "Returns symbol of token"} */ function symbol() public view returns (string _symbol) { return lib.getTokenSymbol(address(this)); } /** * @notice Gets three-letter-abbreviation of token * @return {"_tla" : "Returns three-letter-abbreviation of token"} */ function tla() public view returns (string _tla) { return lib.getTokenTLA(address(this)); } /** * @notice Gets version of token * @return {"_version" : "Returns version of token"} */ function version() public view returns (string _version) { return lib.getTokenVersion(address(this)); } /** * @notice Gets decimals of token * @return {"_decimals" : "Returns number of decimals"} */ function decimals() public view returns (uint _decimals) { return lib.getTokenDecimals(lib.getTokenSymbol(address(this))); } /** * @notice Gets total supply of token * @return {"supply" : "Returns current total supply of token"} */ function totalSupply() public view returns (uint supply) { return lib.getTokenSupply(lib.getTokenSymbol(address(this))); } /** * @notice Gets allowance that spender has with approver * @param account Address of approver * @param spender Address of spender * @return {"amount" : "Returns allowance of given account and spender"} */ function allowance(address account, address spender) public view returns (uint amount) { return lib.getTokenAllowance(lib.getTokenSymbol(address(this)), account, spender); } /** * @notice Gets balance of account * @param account Address for balance lookup * @return {"balance" : "Returns balance amount"} */ function balanceOf(address account) public view returns (uint balance) { return lib.getTokenBalance(lib.getTokenSymbol(address(this)), account); } /** * @notice Gets fee parameters * @return { "bps":"Fee amount as a mesuare of basis points", "min":"Minimum fee amount", "max":"Maximum fee amount", "flat":"Flat fee amount", "contract":"Address of fee contract" } */ function getFeeParams() public view returns (uint bps, uint min, uint max, uint flat, bytes feeMsg, address feeAccount) { address feeContract = lib.getFeeContract(address(this)); return ( lib.getFeeBPS(feeContract), lib.getFeeMin(feeContract), lib.getFeeMax(feeContract), lib.getFeeFlat(feeContract), lib.getFeeMsg(feeContract), feeContract ); } /** * @notice Calculates fee of a given transfer amount * @param amount Amount to calculcate fee value * @return {"fees": "Returns the calculated transaction fees based on the fee contract parameters"} */ function calculateFees(uint amount) public view returns (uint fees) { return lib.calculateFees(lib.getFeeContract(address(this)), amount); } /** * @notice transfers 'amount' from msg.sender to a receiving account 'to' * @param to Receiving address * @param amount Transfer amount * @return {"success" : "Returns true if transfer succeeds"} */ function transfer(address to, uint amount) public notDeprecated returns (bool success) { address feeContract = lib.getFeeContract(address(this)); string memory currency = lib.getTokenSymbol(address(this)); /// @notice send transfer through library /// @dev !!! mutates storage state require( lib.forceTransfer(currency, msg.sender, to, amount, "0x0"), "Error: Unable to transfer funds to account."); // @dev transfer fees to fee contract require( lib.forceTransfer(currency, msg.sender, feeContract, calculateFees(amount), lib.getFeeMsg(feeContract)), "Error: Unable to transfer fees to fee contract."); emit Transfer(msg.sender, to, amount); return true; } /** * @notice spender transfers from approvers account to the reciving account * @param from Approver's address * @param to Receiving address * @param amount Transfer amount * @return {"success" : "Returns true if transferFrom succeeds"} */ function transferFrom(address from, address to, uint amount) public notDeprecated returns (bool success) { address feeContract = lib.getFeeContract(address(this)); string memory currency = lib.getTokenSymbol(address(this)); uint fees = calculateFees(amount); /// @notice sends transferFrom through library /// @dev !!! mutates storage state require( lib.forceTransfer(currency, from, to, amount, "0x0"), "Error: Unable to transfer funds. Please check your parameters and ensure the spender has the approved amount of funds to transfer." ); require( lib.forceTransfer(currency, from, feeContract, fees, lib.getFeeMsg(feeContract)), "Error: Unable to transfer funds. Please check your parameters and ensure the spender has the approved amount of funds to transfer." ); /// @notice This transaction will fail if the msg.sender does not have an approved allowance. require( lib.updateAllowance(lib.getTokenSymbol(address(this)), from, amount.add(fees)), "Error: Unable to update allowance for spender." ); emit Transfer(from, to, amount); return true; } /** * @notice approves spender a given amount * @param spender Spender's address * @param amount Allowance amount * @return {"success" : "Returns true if approve succeeds"} */ function approve(address spender, uint amount) public notDeprecated returns (bool success) { /// @notice sends approve through library /// @dev !!! mtuates storage states require( lib.approveAllowance(spender, amount), "Error: Unable to approve allowance for spender. Please ensure spender is not null and does not have a frozen balance." ); return true; } /** * @notice gets currency status of contract * @return {"deprecated" : "Returns true if deprecated, false otherwise"} */ function deprecateInterface() public onlyOwner returns (bool deprecated) { require(lib.setDeprecatedContract(address(this)), "Error: Unable to deprecate contract!"); return true; } modifier notDeprecated() { /// @notice throws if contract is deprecated require(!lib.isContractDeprecated(address(this)), "Error: Contract has been deprecated, cannot perform operation!"); _; } }
Multiplies two numbers, throws on overflow. a Multiplier b Multiplicand return {"result" : "Returns product"}/
function mul(uint256 a, uint256 b) internal pure returns (uint256 result) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "Error: Unsafe multiplication operation!"); return c; }
12,990,058
// File: ERC20.sol pragma solidity ^0.5.10; /// @title ERC20 interface is a subset of the ERC20 specification. /// @notice see https://github.com/ethereum/EIPs/issues/20 interface ERC20 { function allowance(address _owner, address _spender) external view returns (uint256); function approve(address _spender, uint256 _value) external returns (bool); function balanceOf(address _who) external view returns (uint256); function totalSupply() external view returns (uint256); function transfer(address _to, uint256 _value) external returns (bool); function transferFrom(address _from, address _to, uint256 _value) external returns (bool); } // File: SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // File: Address.sol pragma solidity ^0.5.0; /** * @dev Collection of functions related to the address type, */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * > It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File: SafeERC20.sol /** * The MIT License (MIT) * * Copyright (c) 2016-2019 zOS Global Limited * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(ERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(ERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(ERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(ERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(ERC20 token, bytes memory data) internal { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: transferrable.sol /** * Transferrable - The Consumer Contract Wallet * Copyright (C) 2019 The Contract Wallet Company Limited * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.10; /// @title SafeTransfer, allowing contract to withdraw tokens accidentally sent to itself contract Transferrable { using SafeERC20 for ERC20; /// @dev This function is used to move tokens sent accidentally to this contract method. /// @dev The owner can chose the new destination address /// @param _to is the recipient's address. /// @param _asset is the address of an ERC20 token or 0x0 for ether. /// @param _amount is the amount to be transferred in base units. function _safeTransfer(address payable _to, address _asset, uint _amount) internal { // address(0) is used to denote ETH if (_asset == address(0)) { _to.transfer(_amount); } else { ERC20(_asset).safeTransfer(_to, _amount); } } } // File: balanceable.sol /** * Balanceable - The Consumer Contract Wallet * Copyright (C) 2019 The Contract Wallet Company Limited * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.10; /// @title Balanceable - This is a contract used to get a balance contract Balanceable { /// @dev This function is used to get a balance /// @param _address of which balance we are trying to ascertain /// @param _asset is the address of an ERC20 token or 0x0 for ether. /// @return balance associated with an address, for any token, in the wei equivalent function _balance(address _address, address _asset) internal view returns (uint) { if (_asset != address(0)) { return ERC20(_asset).balanceOf(_address); } else { return _address.balance; } } } // File: burner.sol /** * IBurner - The Consumer Contract Wallet * Copyright (C) 2019 The Contract Wallet Company Limited * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.10; // The BurnerToken interface is the interface to a token contract which // provides the total burnable supply for the TokenHolder contract. interface IBurner { function currentSupply() external view returns (uint); } // File: ownable.sol /** * Ownable - The Consumer Contract Wallet * Copyright (C) 2019 The Contract Wallet Company Limited * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.10; /// @title Ownable has an owner address and provides basic authorization control functions. /// This contract is modified version of the MIT OpenZepplin Ownable contract /// This contract allows for the transferOwnership operation to be made impossible /// https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ownership/Ownable.sol contract Ownable { event TransferredOwnership(address _from, address _to); event LockedOwnership(address _locked); address payable private _owner; bool private _isTransferable; /// @notice Constructor sets the original owner of the contract and whether or not it is one time transferable. constructor(address payable _account_, bool _transferable_) internal { _owner = _account_; _isTransferable = _transferable_; // Emit the LockedOwnership event if no longer transferable. if (!_isTransferable) { emit LockedOwnership(_account_); } emit TransferredOwnership(address(0), _account_); } /// @notice Reverts if called by any account other than the owner. modifier onlyOwner() { require(_isOwner(msg.sender), "sender is not an owner"); _; } /// @notice Allows the current owner to transfer control of the contract to a new address. /// @param _account address to transfer ownership to. /// @param _transferable indicates whether to keep the ownership transferable. function transferOwnership(address payable _account, bool _transferable) external onlyOwner { // Require that the ownership is transferable. require(_isTransferable, "ownership is not transferable"); // Require that the new owner is not the zero address. require(_account != address(0), "owner cannot be set to zero address"); // Set the transferable flag to the value _transferable passed in. _isTransferable = _transferable; // Emit the LockedOwnership event if no longer transferable. if (!_transferable) { emit LockedOwnership(_account); } // Emit the ownership transfer event. emit TransferredOwnership(_owner, _account); // Set the owner to the provided address. _owner = _account; } /// @notice check if the ownership is transferable. /// @return true if the ownership is transferable. function isTransferable() external view returns (bool) { return _isTransferable; } /// @notice Allows the current owner to relinquish control of the contract. /// @dev Renouncing to ownership will leave the contract without an owner and unusable. /// @dev It will not be possible to call the functions with the `onlyOwner` modifier anymore. function renounceOwnership() external onlyOwner { // Require that the ownership is transferable. require(_isTransferable, "ownership is not transferable"); // note that this could be terminal _owner = address(0); emit TransferredOwnership(_owner, address(0)); } /// @notice Find out owner address /// @return address of the owner. function owner() public view returns (address payable) { return _owner; } /// @notice Check if owner address /// @return true if sender is the owner of the contract. function _isOwner(address _address) internal view returns (bool) { return _address == _owner; } } // File: controller.sol /** * Controller - The Consumer Contract Wallet * Copyright (C) 2019 The Contract Wallet Company Limited * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.10; /// @title The IController interface provides access to the isController and isAdmin checks. interface IController { function isController(address) external view returns (bool); function isAdmin(address) external view returns (bool); } /// @title Controller stores a list of controller addresses that can be used for authentication in other contracts. /// @notice The Controller implements a hierarchy of concepts, Owner, Admin, and the Controllers. /// @dev Owner can change the Admins /// @dev Admins and can the Controllers /// @dev Controllers are used by the application. contract Controller is IController, Ownable, Transferrable { event AddedController(address _sender, address _controller); event RemovedController(address _sender, address _controller); event AddedAdmin(address _sender, address _admin); event RemovedAdmin(address _sender, address _admin); event Claimed(address _to, address _asset, uint _amount); event Stopped(address _sender); event Started(address _sender); mapping (address => bool) private _isAdmin; uint private _adminCount; mapping (address => bool) private _isController; uint private _controllerCount; bool private _stopped; /// @notice Constructor initializes the owner with the provided address. /// @param _ownerAddress_ address of the owner. constructor(address payable _ownerAddress_) Ownable(_ownerAddress_, false) public {} /// @notice Checks if message sender is an admin. modifier onlyAdmin() { require(isAdmin(msg.sender), "sender is not an admin"); _; } /// @notice Check if Owner or Admin modifier onlyAdminOrOwner() { require(_isOwner(msg.sender) || isAdmin(msg.sender), "sender is not an admin"); _; } /// @notice Check if controller is stopped modifier notStopped() { require(!isStopped(), "controller is stopped"); _; } /// @notice Add a new admin to the list of admins. /// @param _account address to add to the list of admins. function addAdmin(address _account) external onlyOwner notStopped { _addAdmin(_account); } /// @notice Remove a admin from the list of admins. /// @param _account address to remove from the list of admins. function removeAdmin(address _account) external onlyOwner { _removeAdmin(_account); } /// @return the current number of admins. function adminCount() external view returns (uint) { return _adminCount; } /// @notice Add a new controller to the list of controllers. /// @param _account address to add to the list of controllers. function addController(address _account) external onlyAdminOrOwner notStopped { _addController(_account); } /// @notice Remove a controller from the list of controllers. /// @param _account address to remove from the list of controllers. function removeController(address _account) external onlyAdminOrOwner { _removeController(_account); } /// @notice count the Controllers /// @return the current number of controllers. function controllerCount() external view returns (uint) { return _controllerCount; } /// @notice is an address an Admin? /// @return true if the provided account is an admin. function isAdmin(address _account) public view notStopped returns (bool) { return _isAdmin[_account]; } /// @notice is an address a Controller? /// @return true if the provided account is a controller. function isController(address _account) public view notStopped returns (bool) { return _isController[_account]; } /// @notice this function can be used to see if the controller has been stopped /// @return true is the Controller has been stopped function isStopped() public view returns (bool) { return _stopped; } /// @notice Internal-only function that adds a new admin. function _addAdmin(address _account) private { require(!_isAdmin[_account], "provided account is already an admin"); require(!_isController[_account], "provided account is already a controller"); require(!_isOwner(_account), "provided account is already the owner"); require(_account != address(0), "provided account is the zero address"); _isAdmin[_account] = true; _adminCount++; emit AddedAdmin(msg.sender, _account); } /// @notice Internal-only function that removes an existing admin. function _removeAdmin(address _account) private { require(_isAdmin[_account], "provided account is not an admin"); _isAdmin[_account] = false; _adminCount--; emit RemovedAdmin(msg.sender, _account); } /// @notice Internal-only function that adds a new controller. function _addController(address _account) private { require(!_isAdmin[_account], "provided account is already an admin"); require(!_isController[_account], "provided account is already a controller"); require(!_isOwner(_account), "provided account is already the owner"); require(_account != address(0), "provided account is the zero address"); _isController[_account] = true; _controllerCount++; emit AddedController(msg.sender, _account); } /// @notice Internal-only function that removes an existing controller. function _removeController(address _account) private { require(_isController[_account], "provided account is not a controller"); _isController[_account] = false; _controllerCount--; emit RemovedController(msg.sender, _account); } /// @notice stop our controllers and admins from being useable function stop() external onlyAdminOrOwner { _stopped = true; emit Stopped(msg.sender); } /// @notice start our controller again function start() external onlyOwner { _stopped = false; emit Started(msg.sender); } //// @notice Withdraw tokens from the smart contract to the specified account. function claim(address payable _to, address _asset, uint _amount) external onlyAdmin notStopped { _safeTransfer(_to, _asset, _amount); emit Claimed(_to, _asset, _amount); } } // File: ENS.sol /** * BSD 2-Clause License * * Copyright (c) 2018, True Names Limited * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ pragma solidity ^0.5.0; interface ENS { // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed node, address resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed node, uint64 ttl); function setSubnodeOwner(bytes32 node, bytes32 label, address owner) external; function setResolver(bytes32 node, address resolver) external; function setOwner(bytes32 node, address owner) external; function setTTL(bytes32 node, uint64 ttl) external; function owner(bytes32 node) external view returns (address); function resolver(bytes32 node) external view returns (address); function ttl(bytes32 node) external view returns (uint64); } // File: ResolverBase.sol pragma solidity ^0.5.0; contract ResolverBase { bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7; function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == INTERFACE_META_ID; } function isAuthorised(bytes32 node) internal view returns(bool); modifier authorised(bytes32 node) { require(isAuthorised(node)); _; } } // File: ABIResolver.sol pragma solidity ^0.5.0; contract ABIResolver is ResolverBase { bytes4 constant private ABI_INTERFACE_ID = 0x2203ab56; event ABIChanged(bytes32 indexed node, uint256 indexed contentType); mapping(bytes32=>mapping(uint256=>bytes)) abis; /** * Sets the ABI associated with an ENS node. * Nodes may have one ABI of each content type. To remove an ABI, set it to * the empty string. * @param node The node to update. * @param contentType The content type of the ABI * @param data The ABI data. */ function setABI(bytes32 node, uint256 contentType, bytes calldata data) external authorised(node) { // Content types must be powers of 2 require(((contentType - 1) & contentType) == 0); abis[node][contentType] = data; emit ABIChanged(node, contentType); } /** * Returns the ABI associated with an ENS node. * Defined in EIP205. * @param node The ENS node to query * @param contentTypes A bitwise OR of the ABI formats accepted by the caller. * @return contentType The content type of the return value * @return data The ABI data */ function ABI(bytes32 node, uint256 contentTypes) external view returns (uint256, bytes memory) { mapping(uint256=>bytes) storage abiset = abis[node]; for (uint256 contentType = 1; contentType <= contentTypes; contentType <<= 1) { if ((contentType & contentTypes) != 0 && abiset[contentType].length > 0) { return (contentType, abiset[contentType]); } } return (0, bytes("")); } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == ABI_INTERFACE_ID || super.supportsInterface(interfaceID); } } // File: AddrResolver.sol pragma solidity ^0.5.0; contract AddrResolver is ResolverBase { bytes4 constant private ADDR_INTERFACE_ID = 0x3b3b57de; event AddrChanged(bytes32 indexed node, address a); mapping(bytes32=>address) addresses; /** * Sets the address associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param addr The address to set. */ function setAddr(bytes32 node, address addr) external authorised(node) { addresses[node] = addr; emit AddrChanged(node, addr); } /** * Returns the address associated with an ENS node. * @param node The ENS node to query. * @return The associated address. */ function addr(bytes32 node) public view returns (address) { return addresses[node]; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == ADDR_INTERFACE_ID || super.supportsInterface(interfaceID); } } // File: ContentHashResolver.sol pragma solidity ^0.5.0; contract ContentHashResolver is ResolverBase { bytes4 constant private CONTENT_HASH_INTERFACE_ID = 0xbc1c58d1; event ContenthashChanged(bytes32 indexed node, bytes hash); mapping(bytes32=>bytes) hashes; /** * Sets the contenthash associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param hash The contenthash to set */ function setContenthash(bytes32 node, bytes calldata hash) external authorised(node) { hashes[node] = hash; emit ContenthashChanged(node, hash); } /** * Returns the contenthash associated with an ENS node. * @param node The ENS node to query. * @return The associated contenthash. */ function contenthash(bytes32 node) external view returns (bytes memory) { return hashes[node]; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == CONTENT_HASH_INTERFACE_ID || super.supportsInterface(interfaceID); } } // File: InterfaceResolver.sol pragma solidity ^0.5.0; contract InterfaceResolver is ResolverBase, AddrResolver { bytes4 constant private INTERFACE_INTERFACE_ID = bytes4(keccak256("interfaceImplementer(bytes32,bytes4)")); bytes4 private constant INTERFACE_META_ID = 0x01ffc9a7; event InterfaceChanged(bytes32 indexed node, bytes4 indexed interfaceID, address implementer); mapping(bytes32=>mapping(bytes4=>address)) interfaces; /** * Sets an interface associated with a name. * Setting the address to 0 restores the default behaviour of querying the contract at `addr()` for interface support. * @param node The node to update. * @param interfaceID The EIP 168 interface ID. * @param implementer The address of a contract that implements this interface for this node. */ function setInterface(bytes32 node, bytes4 interfaceID, address implementer) external authorised(node) { interfaces[node][interfaceID] = implementer; emit InterfaceChanged(node, interfaceID, implementer); } /** * Returns the address of a contract that implements the specified interface for this name. * If an implementer has not been set for this interfaceID and name, the resolver will query * the contract at `addr()`. If `addr()` is set, a contract exists at that address, and that * contract implements EIP168 and returns `true` for the specified interfaceID, its address * will be returned. * @param node The ENS node to query. * @param interfaceID The EIP 168 interface ID to check for. * @return The address that implements this interface, or 0 if the interface is unsupported. */ function interfaceImplementer(bytes32 node, bytes4 interfaceID) external view returns (address) { address implementer = interfaces[node][interfaceID]; if(implementer != address(0)) { return implementer; } address a = addr(node); if(a == address(0)) { return address(0); } (bool success, bytes memory returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", INTERFACE_META_ID)); if(!success || returnData.length < 32 || returnData[31] == 0) { // EIP 168 not supported by target return address(0); } (success, returnData) = a.staticcall(abi.encodeWithSignature("supportsInterface(bytes4)", interfaceID)); if(!success || returnData.length < 32 || returnData[31] == 0) { // Specified interface not supported by target return address(0); } return a; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == INTERFACE_INTERFACE_ID || super.supportsInterface(interfaceID); } } // File: NameResolver.sol pragma solidity ^0.5.0; contract NameResolver is ResolverBase { bytes4 constant private NAME_INTERFACE_ID = 0x691f3431; event NameChanged(bytes32 indexed node, string name); mapping(bytes32=>string) names; /** * Sets the name associated with an ENS node, for reverse records. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param name The name to set. */ function setName(bytes32 node, string calldata name) external authorised(node) { names[node] = name; emit NameChanged(node, name); } /** * Returns the name associated with an ENS node, for reverse records. * Defined in EIP181. * @param node The ENS node to query. * @return The associated name. */ function name(bytes32 node) external view returns (string memory) { return names[node]; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == NAME_INTERFACE_ID || super.supportsInterface(interfaceID); } } // File: PubkeyResolver.sol pragma solidity ^0.5.0; contract PubkeyResolver is ResolverBase { bytes4 constant private PUBKEY_INTERFACE_ID = 0xc8690233; event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y); struct PublicKey { bytes32 x; bytes32 y; } mapping(bytes32=>PublicKey) pubkeys; /** * Sets the SECP256k1 public key associated with an ENS node. * @param node The ENS node to query * @param x the X coordinate of the curve point for the public key. * @param y the Y coordinate of the curve point for the public key. */ function setPubkey(bytes32 node, bytes32 x, bytes32 y) external authorised(node) { pubkeys[node] = PublicKey(x, y); emit PubkeyChanged(node, x, y); } /** * Returns the SECP256k1 public key associated with an ENS node. * Defined in EIP 619. * @param node The ENS node to query * @return x, y the X and Y coordinates of the curve point for the public key. */ function pubkey(bytes32 node) external view returns (bytes32 x, bytes32 y) { return (pubkeys[node].x, pubkeys[node].y); } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == PUBKEY_INTERFACE_ID || super.supportsInterface(interfaceID); } } // File: TextResolver.sol pragma solidity ^0.5.0; contract TextResolver is ResolverBase { bytes4 constant private TEXT_INTERFACE_ID = 0x59d1d43c; event TextChanged(bytes32 indexed node, string indexedKey, string key); mapping(bytes32=>mapping(string=>string)) texts; /** * Sets the text data associated with an ENS node and key. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param key The key to set. * @param value The text data value to set. */ function setText(bytes32 node, string calldata key, string calldata value) external authorised(node) { texts[node][key] = value; emit TextChanged(node, key, key); } /** * Returns the text data associated with an ENS node and key. * @param node The ENS node to query. * @param key The text data key to query. * @return The associated text data. */ function text(bytes32 node, string calldata key) external view returns (string memory) { return texts[node][key]; } function supportsInterface(bytes4 interfaceID) public pure returns(bool) { return interfaceID == TEXT_INTERFACE_ID || super.supportsInterface(interfaceID); } } // File: PublicResolver.sol /** * BSD 2-Clause License * * Copyright (c) 2018, True Names Limited * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ pragma solidity ^0.5.0; /** * A simple resolver anyone can use; only allows the owner of a node to set its * address. */ contract PublicResolver is ABIResolver, AddrResolver, ContentHashResolver, InterfaceResolver, NameResolver, PubkeyResolver, TextResolver { ENS ens; /** * A mapping of authorisations. An address that is authorised for a name * may make any changes to the name that the owner could, but may not update * the set of authorisations. * (node, owner, caller) => isAuthorised */ mapping(bytes32=>mapping(address=>mapping(address=>bool))) public authorisations; event AuthorisationChanged(bytes32 indexed node, address indexed owner, address indexed target, bool isAuthorised); constructor(ENS _ens) public { ens = _ens; } /** * @dev Sets or clears an authorisation. * Authorisations are specific to the caller. Any account can set an authorisation * for any name, but the authorisation that is checked will be that of the * current owner of a name. Thus, transferring a name effectively clears any * existing authorisations, and new authorisations can be set in advance of * an ownership transfer if desired. * * @param node The name to change the authorisation on. * @param target The address that is to be authorised or deauthorised. * @param isAuthorised True if the address should be authorised, or false if it should be deauthorised. */ function setAuthorisation(bytes32 node, address target, bool isAuthorised) external { authorisations[node][msg.sender][target] = isAuthorised; emit AuthorisationChanged(node, msg.sender, target, isAuthorised); } function isAuthorised(bytes32 node) internal view returns(bool) { address owner = ens.owner(node); return owner == msg.sender || authorisations[node][owner][msg.sender]; } } // File: ensResolvable.sol /** * ENSResolvable - The Consumer Contract Wallet * Copyright (C) 2019 The Contract Wallet Company Limited * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.10; ///@title ENSResolvable - Ethereum Name Service Resolver ///@notice contract should be used to get an address for an ENS node contract ENSResolvable { /// @notice _ens is an instance of ENS ENS private _ens; /// @notice _ensRegistry points to the ENS registry smart contract. address private _ensRegistry; /// @param _ensReg_ is the ENS registry used constructor(address _ensReg_) internal { _ensRegistry = _ensReg_; _ens = ENS(_ensRegistry); } /// @notice this is used to that one can observe which ENS registry is being used function ensRegistry() external view returns (address) { return _ensRegistry; } /// @notice helper function used to get the address of a node /// @param _node of the ENS entry that needs resolving /// @return the address of the said node function _ensResolve(bytes32 _node) internal view returns (address) { return PublicResolver(_ens.resolver(_node)).addr(_node); } } // File: controllable.sol /** * Controllable - The Consumer Contract Wallet * Copyright (C) 2019 The Contract Wallet Company Limited * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.10; /// @title Controllable implements access control functionality of the Controller found via ENS. contract Controllable is ENSResolvable { /// @dev Is the registered ENS node identifying the controller contract. bytes32 private _controllerNode; /// @notice Constructor initializes the controller contract object. /// @param _controllerNode_ is the ENS node of the Controller. constructor(bytes32 _controllerNode_) internal { _controllerNode = _controllerNode_; } /// @notice Checks if message sender is a controller. modifier onlyController() { require(_isController(msg.sender), "sender is not a controller"); _; } /// @notice Checks if message sender is an admin. modifier onlyAdmin() { require(_isAdmin(msg.sender), "sender is not an admin"); _; } /// @return the controller node registered in ENS. function controllerNode() external view returns (bytes32) { return _controllerNode; } /// @return true if the provided account is a controller. function _isController(address _account) internal view returns (bool) { return IController(_ensResolve(_controllerNode)).isController(_account); } /// @return true if the provided account is an admin. function _isAdmin(address _account) internal view returns (bool) { return IController(_ensResolve(_controllerNode)).isAdmin(_account); } } // File: bytesUtils.sol /** * BytesUtils - The Consumer Contract Wallet * Copyright (C) 2019 The Contract Wallet Company Limited * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.10; /// @title BytesUtils provides basic byte slicing and casting functionality. library BytesUtils { using SafeMath for uint256; /// @dev This function converts to an address /// @param _bts bytes /// @param _from start position function _bytesToAddress(bytes memory _bts, uint _from) internal pure returns (address) { require(_bts.length >= _from.add(20), "slicing out of range"); bytes20 convertedAddress; uint startByte = _from.add(32); //first 32 bytes denote the array length assembly { convertedAddress := mload(add(_bts, startByte)) } return address(convertedAddress); } /// @dev This function slices bytes into bytes4 /// @param _bts some bytes /// @param _from start position function _bytesToBytes4(bytes memory _bts, uint _from) internal pure returns (bytes4) { require(_bts.length >= _from.add(4), "slicing out of range"); bytes4 slicedBytes4; uint startByte = _from.add(32); //first 32 bytes denote the array length assembly { slicedBytes4 := mload(add(_bts, startByte)) } return slicedBytes4; } /// @dev This function slices a uint /// @param _bts some bytes /// @param _from start position // credit to https://ethereum.stackexchange.com/questions/51229/how-to-convert-bytes-to-uint-in-solidity // and Nick Johnson https://ethereum.stackexchange.com/questions/4170/how-to-convert-a-uint-to-bytes-in-solidity/4177#4177 function _bytesToUint256(bytes memory _bts, uint _from) internal pure returns (uint) { require(_bts.length >= _from.add(32), "slicing out of range"); uint convertedUint256; uint startByte = _from.add(32); //first 32 bytes denote the array length assembly { convertedUint256 := mload(add(_bts, startByte)) } return convertedUint256; } } // File: strings.sol /* * Copyright 2016 Nick Johnson * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * @title String & slice utility library for Solidity contracts. * @author Nick Johnson <arachnid@notdot.net> * * @dev Functionality in this library is largely implemented using an * abstraction called a 'slice'. A slice represents a part of a string - * anything from the entire string to a single character, or even no * characters at all (a 0-length slice). Since a slice only has to specify * an offset and a length, copying and manipulating slices is a lot less * expensive than copying and manipulating the strings they reference. * * To further reduce gas costs, most functions on slice that need to return * a slice modify the original one instead of allocating a new one; for * instance, `s.split(".")` will return the text up to the first '.', * modifying s to only contain the remainder of the string after the '.'. * In situations where you do not want to modify the original slice, you * can make a copy first with `.copy()`, for example: * `s.copy().split(".")`. Try and avoid using this idiom in loops; since * Solidity has no memory management, it will result in allocating many * short-lived slices that are later discarded. * * Functions that return two slices come in two versions: a non-allocating * version that takes the second slice as an argument, modifying it in * place, and an allocating version that allocates and returns the second * slice; see `nextRune` for example. * * Functions that have to copy string data will return strings rather than * slices; these can be cast back to slices for further processing if * required. * * For convenience, some functions are provided with non-modifying * variants that create a new slice and return both; for instance, * `s.splitNew('.')` leaves s unmodified, and returns two values * corresponding to the left and right parts of the string. */ pragma solidity ^0.5.0; library strings { struct slice { uint _len; uint _ptr; } function memcpy(uint dest, uint src, uint len) private pure { // Copy word-length chunks while possible for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /* * @dev Returns a slice containing the entire string. * @param self The string to make a slice from. * @return A newly allocated slice containing the entire string. */ function toSlice(string memory self) internal pure returns (slice memory) { uint ptr; assembly { ptr := add(self, 0x20) } return slice(bytes(self).length, ptr); } /* * @dev Returns the length of a null-terminated bytes32 string. * @param self The value to find the length of. * @return The length of the string, from 0 to 32. */ function len(bytes32 self) internal pure returns (uint) { uint ret; if (self == 0) return 0; if (uint(self) & 0xffffffffffffffffffffffffffffffff == 0) { ret += 16; self = bytes32(uint(self) / 0x100000000000000000000000000000000); } if (uint(self) & 0xffffffffffffffff == 0) { ret += 8; self = bytes32(uint(self) / 0x10000000000000000); } if (uint(self) & 0xffffffff == 0) { ret += 4; self = bytes32(uint(self) / 0x100000000); } if (uint(self) & 0xffff == 0) { ret += 2; self = bytes32(uint(self) / 0x10000); } if (uint(self) & 0xff == 0) { ret += 1; } return 32 - ret; } /* * @dev Returns a slice containing the entire bytes32, interpreted as a * null-terminated utf-8 string. * @param self The bytes32 value to convert to a slice. * @return A new slice containing the value of the input argument up to the * first null. */ function toSliceB32(bytes32 self) internal pure returns (slice memory ret) { // Allocate space for `self` in memory, copy it there, and point ret at it assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 0x20)) mstore(ptr, self) mstore(add(ret, 0x20), ptr) } ret._len = len(self); } /* * @dev Returns a new slice containing the same data as the current slice. * @param self The slice to copy. * @return A new slice containing the same data as `self`. */ function copy(slice memory self) internal pure returns (slice memory) { return slice(self._len, self._ptr); } /* * @dev Copies a slice to a new string. * @param self The slice to copy. * @return A newly allocated string containing the slice's text. */ function toString(slice memory self) internal pure returns (string memory) { string memory ret = new string(self._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); return ret; } /* * @dev Returns the length in runes of the slice. Note that this operation * takes time proportional to the length of the slice; avoid using it * in loops, and call `slice.empty()` if you only need to know whether * the slice is empty or not. * @param self The slice to operate on. * @return The length of the slice in runes. */ function len(slice memory self) internal pure returns (uint l) { // Starting at ptr-31 means the LSB will be the byte we care about uint ptr = self._ptr - 31; uint end = ptr + self._len; for (l = 0; ptr < end; l++) { uint8 b; assembly { b := and(mload(ptr), 0xFF) } if (b < 0x80) { ptr += 1; } else if (b < 0xE0) { ptr += 2; } else if (b < 0xF0) { ptr += 3; } else if (b < 0xF8) { ptr += 4; } else if (b < 0xFC) { ptr += 5; } else { ptr += 6; } } } /* * @dev Returns true if the slice is empty (has a length of 0). * @param self The slice to operate on. * @return True if the slice is empty, False otherwise. */ function empty(slice memory self) internal pure returns (bool) { return self._len == 0; } /* * @dev Returns a positive number if `other` comes lexicographically after * `self`, a negative number if it comes before, or zero if the * contents of the two slices are equal. Comparison is done per-rune, * on unicode codepoints. * @param self The first slice to compare. * @param other The second slice to compare. * @return The result of the comparison. */ function compare(slice memory self, slice memory other) internal pure returns (int) { uint shortest = self._len; if (other._len < self._len) shortest = other._len; uint selfptr = self._ptr; uint otherptr = other._ptr; for (uint idx = 0; idx < shortest; idx += 32) { uint a; uint b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { // Mask out irrelevant bytes and check again uint256 mask = uint256(-1); // 0xffff... if (shortest < 32) { mask = ~(2 ** (8 * (32 - shortest + idx)) - 1); } uint256 diff = (a & mask) - (b & mask); if (diff != 0) return int(diff); } selfptr += 32; otherptr += 32; } return int(self._len) - int(other._len); } /* * @dev Returns true if the two slices contain the same text. * @param self The first slice to compare. * @param self The second slice to compare. * @return True if the slices are equal, false otherwise. */ function equals(slice memory self, slice memory other) internal pure returns (bool) { return compare(self, other) == 0; } /* * @dev Extracts the first rune in the slice into `rune`, advancing the * slice to point to the next rune and returning `self`. * @param self The slice to operate on. * @param rune The slice that will contain the first rune. * @return `rune`. */ function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) { rune._ptr = self._ptr; if (self._len == 0) { rune._len = 0; return rune; } uint l; uint b; // Load the first byte of the rune into the LSBs of b assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) } if (b < 0x80) { l = 1; } else if (b < 0xE0) { l = 2; } else if (b < 0xF0) { l = 3; } else { l = 4; } // Check for truncated codepoints if (l > self._len) { rune._len = self._len; self._ptr += self._len; self._len = 0; return rune; } self._ptr += l; self._len -= l; rune._len = l; return rune; } /* * @dev Returns the first rune in the slice, advancing the slice to point * to the next rune. * @param self The slice to operate on. * @return A slice containing only the first rune from `self`. */ function nextRune(slice memory self) internal pure returns (slice memory ret) { nextRune(self, ret); } /* * @dev Returns the number of the first codepoint in the slice. * @param self The slice to operate on. * @return The number of the first codepoint in the slice. */ function ord(slice memory self) internal pure returns (uint ret) { if (self._len == 0) { return 0; } uint word; uint length; uint divisor = 2 ** 248; // Load the rune into the MSBs of b assembly { word:= mload(mload(add(self, 32))) } uint b = word / divisor; if (b < 0x80) { ret = b; length = 1; } else if (b < 0xE0) { ret = b & 0x1F; length = 2; } else if (b < 0xF0) { ret = b & 0x0F; length = 3; } else { ret = b & 0x07; length = 4; } // Check for truncated codepoints if (length > self._len) { return 0; } for (uint i = 1; i < length; i++) { divisor = divisor / 256; b = (word / divisor) & 0xFF; if (b & 0xC0 != 0x80) { // Invalid UTF-8 sequence return 0; } ret = (ret * 64) | (b & 0x3F); } return ret; } /* * @dev Returns the keccak-256 hash of the slice. * @param self The slice to hash. * @return The hash of the slice. */ function keccak(slice memory self) internal pure returns (bytes32 ret) { assembly { ret := keccak256(mload(add(self, 32)), mload(self)) } } /* * @dev Returns true if `self` starts with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function startsWith(slice memory self, slice memory needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } if (self._ptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` starts with `needle`, `needle` is removed from the * beginning of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) { if (self._len < needle._len) { return self; } bool equal = true; if (self._ptr != needle._ptr) { assembly { let length := mload(needle) let selfptr := mload(add(self, 0x20)) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; self._ptr += needle._len; } return self; } /* * @dev Returns true if the slice ends with `needle`. * @param self The slice to operate on. * @param needle The slice to search for. * @return True if the slice starts with the provided text, false otherwise. */ function endsWith(slice memory self, slice memory needle) internal pure returns (bool) { if (self._len < needle._len) { return false; } uint selfptr = self._ptr + self._len - needle._len; if (selfptr == needle._ptr) { return true; } bool equal; assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } return equal; } /* * @dev If `self` ends with `needle`, `needle` is removed from the * end of `self`. Otherwise, `self` is unmodified. * @param self The slice to operate on. * @param needle The slice to search for. * @return `self` */ function until(slice memory self, slice memory needle) internal pure returns (slice memory) { if (self._len < needle._len) { return self; } uint selfptr = self._ptr + self._len - needle._len; bool equal = true; if (selfptr != needle._ptr) { assembly { let length := mload(needle) let needleptr := mload(add(needle, 0x20)) equal := eq(keccak256(selfptr, length), keccak256(needleptr, length)) } } if (equal) { self._len -= needle._len; } return self; } // Returns the memory address of the first byte of the first occurrence of // `needle` in `self`, or the first byte after `self` if not found. function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr = selfptr; uint idx; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } uint end = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr >= end) return selfptr + selflen; ptr++; assembly { ptrdata := and(mload(ptr), mask) } } return ptr; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } for (idx = 0; idx <= selflen - needlelen; idx++) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr; ptr += 1; } } } return selfptr + selflen; } // Returns the memory address of the first byte after the last occurrence of // `needle` in `self`, or the address of `self` if not found. function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { uint ptr; if (needlelen <= selflen) { if (needlelen <= 32) { bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1)); bytes32 needledata; assembly { needledata := and(mload(needleptr), mask) } ptr = selfptr + selflen - needlelen; bytes32 ptrdata; assembly { ptrdata := and(mload(ptr), mask) } while (ptrdata != needledata) { if (ptr <= selfptr) return selfptr; ptr--; assembly { ptrdata := and(mload(ptr), mask) } } return ptr + needlelen; } else { // For long needles, use hashing bytes32 hash; assembly { hash := keccak256(needleptr, needlelen) } ptr = selfptr + (selflen - needlelen); while (ptr >= selfptr) { bytes32 testHash; assembly { testHash := keccak256(ptr, needlelen) } if (hash == testHash) return ptr + needlelen; ptr -= 1; } } } return selfptr; } /* * @dev Modifies `self` to contain everything from the first occurrence of * `needle` to the end of the slice. `self` is set to the empty slice * if `needle` is not found. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function find(slice memory self, slice memory needle) internal pure returns (slice memory) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); self._len -= ptr - self._ptr; self._ptr = ptr; return self; } /* * @dev Modifies `self` to contain the part of the string from the start of * `self` to the end of the first occurrence of `needle`. If `needle` * is not found, `self` is set to the empty slice. * @param self The slice to search and modify. * @param needle The text to search for. * @return `self`. */ function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); self._len = ptr - self._ptr; return self; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and `token` to everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = self._ptr; token._len = ptr - self._ptr; if (ptr == self._ptr + self._len) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; self._ptr = ptr + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything after the first * occurrence of `needle`, and returning everything before it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` up to the first occurrence of `delim`. */ function split(slice memory self, slice memory needle) internal pure returns (slice memory token) { split(self, needle, token); } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and `token` to everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and `token` is set to the entirety of `self`. * @param self The slice to split. * @param needle The text to search for in `self`. * @param token An output parameter to which the first token is written. * @return `token`. */ function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr); token._ptr = ptr; token._len = self._len - (ptr - self._ptr); if (ptr == self._ptr) { // Not found self._len = 0; } else { self._len -= token._len + needle._len; } return token; } /* * @dev Splits the slice, setting `self` to everything before the last * occurrence of `needle`, and returning everything after it. If * `needle` does not occur in `self`, `self` is set to the empty slice, * and the entirety of `self` is returned. * @param self The slice to split. * @param needle The text to search for in `self`. * @return The part of `self` after the last occurrence of `delim`. */ function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) { rsplit(self, needle, token); } /* * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return The number of occurrences of `needle` found in `self`. */ function count(slice memory self, slice memory needle) internal pure returns (uint cnt) { uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len; while (ptr <= self._ptr + self._len) { cnt++; ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len; } } /* * @dev Returns True if `self` contains `needle`. * @param self The slice to search. * @param needle The text to search for in `self`. * @return True if `needle` is found in `self`, false otherwise. */ function contains(slice memory self, slice memory needle) internal pure returns (bool) { return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr; } /* * @dev Returns a newly allocated string containing the concatenation of * `self` and `other`. * @param self The first slice to concatenate. * @param other The second slice to concatenate. * @return The concatenation of the two strings. */ function concat(slice memory self, slice memory other) internal pure returns (string memory) { string memory ret = new string(self._len + other._len); uint retptr; assembly { retptr := add(ret, 32) } memcpy(retptr, self._ptr, self._len); memcpy(retptr + self._len, other._ptr, other._len); return ret; } /* * @dev Joins an array of slices, using `self` as a delimiter, returning a * newly allocated string. * @param self The delimiter to use. * @param parts A list of slices to join. * @return A newly allocated string containing all the slices in `parts`, * joined with `self`. */ function join(slice memory self, slice[] memory parts) internal pure returns (string memory) { if (parts.length == 0) return ""; uint length = self._len * (parts.length - 1); for (uint i = 0; i < parts.length; i++) { length += parts[i]._len; } string memory ret = new string(length); uint retptr; assembly { retptr := add(ret, 32) } for (uint i = 0; i < parts.length; i++) { memcpy(retptr, parts[i]._ptr, parts[i]._len); retptr += parts[i]._len; if (i < parts.length - 1) { memcpy(retptr, self._ptr, self._len); retptr += self._len; } } return ret; } } // File: tokenWhitelist.sol /** * TokenWhitelist - The Consumer Contract Wallet * Copyright (C) 2019 The Contract Wallet Company Limited * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.10; /// @title The ITokenWhitelist interface provides access to a whitelist of tokens. interface ITokenWhitelist { function getTokenInfo(address) external view returns (string memory, uint256, uint256, bool, bool, bool, uint256); function getStablecoinInfo() external view returns (string memory, uint256, uint256, bool, bool, bool, uint256); function tokenAddressArray() external view returns (address[] memory); function redeemableTokens() external view returns (address[] memory); function methodIdWhitelist(bytes4) external view returns (bool); function getERC20RecipientAndAmount(address, bytes calldata) external view returns (address, uint); function stablecoin() external view returns (address); function updateTokenRate(address, uint, uint) external; } /// @title TokenWhitelist stores a list of tokens used by the Consumer Contract Wallet, the Oracle, the TKN Holder and the TKN Licence Contract contract TokenWhitelist is ENSResolvable, Controllable, Transferrable { using strings for *; using SafeMath for uint256; using BytesUtils for bytes; event UpdatedTokenRate(address _sender, address _token, uint _rate); event UpdatedTokenLoadable(address _sender, address _token, bool _loadable); event UpdatedTokenRedeemable(address _sender, address _token, bool _redeemable); event AddedToken(address _sender, address _token, string _symbol, uint _magnitude, bool _loadable, bool _redeemable); event RemovedToken(address _sender, address _token); event AddedMethodId(bytes4 _methodId); event RemovedMethodId(bytes4 _methodId); event AddedExclusiveMethod(address _token, bytes4 _methodId); event RemovedExclusiveMethod(address _token, bytes4 _methodId); event Claimed(address _to, address _asset, uint _amount); /// @dev these are the methods whitelisted by default in executeTransaction() for protected tokens bytes4 private constant _APPROVE = 0x095ea7b3; // keccak256(approve(address,uint256)) => 0x095ea7b3 bytes4 private constant _BURN = 0x42966c68; // keccak256(burn(uint256)) => 0x42966c68 bytes4 private constant _TRANSFER= 0xa9059cbb; // keccak256(transfer(address,uint256)) => 0xa9059cbb bytes4 private constant _TRANSFER_FROM = 0x23b872dd; // keccak256(transferFrom(address,address,uint256)) => 0x23b872dd struct Token { string symbol; // Token symbol uint magnitude; // 10^decimals uint rate; // Token exchange rate in wei bool available; // Flags if the token is available or not bool loadable; // Flags if token is loadable to the TokenCard bool redeemable; // Flags if token is redeemable in the TKN Holder contract uint lastUpdate; // Time of the last rate update } mapping(address => Token) private _tokenInfoMap; // @notice specifies whitelisted methodIds for protected tokens in wallet's excuteTranaction() e.g. keccak256(transfer(address,uint256)) => 0xa9059cbb mapping(bytes4 => bool) private _methodIdWhitelist; address[] private _tokenAddressArray; /// @notice keeping track of how many redeemable tokens are in the tokenWhitelist uint private _redeemableCounter; /// @notice Address of the stablecoin. address private _stablecoin; /// @notice is registered ENS node identifying the oracle contract. bytes32 private _oracleNode; /// @notice Constructor initializes ENSResolvable, and Controllable. /// @param _ens_ is the ENS registry address. /// @param _oracleNode_ is the ENS node of the Oracle. /// @param _controllerNode_ is our Controllers node. /// @param _stablecoinAddress_ is the address of the stablecoint used by the wallet for the card load limit. constructor(address _ens_, bytes32 _oracleNode_, bytes32 _controllerNode_, address _stablecoinAddress_) ENSResolvable(_ens_) Controllable(_controllerNode_) public { _oracleNode = _oracleNode_; _stablecoin = _stablecoinAddress_; //a priori ERC20 whitelisted methods _methodIdWhitelist[_APPROVE] = true; _methodIdWhitelist[_BURN] = true; _methodIdWhitelist[_TRANSFER] = true; _methodIdWhitelist[_TRANSFER_FROM] = true; } modifier onlyAdminOrOracle() { address oracleAddress = _ensResolve(_oracleNode); require (_isAdmin(msg.sender) || msg.sender == oracleAddress, "either oracle or admin"); _; } /// @notice Add ERC20 tokens to the list of whitelisted tokens. /// @param _tokens ERC20 token contract addresses. /// @param _symbols ERC20 token names. /// @param _magnitude 10 to the power of number of decimal places used by each ERC20 token. /// @param _loadable is a bool that states whether or not a token is loadable to the TokenCard. /// @param _redeemable is a bool that states whether or not a token is redeemable in the TKN Holder Contract. /// @param _lastUpdate is a unit representing an ISO datetime e.g. 20180913153211. function addTokens(address[] calldata _tokens, bytes32[] calldata _symbols, uint[] calldata _magnitude, bool[] calldata _loadable, bool[] calldata _redeemable, uint _lastUpdate) external onlyAdmin { // Require that all parameters have the same length. require(_tokens.length == _symbols.length && _tokens.length == _magnitude.length && _tokens.length == _loadable.length && _tokens.length == _loadable.length, "parameter lengths do not match"); // Add each token to the list of supported tokens. for (uint i = 0; i < _tokens.length; i++) { // Require that the token isn't already available. require(!_tokenInfoMap[_tokens[i]].available, "token already available"); // Store the intermediate values. string memory symbol = _symbols[i].toSliceB32().toString(); // Add the token to the token list. _tokenInfoMap[_tokens[i]] = Token({ symbol : symbol, magnitude : _magnitude[i], rate : 0, available : true, loadable : _loadable[i], redeemable: _redeemable[i], lastUpdate : _lastUpdate }); // Add the token address to the address list. _tokenAddressArray.push(_tokens[i]); //if the token is redeemable increase the redeemableCounter if (_redeemable[i]){ _redeemableCounter = _redeemableCounter.add(1); } // Emit token addition event. emit AddedToken(msg.sender, _tokens[i], symbol, _magnitude[i], _loadable[i], _redeemable[i]); } } /// @notice Remove ERC20 tokens from the whitelist of tokens. /// @param _tokens ERC20 token contract addresses. function removeTokens(address[] calldata _tokens) external onlyAdmin { // Delete each token object from the list of supported tokens based on the addresses provided. for (uint i = 0; i < _tokens.length; i++) { // Store the token address. address token = _tokens[i]; //token must be available, reverts on duplicates as well require(_tokenInfoMap[token].available, "token is not available"); //if the token is redeemable decrease the redeemableCounter if (_tokenInfoMap[token].redeemable){ _redeemableCounter = _redeemableCounter.sub(1); } // Delete the token object. delete _tokenInfoMap[token]; // Remove the token address from the address list. for (uint j = 0; j < _tokenAddressArray.length.sub(1); j++) { if (_tokenAddressArray[j] == token) { _tokenAddressArray[j] = _tokenAddressArray[_tokenAddressArray.length.sub(1)]; break; } } _tokenAddressArray.length--; // Emit token removal event. emit RemovedToken(msg.sender, token); } } /// @notice based on the method it returns the recipient address and amount/value, ERC20 specific. /// @param _data is the transaction payload. function getERC20RecipientAndAmount(address _token, bytes calldata _data) external view returns (address, uint) { // Require that there exist enough bytes for encoding at least a method signature + data in the transaction payload: // 4 (signature) + 32(address or uint256) require(_data.length >= 4 + 32, "not enough method-encoding bytes"); // Get the method signature bytes4 signature = _data._bytesToBytes4(0); // Check if method Id is supported require(isERC20MethodSupported(_token, signature), "unsupported method"); // returns the recipient's address and amount is the value to be transferred if (signature == _BURN) { // 4 (signature) + 32(uint256) return (_token, _data._bytesToUint256(4)); } else if (signature == _TRANSFER_FROM) { // 4 (signature) + 32(address) + 32(address) + 32(uint256) require(_data.length >= 4 + 32 + 32 + 32, "not enough data for transferFrom"); return ( _data._bytesToAddress(4 + 32 + 12), _data._bytesToUint256(4 + 32 + 32)); } else { //transfer or approve // 4 (signature) + 32(address) + 32(uint) require(_data.length >= 4 + 32 + 32, "not enough data for transfer/appprove"); return (_data._bytesToAddress(4 + 12), _data._bytesToUint256(4 + 32)); } } /// @notice Toggles whether or not a token is loadable or not. function setTokenLoadable(address _token, bool _loadable) external onlyAdmin { // Require that the token exists. require(_tokenInfoMap[_token].available, "token is not available"); // this sets the loadable flag to the value passed in _tokenInfoMap[_token].loadable = _loadable; emit UpdatedTokenLoadable(msg.sender, _token, _loadable); } /// @notice Toggles whether or not a token is redeemable or not. function setTokenRedeemable(address _token, bool _redeemable) external onlyAdmin { // Require that the token exists. require(_tokenInfoMap[_token].available, "token is not available"); // this sets the redeemable flag to the value passed in _tokenInfoMap[_token].redeemable = _redeemable; emit UpdatedTokenRedeemable(msg.sender, _token, _redeemable); } /// @notice Update ERC20 token exchange rate. /// @param _token ERC20 token contract address. /// @param _rate ERC20 token exchange rate in wei. /// @param _updateDate date for the token updates. This will be compared to when oracle updates are received. function updateTokenRate(address _token, uint _rate, uint _updateDate) external onlyAdminOrOracle { // Require that the token exists. require(_tokenInfoMap[_token].available, "token is not available"); // Update the token's rate. _tokenInfoMap[_token].rate = _rate; // Update the token's last update timestamp. _tokenInfoMap[_token].lastUpdate = _updateDate; // Emit the rate update event. emit UpdatedTokenRate(msg.sender, _token, _rate); } //// @notice Withdraw tokens from the smart contract to the specified account. function claim(address payable _to, address _asset, uint _amount) external onlyAdmin { _safeTransfer(_to, _asset, _amount); emit Claimed(_to, _asset, _amount); } /// @notice This returns all of the fields for a given token. /// @param _a is the address of a given token. /// @return string of the token's symbol. /// @return uint of the token's magnitude. /// @return uint of the token's exchange rate to ETH. /// @return bool whether the token is available. /// @return bool whether the token is loadable to the TokenCard. /// @return bool whether the token is redeemable to the TKN Holder Contract. /// @return uint of the lastUpdated time of the token's exchange rate. function getTokenInfo(address _a) external view returns (string memory, uint256, uint256, bool, bool, bool, uint256) { Token storage tokenInfo = _tokenInfoMap[_a]; return (tokenInfo.symbol, tokenInfo.magnitude, tokenInfo.rate, tokenInfo.available, tokenInfo.loadable, tokenInfo.redeemable, tokenInfo.lastUpdate); } /// @notice This returns all of the fields for our StableCoin. /// @return string of the token's symbol. /// @return uint of the token's magnitude. /// @return uint of the token's exchange rate to ETH. /// @return bool whether the token is available. /// @return bool whether the token is loadable to the TokenCard. /// @return bool whether the token is redeemable to the TKN Holder Contract. /// @return uint of the lastUpdated time of the token's exchange rate. function getStablecoinInfo() external view returns (string memory, uint256, uint256, bool, bool, bool, uint256) { Token storage stablecoinInfo = _tokenInfoMap[_stablecoin]; return (stablecoinInfo.symbol, stablecoinInfo.magnitude, stablecoinInfo.rate, stablecoinInfo.available, stablecoinInfo.loadable, stablecoinInfo.redeemable, stablecoinInfo.lastUpdate); } /// @notice This returns an array of all whitelisted token addresses. /// @return address[] of whitelisted tokens. function tokenAddressArray() external view returns (address[] memory) { return _tokenAddressArray; } /// @notice This returns an array of all redeemable token addresses. /// @return address[] of redeemable tokens. function redeemableTokens() external view returns (address[] memory) { address[] memory redeemableAddresses = new address[](_redeemableCounter); uint redeemableIndex = 0; for (uint i = 0; i < _tokenAddressArray.length; i++) { address token = _tokenAddressArray[i]; if (_tokenInfoMap[token].redeemable){ redeemableAddresses[redeemableIndex] = token; redeemableIndex += 1; } } return redeemableAddresses; } /// @notice This returns true if a method Id is supported for the specific token. /// @return true if _methodId is supported in general or just for the specific token. function isERC20MethodSupported(address _token, bytes4 _methodId) public view returns (bool) { require(_tokenInfoMap[_token].available, "non-existing token"); return (_methodIdWhitelist[_methodId]); } /// @notice This returns true if the method is supported for all protected tokens. /// @return true if _methodId is in the method whitelist. function isERC20MethodWhitelisted(bytes4 _methodId) external view returns (bool) { return (_methodIdWhitelist[_methodId]); } /// @notice This returns the number of redeemable tokens. /// @return current # of redeemables. function redeemableCounter() external view returns (uint) { return _redeemableCounter; } /// @notice This returns the address of our stablecoin of choice. /// @return the address of the stablecoin contract. function stablecoin() external view returns (address) { return _stablecoin; } /// @notice this returns the node hash of our Oracle. /// @return the oracle node registered in ENS. function oracleNode() external view returns (bytes32) { return _oracleNode; } } // File: tokenWhitelistable.sol /** * TokenWhitelistable - The Consumer Contract Wallet * Copyright (C) 2019 The Contract Wallet Company Limited * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.10; /// @title TokenWhitelistable implements access to the TokenWhitelist located behind ENS. contract TokenWhitelistable is ENSResolvable { /// @notice Is the registered ENS node identifying the tokenWhitelist contract bytes32 private _tokenWhitelistNode; /// @notice Constructor initializes the TokenWhitelistable object. /// @param _tokenWhitelistNode_ is the ENS node of the TokenWhitelist. constructor(bytes32 _tokenWhitelistNode_) internal { _tokenWhitelistNode = _tokenWhitelistNode_; } /// @notice This shows what TokenWhitelist is being used /// @return TokenWhitelist's node registered in ENS. function tokenWhitelistNode() external view returns (bytes32) { return _tokenWhitelistNode; } /// @notice This returns all of the fields for a given token. /// @param _a is the address of a given token. /// @return string of the token's symbol. /// @return uint of the token's magnitude. /// @return uint of the token's exchange rate to ETH. /// @return bool whether the token is available. /// @return bool whether the token is loadable to the TokenCard. /// @return bool whether the token is redeemable to the TKN Holder Contract. /// @return uint of the lastUpdated time of the token's exchange rate. function _getTokenInfo(address _a) internal view returns (string memory, uint256, uint256, bool, bool, bool, uint256) { return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).getTokenInfo(_a); } /// @notice This returns all of the fields for our stablecoin token. /// @return string of the token's symbol. /// @return uint of the token's magnitude. /// @return uint of the token's exchange rate to ETH. /// @return bool whether the token is available. /// @return bool whether the token is loadable to the TokenCard. /// @return bool whether the token is redeemable to the TKN Holder Contract. /// @return uint of the lastUpdated time of the token's exchange rate. function _getStablecoinInfo() internal view returns (string memory, uint256, uint256, bool, bool, bool, uint256) { return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).getStablecoinInfo(); } /// @notice This returns an array of our whitelisted addresses. /// @return address[] of our whitelisted tokens. function _tokenAddressArray() internal view returns (address[] memory) { return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).tokenAddressArray(); } /// @notice This returns an array of all redeemable token addresses. /// @return address[] of redeemable tokens. function _redeemableTokens() internal view returns (address[] memory) { return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).redeemableTokens(); } /// @notice Update ERC20 token exchange rate. /// @param _token ERC20 token contract address. /// @param _rate ERC20 token exchange rate in wei. /// @param _updateDate date for the token updates. This will be compared to when oracle updates are received. function _updateTokenRate(address _token, uint _rate, uint _updateDate) internal { ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).updateTokenRate(_token, _rate, _updateDate); } /// @notice based on the method it returns the recipient address and amount/value, ERC20 specific. /// @param _data is the transaction payload. function _getERC20RecipientAndAmount(address _destination, bytes memory _data) internal view returns (address, uint) { return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).getERC20RecipientAndAmount(_destination, _data); } /// @notice Checks whether a token is available. /// @return bool available or not. function _isTokenAvailable(address _a) internal view returns (bool) { ( , , , bool available, , , ) = _getTokenInfo(_a); return available; } /// @notice Checks whether a token is redeemable. /// @return bool redeemable or not. function _isTokenRedeemable(address _a) internal view returns (bool) { ( , , , , , bool redeemable, ) = _getTokenInfo(_a); return redeemable; } /// @notice Checks whether a token is loadable. /// @return bool loadable or not. function _isTokenLoadable(address _a) internal view returns (bool) { ( , , , , bool loadable, , ) = _getTokenInfo(_a); return loadable; } /// @notice This gets the address of the stablecoin. /// @return the address of the stablecoin contract. function _stablecoin() internal view returns (address) { return ITokenWhitelist(_ensResolve(_tokenWhitelistNode)).stablecoin(); } } // File: holder.sol /** * Holder (aka Asset Contract) - The Consumer Contract Wallet * Copyright (C) 2019 The Contract Wallet Company Limited * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity ^0.5.10; /// @title Holder - The TKN Asset Contract /// @notice When the TKN contract calls the burn method, a share of the tokens held by this contract are disbursed to the burner. contract Holder is Balanceable, ENSResolvable, Controllable, Transferrable, TokenWhitelistable { using SafeMath for uint256; event Received(address _from, uint _amount); event CashAndBurned(address _to, address _asset, uint _amount); event Claimed(address _to, address _asset, uint _amount); /// @dev Check if the sender is the burner contract modifier onlyBurner() { require (msg.sender == _burner, "burner contract is not the sender"); _; } // Burner token which can be burned to redeem shares. address private _burner; /// @notice Constructor initializes the holder contract. /// @param _burnerContract_ is the address of the token contract TKN with burning functionality. /// @param _ens_ is the address of the ENS registry. /// @param _tokenWhitelistNode_ is the ENS node of the Token whitelist. /// @param _controllerNode_ is the ENS node of the Controller constructor (address _burnerContract_, address _ens_, bytes32 _tokenWhitelistNode_, bytes32 _controllerNode_) ENSResolvable(_ens_) Controllable(_controllerNode_) TokenWhitelistable(_tokenWhitelistNode_) public { _burner = _burnerContract_; } /// @notice Ether may be sent from anywhere. function() external payable { emit Received(msg.sender, msg.value); } /// @notice Burn handles disbursing a share of tokens in this contract to a given address. /// @param _to The address to disburse to /// @param _amount The amount of TKN that will be burned if this succeeds function burn(address payable _to, uint _amount) external onlyBurner returns (bool) { if (_amount == 0) { return true; } // The burner token deducts from the supply before calling. uint supply = IBurner(_burner).currentSupply().add(_amount); address[] memory redeemableAddresses = _redeemableTokens(); for (uint i = 0; i < redeemableAddresses.length; i++) { uint redeemableBalance = _balance(address(this), redeemableAddresses[i]); if (redeemableBalance > 0) { uint redeemableAmount = redeemableBalance.mul(_amount).div(supply); _safeTransfer(_to, redeemableAddresses[i], redeemableAmount); emit CashAndBurned(_to, redeemableAddresses[i], redeemableAmount); } } return true; } /// @notice This allows for the admin to reclaim the non-redeemableTokens /// @param _to this is the address which the reclaimed tokens will be sent to /// @param _nonRedeemableAddresses this is the array of tokens to be claimed function nonRedeemableTokenClaim(address payable _to, address[] calldata _nonRedeemableAddresses) external onlyAdmin returns (bool) { for (uint i = 0; i < _nonRedeemableAddresses.length; i++) { //revert if token is redeemable require(!_isTokenRedeemable(_nonRedeemableAddresses[i]), "redeemables cannot be claimed"); uint claimBalance = _balance(address(this), _nonRedeemableAddresses[i]); if (claimBalance > 0) { _safeTransfer(_to, _nonRedeemableAddresses[i], claimBalance); emit Claimed(_to, _nonRedeemableAddresses[i], claimBalance); } } return true; } /// @notice Returned the address of the burner contract /// @return the TKN address function burner() external view returns (address) { return _burner; } }
Update ERC20 token exchange rate. _token ERC20 token contract address. _rate ERC20 token exchange rate in wei. _updateDate date for the token updates. This will be compared to when oracle updates are received. Require that the token exists. Update the token's rate. Update the token's last update timestamp. Emit the rate update event.
function updateTokenRate(address _token, uint _rate, uint _updateDate) external onlyAdminOrOracle { require(_tokenInfoMap[_token].available, "token is not available"); _tokenInfoMap[_token].rate = _rate; _tokenInfoMap[_token].lastUpdate = _updateDate; emit UpdatedTokenRate(msg.sender, _token, _rate); }
913,799
./partial_match/1/0xDf0dbc66f85979a1d54671c4D9e439F306Be27EE/sources/_mean-finance/nft-descriptors/solidity/interfaces/IDCAHubPositionDescriptor.sol
The interface for generating a description for a position in a DCA Hub Contracts that implement this interface must return a base64 JSON with the entire description/
interface IDCAHubPositionDescriptor { function tokenURI(address hub, uint256 positionId) external view returns (string memory description); pragma solidity >=0.8.7 <0.9.0; }
9,345,386
./full_match/5/0xbafC5cd0Ab05E195039cEee17440cf0FbBB3Cc70/sources/contracts/CrowdFunding.sol
payable(address(this)).transfer(amount);
function donate(uint256 _id) public payable { uint256 amount = msg.value; Campaign storage campaign = campaigns[_id]; campaign.donators.push(msg.sender); campaign.donations.push(amount); }
7,081,230
/* Copyright 2020 Set Labs Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { IController } from "../../../interfaces/IController.sol"; import { ISetToken } from "../../../interfaces/ISetToken.sol"; import { ModuleBase } from "../../../protocol/lib/ModuleBase.sol"; contract ModuleBaseMock is ModuleBase { bool public removed; constructor(IController _controller) public ModuleBase(_controller) {} /* ============ External Functions ============ */ function testTransferFrom(IERC20 _token, address _from, address _to, uint256 _quantity) external { return transferFrom(_token, _from, _to, _quantity); } function testIsSetPendingInitialization(ISetToken _setToken) external view returns(bool) { return isSetPendingInitialization(_setToken); } function testIsSetManager(ISetToken _setToken, address _toCheck) external view returns(bool) { return isSetManager(_setToken, _toCheck); } function testIsSetValidAndInitialized(ISetToken _setToken) external view returns(bool) { return isSetValidAndInitialized(_setToken); } function testOnlyManagerAndValidSet(ISetToken _setToken) external view onlyManagerAndValidSet(_setToken) {} function testGetAndValidateAdapter(string memory _integrationName) external view returns(address) { return getAndValidateAdapter(_integrationName); } function testGetAndValidateAdapterWithHash(bytes32 _integrationHash) external view returns(address) { return getAndValidateAdapterWithHash(_integrationHash); } function testGetModuleFee(uint256 _feeIndex, uint256 _quantity) external view returns(uint256) { return getModuleFee(_feeIndex, _quantity); } function testPayProtocolFeeFromSetToken( ISetToken _setToken, address _component, uint256 _feeQuantity ) external { payProtocolFeeFromSetToken(_setToken, _component, _feeQuantity); } function testOnlySetManager(ISetToken _setToken) external view onlySetManager(_setToken, msg.sender) {} function testOnlyModule(ISetToken _setToken) external view onlyModule(_setToken) {} function removeModule() external override { removed = true; } function testOnlyValidAndInitializedSet(ISetToken _setToken) external view onlyValidAndInitializedSet(_setToken) {} function testOnlyValidInitialization(ISetToken _setToken) external view onlyValidAndPendingSet(_setToken) {} /* ============ Helper Functions ============ */ function initializeModuleOnSet(ISetToken _setToken) external { _setToken.initializeModule(); } }
============ Helper Functions ============ /
function testOnlyValidAndInitializedSet(ISetToken _setToken) function testOnlyValidInitialization(ISetToken _setToken) function initializeModuleOnSet(ISetToken _setToken) external { _setToken.initializeModule(); }
6,349,320
pragma solidity >=0.4.18 <0.7.0; import '../solidity-lib/openzeppelin-solidity-112/contracts/lifecycle/TokenDestructible.sol'; import '../solidity-lib/openzeppelin-solidity-112/contracts/token/ERC20/ERC20.sol'; import '../solidity-lib/openzeppelin-solidity-112/contracts/math/SafeMath.sol'; import './OwnerContract.sol'; import './Withdrawable.sol'; import './DepositWithdraw.sol'; import './DRCWalletMgrParamsInterface.sol'; import './DRCWalletStorageInterface.sol'; /** * contract that manage the wallet operations on DRC platform */ contract DRCWalletManager is OwnerContract, Withdrawable, TokenDestructible { using SafeMath for uint256; /** * withdraw wallet description */ // struct WithdrawWallet { // bytes32 name; // address walletAddr; // } /** * Deposit data storage */ // struct DepositRepository { // // uint256 balance; // uint256 frozen; // WithdrawWallet[] withdrawWallets; // // mapping (bytes32 => address) withdrawWallets; // } // mapping (address => DepositRepository) depositRepos; // mapping (address => address) public walletDeposits; // mapping (address => bool) public frozenDeposits; ERC20 public tk; // the token will be managed IDRCWalletMgrParams public params; // the parameters that the management needs IDRCWalletStorage public walletStorage; // the deposits and wallets data stored in a contract event CreateDepositAddress(address indexed _wallet, address _deposit); event FrozenTokens(address indexed _deposit, bool _freeze, uint256 _value); event ChangeDefaultWallet(address indexed _oldWallet, address _newWallet); /** * @dev initialize this contract with token, parameters and storage address * * @param _token the token address that will be withdraw * @param _walletParams the wallet management parameters */ function initialize(address _token, address _walletParams, address _walletStorage) onlyOwner public returns(bool) { require(_token != address(0)); require(_walletParams != address(0)); tk = ERC20(_token); params = IDRCWalletMgrParams(_walletParams); walletStorage = IDRCWalletStorage(_walletStorage); return true; } /** * @dev create deposit contract address for the default withdraw wallet * * @param _wallet the binded default withdraw wallet address */ function createDepositContract(address payable _wallet) onlyOwner public returns(address) { require(_wallet != address(0)); DepositWithdraw deposWithdr = new DepositWithdraw(_wallet); // new contract for deposit address payable _deposit = address(uint160(address(deposWithdr))); // walletDeposits[_wallet] = _deposit; // WithdrawWallet[] storage withdrawWalletList = depositRepos[_deposit].withdrawWallets; // withdrawWalletList.push(WithdrawWallet("default wallet", _wallet)); // // depositRepos[_deposit].balance = 0; // depositRepos[_deposit].frozen = 0; walletStorage.addDeposit(_wallet, _deposit); // deposWithdr.authorize(address(tk), this, 1e27); // give authorization to owner contract emit CreateDepositAddress(_wallet, _deposit); return _deposit; } /** * @dev deposit a value of funds to the deposit address * * @param _deposit the deposit address * @param _increase increase or decrease the value * @param _value the deposit funds value */ function doDeposit(address payable _deposit, bool _increase, uint256 _value) onlyOwner public returns(bool) { return (_increase ? walletStorage.increaseBalance(_deposit, _value) : walletStorage.decreaseBalance(_deposit, _value)); } /** * @dev get deposit contract address by using the default withdraw wallet * * @param _wallet the binded default withdraw wallet address */ function getDepositAddress(address payable _wallet) onlyOwner public view returns(address) { require(_wallet != address(0)); // address deposit = walletDeposits[_wallet]; // return deposit; return walletStorage.walletDeposits(_wallet); } /** * @dev get deposit balance and frozen amount by using the deposit address * * @param _deposit the deposit contract address */ function getDepositInfo(address payable _deposit) onlyOwner public view returns(uint256, uint256) { require(_deposit != address(0)); uint256 _balance = walletStorage.balanceOf(_deposit); // uint256 frozenAmount = depositRepos[_deposit].frozen; uint256 frozenAmount = walletStorage.frozenAmount(_deposit); // depositRepos[_deposit].balance = _balance; return (_balance, frozenAmount); } /** * @dev get the number of withdraw wallet addresses bindig to the deposit contract address * * @param _deposit the deposit contract address */ function getDepositWithdrawCount(address payable _deposit) onlyOwner public view returns(uint) { require(_deposit != address(0)); // WithdrawWallet[] storage withdrawWalletList = depositRepos[_deposit].withdrawWallets; // uint len = withdrawWalletList.length; uint len = walletStorage.walletsNumber(_deposit); return len; } /** * @dev get the withdraw wallet addresses list binding to the deposit contract address * * @param _deposit the deposit contract address * @param _indices the array of indices of the withdraw wallets */ function getDepositWithdrawList(address payable _deposit, uint[] memory _indices) onlyOwner public view returns(bytes32[] memory, address[] memory) { require(_indices.length != 0); bytes32[] memory names = new bytes32[](_indices.length); address[] memory wallets = new address[](_indices.length); for (uint i = 0; i < _indices.length; i = i.add(1)) { // WithdrawWallet storage wallet = depositRepos[_deposit].withdrawWallets[_indices[i]]; // names[i] = wallet.name; // wallets[i] = wallet.walletAddr; names[i] = walletStorage.walletName(_deposit, i); wallets[i] = walletStorage.wallet(_deposit, i); } return (names, wallets); } /** * @dev change the default withdraw wallet address binding to the deposit contract address * * @param _oldWallet the previous default withdraw wallet * @param _newWallet the new default withdraw wallet */ function changeDefaultWithdraw(address payable _oldWallet, address payable _newWallet) onlyOwner public returns(bool) { require(_oldWallet != address(0)); require(_newWallet != address(0)); address payable deposit = walletStorage.walletDeposits(_oldWallet); DepositWithdraw deposWithdr = DepositWithdraw(deposit); require(deposWithdr.setWithdrawWallet(_newWallet)); // WithdrawWallet[] storage withdrawWalletList = depositRepos[deposit].withdrawWallets; // withdrawWalletList[0].walletAddr = _newWallet; bool res = walletStorage.changeDefaultWallet(_oldWallet, _newWallet); emit ChangeDefaultWallet(_oldWallet, _newWallet); return res; } /** * @dev freeze the tokens in the deposit address * * @param _deposit the deposit address * @param _freeze to freeze or release * @param _value the amount of tokens need to be frozen */ function freezeTokens(address payable _deposit, bool _freeze, uint256 _value) onlyOwner public returns(bool) { // require(_deposit != address(0)); // frozenDeposits[_deposit] = _freeze; // if (_freeze) { // depositRepos[_deposit].frozen = depositRepos[_deposit].frozen.add(_value); // } else { // require(_value <= depositRepos[_deposit].frozen); // depositRepos[_deposit].frozen = depositRepos[_deposit].frozen.sub(_value); // } bool res = walletStorage.freezeTokens(_deposit, _freeze, _value); emit FrozenTokens(_deposit, _freeze, _value); return res; } /** * @dev withdraw the tokens from the deposit address to default wallet with charge fee * * @param _deposit the deposit address * @param _time the timestamp the withdraw occurs * @param _value the amount of tokens need to be frozen * @param _check if we will check the value is valid or meet the limit condition */ function withdrawWithFee(address payable _deposit, uint256 _time, uint256 _value, bool _check) onlyOwner public returns(bool) { // WithdrawWallet[] storage withdrawWalletList = depositRepos[_deposit].withdrawWallets; // return withdrawWithFee(_deposit, _time, withdrawWalletList[0].name, withdrawWalletList[0].walletAddr, _value, _check); bytes32 defaultWalletName = walletStorage.walletName(_deposit, 0); address payable defaultWallet = walletStorage.wallet(_deposit, 0); return withdrawWithFee(_deposit, _time, defaultWalletName, defaultWallet, _value, _check); } /** * @dev check if the wallet name is not matching the expected wallet address * * @param _deposit the deposit address * @param _name the withdraw wallet name * @param _to the withdraw wallet address */ function checkWithdrawAddress(address payable _deposit, bytes32 _name, address payable _to) public view returns(bool, bool) { // uint len = depositRepos[_deposit].withdrawWallets.length; uint len = walletStorage.walletsNumber(_deposit); for (uint i = 0; i < len; i = i.add(1)) { // WithdrawWallet memory wallet = depositRepos[_deposit].withdrawWallets[i]; // if (_name == wallet.name) { // return(true, (_to == wallet.walletAddr)); // } // if (_to == wallet.walletAddr) { // return(true, true); // } bytes32 walletName = walletStorage.walletName(_deposit, i); address walletAddr = walletStorage.wallet(_deposit, i); if (_name == walletName) { return (true, (_to == walletAddr)); } if (_to == walletAddr) { return (false, true); } } return (false, false); } /** * @dev withdraw tokens from this contract, send tokens to target withdraw wallet * * @param _deposWithdr the deposit contract that will record withdrawing * @param _time the timestamp occur the withdraw record * @param _to the address the token will be transfer to * @param _value the token transferred value */ function withdrawFromThis(DepositWithdraw _deposWithdr, uint256 _time, address payable _to, uint256 _value) private returns(bool) { uint256 fee = params.chargeFee(); uint256 realAmount = _value.sub(fee); address payable tokenReturn = params.chargeFeePool(); if (tokenReturn != address(0) && fee > 0) { // require(tk.transfer(tokenReturn, fee)); require(walletStorage.withdrawToken(address(tk), tokenReturn, fee)); } // require (tk.transfer(_to, realAmount)); require(walletStorage.withdrawToken(address(tk), _to, realAmount)); _deposWithdr.recordWithdraw(_time, _to, realAmount); return true; } /** * @dev withdraw tokens, send tokens to target withdraw wallet * * @param _deposit the deposit address that will be withdraw from * @param _time the timestamp occur the withdraw record * @param _name the withdraw address alias name to verify * @param _to the address the token will be transfer to * @param _value the token transferred value * @param _check if we will check the value is valid or meet the limit condition */ function withdrawWithFee(address payable _deposit, uint256 _time, bytes32 _name, address payable _to, uint256 _value, bool _check) onlyOwner public returns(bool) { require(_deposit != address(0)); require(_to != address(0)); uint256 totalBalance = walletStorage.balanceOf(_deposit); uint256 frozen = walletStorage.frozenAmount(_deposit); // uint256 available = totalBalance.sub(frozen); // require(_value <= available); if (_check) { require(_value <= totalBalance.sub(frozen)); } uint256 _balance = tk.balanceOf(_deposit); bool exist; bool correct; // WithdrawWallet[] storage withdrawWalletList = depositRepos[_deposit].withdrawWallets; (exist, correct) = checkWithdrawAddress(_deposit, _name, _to); if (!exist) { // withdrawWalletList.push(WithdrawWallet(_name, _to)); if (!correct) { walletStorage.addWithdraw(_deposit, _name, _to); } else { walletStorage.changeWalletName(_deposit, _name, _to); } } else { require(correct, "wallet address must be correct with wallet name!"); } DepositWithdraw deposWithdr = DepositWithdraw(_deposit); /** * if deposit address doesn't have enough tokens to withdraw, * then withdraw from this contract. Record this in the independent deposit contract. */ if (_value > _balance) { require(deposWithdr.checkWithdrawAmount(address(params), _value, _time)); if (_balance > 0) { require(Withdrawable(deposWithdr).withdrawToken(address(tk), address(uint160(address(walletStorage))), _balance)); } require(withdrawFromThis(deposWithdr, _time, _to, _value)); // return true; } else { require(deposWithdr.withdrawToken(address(tk), address(params), _time, _to, _value, params.chargeFee(), params.chargeFeePool())); } return walletStorage.decreaseBalance(_deposit, _value); } /** * @dev destory the old depoist contract and take back the tokens * * @param _deposit the deposit address */ function destroyDepositContract(address payable _deposit) onlyOwner public returns(bool) { require(_deposit != address(0)); DepositWithdraw deposWithdr = DepositWithdraw(_deposit); address[] memory tokens = new address[](1); tokens[0] = address(tk); deposWithdr.destroy(tokens); return walletStorage.removeDeposit(_deposit); } }
get the withdraw wallet addresses list binding to the deposit contract address _deposit the deposit contract address _indices the array of indices of the withdraw wallets/ WithdrawWallet storage wallet = depositRepos[_deposit].withdrawWallets[_indices[i]]; names[i] = wallet.name; wallets[i] = wallet.walletAddr;
function getDepositWithdrawList(address payable _deposit, uint[] memory _indices) onlyOwner public view returns(bytes32[] memory, address[] memory) { require(_indices.length != 0); bytes32[] memory names = new bytes32[](_indices.length); address[] memory wallets = new address[](_indices.length); for (uint i = 0; i < _indices.length; i = i.add(1)) { names[i] = walletStorage.walletName(_deposit, i); wallets[i] = walletStorage.wallet(_deposit, i); } return (names, wallets); }
6,415,876
./full_match/1/0xa6e596b51c6E7FA6f725505c648AE33f27d52a88/sources/nQCToken803.sol
given an amount of Ether, swap all for HATE and send to burn address/
function swapAndBurn(uint256 _amount) public override { require(msg.sender == address(this), "can't swap and burn"); address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = HATE; uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{ value: _amount }(0, path, burn, block.timestamp); }
8,296,634
pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./RealitioERC20.sol"; // openzeppelin imports import "@openzeppelin/contracts/math/SafeMath.sol"; library CeilDiv { // calculates ceil(x/y) function ceildiv(uint256 x, uint256 y) internal pure returns (uint256) { if (x > 0) return ((x - 1) / y) + 1; return x / y; } } /// @title Market Contract Factory contract PredictionMarket { using SafeMath for uint256; using CeilDiv for uint256; // ------ Events ------ event MarketCreated(address indexed user, uint256 indexed marketId, uint256 outcomes, string question, string image); event MarketActionTx( address indexed user, MarketAction indexed action, uint256 indexed marketId, uint256 outcomeId, uint256 shares, uint256 value, uint256 timestamp ); event MarketOutcomePrice(uint256 indexed marketId, uint256 indexed outcomeId, uint256 value, uint256 timestamp); event MarketLiquidity( uint256 indexed marketId, uint256 value, // total liquidity uint256 price, // value of one liquidity share; max: 1 (50-50 situation) uint256 timestamp ); event MarketResolved(address indexed user, uint256 indexed marketId, uint256 outcomeId, uint256 timestamp); // ------ Events End ------ uint256 public constant MAX_UINT_256 = 115792089237316195423570985008687907853269984665640564039457584007913129639935; uint256 public constant ONE = 10**18; enum MarketState { open, closed, resolved } enum MarketAction { buy, sell, addLiquidity, removeLiquidity, claimWinnings, claimLiquidity, claimFees, claimVoided } struct Market { // market details uint256 closesAtTimestamp; uint256 balance; // total stake uint256 liquidity; // stake held uint256 sharesAvailable; // shares held (all outcomes) mapping(address => uint256) liquidityShares; mapping(address => bool) liquidityClaims; // wether user has claimed liquidity earnings MarketState state; // resolution variables MarketResolution resolution; // fees MarketFees fees; // market outcomes uint256[] outcomeIds; mapping(uint256 => MarketOutcome) outcomes; } struct MarketFees { uint256 value; // fee % taken from every transaction uint256 poolWeight; // internal var used to ensure pro-rate fee distribution mapping(address => uint256) claimed; } struct MarketResolution { bool resolved; uint256 outcomeId; bytes32 questionId; // realitio questionId } struct MarketOutcome { uint256 marketId; uint256 id; Shares shares; } struct Shares { uint256 total; // number of shares uint256 available; // available shares mapping(address => uint256) holders; mapping(address => bool) claims; // wether user has claimed winnings mapping(address => bool) voidedClaims; // wether user has claimed voided market shares } uint256[] marketIds; mapping(uint256 => Market) markets; uint256 public marketIndex; // governance uint256 public fee; // fee % taken from every transaction address public treasury; // realitio configs address public realitioAddress; uint256 public realitioTimeout; // market creation IERC20 public token; // token used for rewards / market creation uint256 public requiredBalance; // required balance for market creation // ------ Modifiers ------ modifier isMarket(uint256 marketId) { require(marketId < marketIndex, "Market not found"); _; } modifier timeTransitions(uint256 marketId) { if (now > markets[marketId].closesAtTimestamp && markets[marketId].state == MarketState.open) { nextState(marketId); } _; } modifier atState(uint256 marketId, MarketState state) { require(markets[marketId].state == state, "Market in incorrect state"); _; } modifier notAtState(uint256 marketId, MarketState state) { require(markets[marketId].state != state, "Market in incorrect state"); _; } modifier transitionNext(uint256 marketId) { _; nextState(marketId); } modifier mustHoldRequiredBalance() { require(token.balanceOf(msg.sender) >= requiredBalance, "msg.sender must hold minimum erc20 balance"); _; } // ------ Modifiers End ------ /// @dev protocol is immutable and has no ownership constructor( uint256 _fee, IERC20 _token, uint256 _requiredBalance, address _realitioAddress, uint256 _realitioTimeout, address _treasury ) public { require(_realitioAddress != address(0), "_realitioAddress is address 0"); require(_realitioTimeout > 0, "timeout must be positive"); fee = _fee; token = _token; requiredBalance = _requiredBalance; realitioAddress = _realitioAddress; realitioTimeout = _realitioTimeout; treasury = _treasury; } // ------ Core Functions ------ /// @dev Creates a market, initializes the outcome shares pool and submits a question in Realitio function createMarket( string calldata question, string calldata image, uint256 closesAt, address arbitrator, uint256 outcomes ) external payable mustHoldRequiredBalance() returns (uint256) { uint256 marketId = marketIndex; marketIds.push(marketId); Market storage market = markets[marketId]; require(msg.value > 0, "stake needs to be > 0"); require(closesAt > now, "market must resolve after the current date"); require(arbitrator != address(0), "invalid arbitrator address"); // v1 - only binary markets require(outcomes == 2, "number of outcomes has to be 2"); market.closesAtTimestamp = closesAt; market.state = MarketState.open; market.fees.value = fee; // setting intial value to an integer that does not map to any outcomeId market.resolution.outcomeId = MAX_UINT_256; // creating market outcomes for (uint256 i = 0; i < outcomes; i++) { market.outcomeIds.push(i); MarketOutcome storage outcome = market.outcomes[i]; outcome.marketId = marketId; outcome.id = i; } // creating question in realitio RealitioERC20 realitio = RealitioERC20(realitioAddress); market.resolution.questionId = realitio.askQuestionERC20( 2, question, arbitrator, uint32(realitioTimeout), uint32(closesAt), 0, 0 ); addLiquidity(marketId, msg.value); // emiting initial price events emitMarketOutcomePriceEvents(marketId); emit MarketCreated(msg.sender, marketId, outcomes, question, image); // incrementing market array index marketIndex = marketIndex + 1; return marketId; } /// @dev Calculates the number of shares bought with "amount" balance function calcBuyAmount( uint256 amount, uint256 marketId, uint256 outcomeId ) public view returns (uint256) { Market storage market = markets[marketId]; uint256[] memory outcomesShares = getMarketOutcomesShares(marketId); uint256 amountMinusFees = amount.sub(amount.mul(market.fees.value) / ONE); uint256 buyTokenPoolBalance = outcomesShares[outcomeId]; uint256 endingOutcomeBalance = buyTokenPoolBalance.mul(ONE); for (uint256 i = 0; i < outcomesShares.length; i++) { if (i != outcomeId) { uint256 outcomeShares = outcomesShares[i]; endingOutcomeBalance = endingOutcomeBalance.mul(outcomeShares).ceildiv(outcomeShares.add(amountMinusFees)); } } require(endingOutcomeBalance > 0, "must have non-zero balances"); return buyTokenPoolBalance.add(amountMinusFees).sub(endingOutcomeBalance.ceildiv(ONE)); } /// @dev Calculates the number of shares needed to be sold in order to receive "amount" in balance function calcSellAmount( uint256 amount, uint256 marketId, uint256 outcomeId ) public view returns (uint256 outcomeTokenSellAmount) { Market storage market = markets[marketId]; uint256[] memory outcomesShares = getMarketOutcomesShares(marketId); uint256 amountPlusFees = amount.mul(ONE) / ONE.sub(market.fees.value); uint256 sellTokenPoolBalance = outcomesShares[outcomeId]; uint256 endingOutcomeBalance = sellTokenPoolBalance.mul(ONE); for (uint256 i = 0; i < outcomesShares.length; i++) { if (i != outcomeId) { uint256 outcomeShares = outcomesShares[i]; endingOutcomeBalance = endingOutcomeBalance.mul(outcomeShares).ceildiv(outcomeShares.sub(amountPlusFees)); } } require(endingOutcomeBalance > 0, "must have non-zero balances"); return amountPlusFees.add(endingOutcomeBalance.ceildiv(ONE)).sub(sellTokenPoolBalance); } /// @dev Buy shares of a market outcome function buy( uint256 marketId, uint256 outcomeId, uint256 minOutcomeSharesToBuy ) external payable timeTransitions(marketId) atState(marketId, MarketState.open) { Market storage market = markets[marketId]; uint256 value = msg.value; uint256 shares = calcBuyAmount(value, marketId, outcomeId); require(shares >= minOutcomeSharesToBuy, "minimum buy amount not reached"); require(shares > 0, "shares amount is 0"); // subtracting fee from transaction value uint256 feeAmount = value.mul(market.fees.value) / ONE; market.fees.poolWeight = market.fees.poolWeight.add(feeAmount / 2); { (bool sent,) = payable(treasury).call{ value: feeAmount - feeAmount / 2 }(""); require(sent, "PredictionMarket: fail to send value to platform fee address"); } uint256 valueMinusFees = value.sub(feeAmount); MarketOutcome storage outcome = market.outcomes[outcomeId]; // Funding market shares with received funds addSharesToMarket(marketId, valueMinusFees); require(outcome.shares.available >= shares, "outcome shares pool balance is too low"); transferOutcomeSharesfromPool(msg.sender, marketId, outcomeId, shares); emit MarketActionTx(msg.sender, MarketAction.buy, marketId, outcomeId, shares, value, now); emitMarketOutcomePriceEvents(marketId); } /// @dev Sell shares of a market outcome function sell( uint256 marketId, uint256 outcomeId, uint256 value, uint256 maxOutcomeSharesToSell ) external payable timeTransitions(marketId) atState(marketId, MarketState.open) { Market storage market = markets[marketId]; MarketOutcome storage outcome = market.outcomes[outcomeId]; uint256 shares = calcSellAmount(value, marketId, outcomeId); require(shares <= maxOutcomeSharesToSell, "maximum sell amount exceeded"); require(shares > 0, "shares amount is 0"); require(outcome.shares.holders[msg.sender] >= shares, "user does not have enough balance"); transferOutcomeSharesToPool(msg.sender, marketId, outcomeId, shares); // adding fee to transaction value uint256 feeAmount = value.mul(market.fees.value) / (ONE.sub(fee)); market.fees.poolWeight = market.fees.poolWeight.add(feeAmount / 2); { (bool sent,) = payable(treasury).call{ value: feeAmount - feeAmount / 2 }(""); require(sent, "PredictionMarket: fail to send value to platform fee address"); } uint256 valuePlusFees = value.add(feeAmount); require(market.balance >= valuePlusFees, "market does not have enough balance"); // Rebalancing market shares removeSharesFromMarket(marketId, valuePlusFees); // Transferring funds to user msg.sender.transfer(value); emit MarketActionTx(msg.sender, MarketAction.sell, marketId, outcomeId, shares, value, now); emitMarketOutcomePriceEvents(marketId); } /// @dev Adds liquidity to a market - external function addLiquidity(uint256 marketId) external payable timeTransitions(marketId) atState(marketId, MarketState.open) { addLiquidity(marketId, msg.value); } /// @dev Private function, used by addLiquidity and CreateMarket function addLiquidity(uint256 marketId, uint256 value) private timeTransitions(marketId) atState(marketId, MarketState.open) { Market storage market = markets[marketId]; require(value > 0, "stake has to be greater than 0."); uint256 liquidityAmount; uint256[] memory outcomesShares = getMarketOutcomesShares(marketId); uint256[] memory sendBackAmounts = new uint256[](outcomesShares.length); uint256 poolWeight = 0; if (market.liquidity > 0) { // part of the liquidity is exchanged for outcome shares if market is not balanced for (uint256 i = 0; i < outcomesShares.length; i++) { uint256 outcomeShares = outcomesShares[i]; if (poolWeight < outcomeShares) poolWeight = outcomeShares; } for (uint256 i = 0; i < outcomesShares.length; i++) { uint256 remaining = value.mul(outcomesShares[i]) / poolWeight; sendBackAmounts[i] = value.sub(remaining); } liquidityAmount = value.mul(market.liquidity) / poolWeight; // re-balancing fees pool rebalanceFeesPool(marketId, liquidityAmount, MarketAction.addLiquidity); } else { // funding market with no liquidity liquidityAmount = value; } // funding market market.liquidity = market.liquidity.add(liquidityAmount); market.liquidityShares[msg.sender] = market.liquidityShares[msg.sender].add(liquidityAmount); addSharesToMarket(marketId, value); // transform sendBackAmounts to array of amounts added for (uint256 i = 0; i < sendBackAmounts.length; i++) { if (sendBackAmounts[i] > 0) { uint256 marketShares = market.sharesAvailable; uint256 outcomeShares = market.outcomes[i].shares.available; transferOutcomeSharesfromPool(msg.sender, marketId, i, sendBackAmounts[i]); emit MarketActionTx( msg.sender, MarketAction.buy, marketId, i, sendBackAmounts[i], (marketShares.sub(outcomeShares)).mul(sendBackAmounts[i]).div(market.sharesAvailable), // price * shares now ); } } uint256 liquidityPrice = getMarketLiquidityPrice(marketId); uint256 liquidityValue = liquidityPrice.mul(liquidityAmount) / ONE; emit MarketActionTx(msg.sender, MarketAction.addLiquidity, marketId, 0, liquidityAmount, liquidityValue, now); emit MarketLiquidity(marketId, market.liquidity, liquidityPrice, now); } /// @dev Removes liquidity to a market - external function removeLiquidity(uint256 marketId, uint256 shares) external payable timeTransitions(marketId) atState(marketId, MarketState.open) { Market storage market = markets[marketId]; require(market.liquidityShares[msg.sender] >= shares, "user does not have enough balance"); // claiming any pending fees claimFees(marketId); // re-balancing fees pool rebalanceFeesPool(marketId, shares, MarketAction.removeLiquidity); uint256[] memory outcomesShares = getMarketOutcomesShares(marketId); uint256[] memory sendAmounts = new uint256[](outcomesShares.length); uint256 poolWeight = MAX_UINT_256; // part of the liquidity is exchanged for outcome shares if market is not balanced for (uint256 i = 0; i < outcomesShares.length; i++) { uint256 outcomeShares = outcomesShares[i]; if (poolWeight > outcomeShares) poolWeight = outcomeShares; } uint256 liquidityAmount = shares.mul(poolWeight).div(market.liquidity); for (uint256 i = 0; i < outcomesShares.length; i++) { sendAmounts[i] = outcomesShares[i].mul(shares) / market.liquidity; sendAmounts[i] = sendAmounts[i].sub(liquidityAmount); } // removing liquidity from market removeSharesFromMarket(marketId, liquidityAmount); market.liquidity = market.liquidity.sub(shares); // removing liquidity tokens from market creator market.liquidityShares[msg.sender] = market.liquidityShares[msg.sender].sub(shares); for (uint256 i = 0; i < outcomesShares.length; i++) { if (sendAmounts[i] > 0) { uint256 marketShares = market.sharesAvailable; uint256 outcomeShares = market.outcomes[i].shares.available; transferOutcomeSharesfromPool(msg.sender, marketId, i, sendAmounts[i]); emit MarketActionTx( msg.sender, MarketAction.buy, marketId, i, sendAmounts[i], (marketShares.sub(outcomeShares)).mul(sendAmounts[i]).div(market.sharesAvailable), // price * shares now ); } } // transferring user funds from liquidity removed msg.sender.transfer(liquidityAmount); emit MarketActionTx(msg.sender, MarketAction.removeLiquidity, marketId, 0, shares, liquidityAmount, now); emit MarketLiquidity(marketId, market.liquidity, getMarketLiquidityPrice(marketId), now); } /// @dev Fetches winning outcome from Realitio and resolves the market function resolveMarketOutcome(uint256 marketId) external timeTransitions(marketId) atState(marketId, MarketState.closed) transitionNext(marketId) returns (uint256) { Market storage market = markets[marketId]; RealitioERC20 realitio = RealitioERC20(realitioAddress); // will fail if question is not finalized uint256 outcomeId = uint256(realitio.resultFor(market.resolution.questionId)); market.resolution.outcomeId = outcomeId; emit MarketResolved(msg.sender, marketId, outcomeId, now); emitMarketOutcomePriceEvents(marketId); return market.resolution.outcomeId; } /// @dev Allows holders of resolved outcome shares to claim earnings. function claimWinnings(uint256 marketId) external atState(marketId, MarketState.resolved) { Market storage market = markets[marketId]; MarketOutcome storage resolvedOutcome = market.outcomes[market.resolution.outcomeId]; require(resolvedOutcome.shares.holders[msg.sender] > 0, "user does not hold resolved outcome shares"); require(resolvedOutcome.shares.claims[msg.sender] == false, "user already claimed resolved outcome winnings"); // 1 share => price = 1 uint256 value = resolvedOutcome.shares.holders[msg.sender]; // assuring market has enough funds require(market.balance >= value, "Market does not have enough balance"); market.balance = market.balance.sub(value); resolvedOutcome.shares.claims[msg.sender] = true; emit MarketActionTx( msg.sender, MarketAction.claimWinnings, marketId, market.resolution.outcomeId, resolvedOutcome.shares.holders[msg.sender], value, now ); msg.sender.transfer(value); } /// @dev Allows holders of voided outcome shares to claim balance back. function claimVoidedOutcomeShares(uint256 marketId, uint256 outcomeId) external atState(marketId, MarketState.resolved) { Market storage market = markets[marketId]; MarketOutcome storage outcome = market.outcomes[outcomeId]; require(outcome.shares.holders[msg.sender] > 0, "user does not hold outcome shares"); require(outcome.shares.voidedClaims[msg.sender] == false, "user already claimed outcome shares"); // voided market - shares are valued at last market price uint256 price = getMarketOutcomePrice(marketId, outcomeId); uint256 value = price.mul(outcome.shares.holders[msg.sender]).div(ONE); // assuring market has enough funds require(market.balance >= value, "Market does not have enough balance"); market.balance = market.balance.sub(value); outcome.shares.voidedClaims[msg.sender] = true; emit MarketActionTx( msg.sender, MarketAction.claimVoided, marketId, outcomeId, outcome.shares.holders[msg.sender], value, now ); msg.sender.transfer(value); } /// @dev Allows liquidity providers to claim earnings from liquidity providing. function claimLiquidity(uint256 marketId) external atState(marketId, MarketState.resolved) { Market storage market = markets[marketId]; // claiming any pending fees claimFees(marketId); require(market.liquidityShares[msg.sender] > 0, "user does not hold liquidity shares"); require(market.liquidityClaims[msg.sender] == false, "user already claimed liquidity winnings"); // value = total resolved outcome pool shares * pool share (%) uint256 liquidityPrice = getMarketLiquidityPrice(marketId); uint256 value = liquidityPrice.mul(market.liquidityShares[msg.sender]) / ONE; // assuring market has enough funds require(market.balance >= value, "Market does not have enough balance"); market.balance = market.balance.sub(value); market.liquidityClaims[msg.sender] = true; emit MarketActionTx( msg.sender, MarketAction.claimLiquidity, marketId, 0, market.liquidityShares[msg.sender], value, now ); msg.sender.transfer(value); } /// @dev Allows liquidity providers to claim their fees share from fees pool function claimFees(uint256 marketId) public payable { Market storage market = markets[marketId]; uint256 claimableFees = getUserClaimableFees(marketId, msg.sender); if (claimableFees > 0) { market.fees.claimed[msg.sender] = market.fees.claimed[msg.sender].add(claimableFees); msg.sender.transfer(claimableFees); } emit MarketActionTx( msg.sender, MarketAction.claimFees, marketId, 0, market.liquidityShares[msg.sender], claimableFees, now ); } /// @dev Rebalances the fees pool. Needed in every AddLiquidity / RemoveLiquidity call function rebalanceFeesPool( uint256 marketId, uint256 liquidityShares, MarketAction action ) private returns (uint256) { Market storage market = markets[marketId]; uint256 poolWeight = liquidityShares.mul(market.fees.poolWeight).div(market.liquidity); if (action == MarketAction.addLiquidity) { market.fees.poolWeight = market.fees.poolWeight.add(poolWeight); market.fees.claimed[msg.sender] = market.fees.claimed[msg.sender].add(poolWeight); } else { market.fees.poolWeight = market.fees.poolWeight.sub(poolWeight); market.fees.claimed[msg.sender] = market.fees.claimed[msg.sender].sub(poolWeight); } } /// @dev Transitions market to next state function nextState(uint256 marketId) private { Market storage market = markets[marketId]; market.state = MarketState(uint256(market.state) + 1); } /// @dev Emits a outcome price event for every outcome function emitMarketOutcomePriceEvents(uint256 marketId) private { Market storage market = markets[marketId]; for (uint256 i = 0; i < market.outcomeIds.length; i++) { emit MarketOutcomePrice(marketId, i, getMarketOutcomePrice(marketId, i), now); } // liquidity shares also change value emit MarketLiquidity(marketId, market.liquidity, getMarketLiquidityPrice(marketId), now); } /// @dev Adds outcome shares to shares pool function addSharesToMarket(uint256 marketId, uint256 shares) private { Market storage market = markets[marketId]; for (uint256 i = 0; i < market.outcomeIds.length; i++) { MarketOutcome storage outcome = market.outcomes[i]; outcome.shares.available = outcome.shares.available.add(shares); outcome.shares.total = outcome.shares.total.add(shares); // only adding to market total shares, the available remains market.sharesAvailable = market.sharesAvailable.add(shares); } market.balance = market.balance.add(shares); } /// @dev Removes outcome shares from shares pool function removeSharesFromMarket(uint256 marketId, uint256 shares) private { Market storage market = markets[marketId]; for (uint256 i = 0; i < market.outcomeIds.length; i++) { MarketOutcome storage outcome = market.outcomes[i]; outcome.shares.available = outcome.shares.available.sub(shares); outcome.shares.total = outcome.shares.total.sub(shares); // only subtracting from market total shares, the available remains market.sharesAvailable = market.sharesAvailable.sub(shares); } market.balance = market.balance.sub(shares); } /// @dev Transfer outcome shares from pool to user balance function transferOutcomeSharesfromPool( address user, uint256 marketId, uint256 outcomeId, uint256 shares ) private { Market storage market = markets[marketId]; MarketOutcome storage outcome = market.outcomes[outcomeId]; // transfering shares from shares pool to user outcome.shares.holders[user] = outcome.shares.holders[user].add(shares); outcome.shares.available = outcome.shares.available.sub(shares); market.sharesAvailable = market.sharesAvailable.sub(shares); } /// @dev Transfer outcome shares from user balance back to pool function transferOutcomeSharesToPool( address user, uint256 marketId, uint256 outcomeId, uint256 shares ) private { Market storage market = markets[marketId]; MarketOutcome storage outcome = market.outcomes[outcomeId]; // adding shares back to pool outcome.shares.holders[user] = outcome.shares.holders[user].sub(shares); outcome.shares.available = outcome.shares.available.add(shares); market.sharesAvailable = market.sharesAvailable.add(shares); } // ------ Core Functions End ------ // ------ Getters ------ function getUserMarketShares(uint256 marketId, address user) external view returns ( uint256, uint256, uint256 ) { Market storage market = markets[marketId]; return ( market.liquidityShares[user], market.outcomes[0].shares.holders[user], market.outcomes[1].shares.holders[user] ); } function getUserClaimStatus(uint256 marketId, address user) external view returns ( bool, bool, bool, bool, uint256 ) { Market storage market = markets[marketId]; // market still not resolved if (market.state != MarketState.resolved) { return (false, false, false, false, getUserClaimableFees(marketId, user)); } MarketOutcome storage outcome = market.outcomes[market.resolution.outcomeId]; return ( outcome.shares.holders[user] > 0, outcome.shares.claims[user], market.liquidityShares[user] > 0, market.liquidityClaims[user], getUserClaimableFees(marketId, user) ); } function getUserLiquidityPoolShare(uint256 marketId, address user) external view returns (uint256) { Market storage market = markets[marketId]; return market.liquidityShares[user].mul(ONE).div(market.liquidity); } function getUserClaimableFees(uint256 marketId, address user) public view returns (uint256) { Market storage market = markets[marketId]; uint256 rawAmount = market.fees.poolWeight.mul(market.liquidityShares[user]).div(market.liquidity); // No fees left to claim if (market.fees.claimed[user] > rawAmount) return 0; return rawAmount.sub(market.fees.claimed[user]); } function getMarkets() external view returns (uint256[] memory) { return marketIds; } function getMarketData(uint256 marketId) external view returns ( MarketState, uint256, uint256, uint256, uint256, int256 ) { Market storage market = markets[marketId]; return ( market.state, market.closesAtTimestamp, market.liquidity, market.balance, market.sharesAvailable, getMarketResolvedOutcome(marketId) ); } function getMarketAltData(uint256 marketId) external view returns ( uint256, bytes32, uint256 ) { Market storage market = markets[marketId]; return (market.fees.value, market.resolution.questionId, uint256(market.resolution.questionId)); } function getMarketQuestion(uint256 marketId) external view returns (bytes32) { Market storage market = markets[marketId]; return (market.resolution.questionId); } function getMarketPrices(uint256 marketId) external view returns ( uint256, uint256, uint256 ) { return (getMarketLiquidityPrice(marketId), getMarketOutcomePrice(marketId, 0), getMarketOutcomePrice(marketId, 1)); } function getMarketLiquidityPrice(uint256 marketId) public view returns (uint256) { Market storage market = markets[marketId]; if (market.state == MarketState.resolved && !isMarketVoided(marketId)) { // resolved market, price is either 0 or 1 // final liquidity price = outcome shares / liquidity shares return market.outcomes[market.resolution.outcomeId].shares.available.mul(ONE).div(market.liquidity); } // liquidity price = # liquidity shares / # outcome shares * # outcomes return market.liquidity.mul(ONE * market.outcomeIds.length).div(market.sharesAvailable); } function getMarketResolvedOutcome(uint256 marketId) public view returns (int256) { Market storage market = markets[marketId]; // returning -1 if market still not resolved if (market.state != MarketState.resolved) { return -1; } return int256(market.resolution.outcomeId); } function isMarketVoided(uint256 marketId) public view returns (bool) { Market storage market = markets[marketId]; // market still not resolved, still in valid state if (market.state != MarketState.resolved) { return false; } // resolved market id does not match any of the market ids return market.resolution.outcomeId >= market.outcomeIds.length; } // ------ Outcome Getters ------ function getMarketOutcomeIds(uint256 marketId) external view returns (uint256[] memory) { Market storage market = markets[marketId]; return market.outcomeIds; } function getMarketOutcomePrice(uint256 marketId, uint256 outcomeId) public view returns (uint256) { Market storage market = markets[marketId]; MarketOutcome storage outcome = market.outcomes[outcomeId]; if (market.state == MarketState.resolved && !isMarketVoided(marketId)) { // resolved market, price is either 0 or 1 return outcomeId == market.resolution.outcomeId ? ONE : 0; } return (market.sharesAvailable.sub(outcome.shares.available)).mul(ONE).div(market.sharesAvailable); } function getMarketOutcomeData(uint256 marketId, uint256 outcomeId) external view returns ( uint256, uint256, uint256 ) { Market storage market = markets[marketId]; MarketOutcome storage outcome = market.outcomes[outcomeId]; return (getMarketOutcomePrice(marketId, outcomeId), outcome.shares.available, outcome.shares.total); } function getMarketOutcomesShares(uint256 marketId) private view returns (uint256[] memory) { Market storage market = markets[marketId]; uint256[] memory shares = new uint256[](market.outcomeIds.length); for (uint256 i = 0; i < market.outcomeIds.length; i++) { shares[i] = market.outcomes[i].shares.available; } return shares; } } /** *Submitted for verification at Etherscan.io on 2021-06-09 */ pragma solidity >0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } pragma solidity >0.4.24; /** * @title ReailtioSafeMath256 * @dev Math operations with safety checks that throw on error */ library RealitioSafeMath256 { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } pragma solidity >0.4.24; /** * @title RealitioSafeMath32 * @dev Math operations with safety checks that throw on error * @dev Copy of SafeMath but for uint32 instead of uint256 * @dev Deleted functions we don't use */ library RealitioSafeMath32 { function add(uint32 a, uint32 b) internal pure returns (uint32) { uint32 c = a + b; assert(c >= a); return c; } } pragma solidity >0.4.18; contract BalanceHolder { IERC20 public token; mapping(address => uint256) public balanceOf; event LogWithdraw( address indexed user, uint256 amount ); function withdraw() public { uint256 bal = balanceOf[msg.sender]; balanceOf[msg.sender] = 0; require(token.transfer(msg.sender, bal)); emit LogWithdraw(msg.sender, bal); } } pragma solidity >0.4.24; contract RealitioERC20 is BalanceHolder { using RealitioSafeMath256 for uint256; using RealitioSafeMath32 for uint32; address constant NULL_ADDRESS = address(0); // History hash when no history is created, or history has been cleared bytes32 constant NULL_HASH = bytes32(0); // An unitinalized finalize_ts for a question will indicate an unanswered question. uint32 constant UNANSWERED = 0; // An unanswered reveal_ts for a commitment will indicate that it does not exist. uint256 constant COMMITMENT_NON_EXISTENT = 0; // Commit->reveal timeout is 1/8 of the question timeout (rounded down). uint32 constant COMMITMENT_TIMEOUT_RATIO = 8; event LogSetQuestionFee( address arbitrator, uint256 amount ); event LogNewTemplate( uint256 indexed template_id, address indexed user, string question_text ); event LogNewQuestion( bytes32 indexed question_id, address indexed user, uint256 template_id, string question, bytes32 indexed content_hash, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce, uint256 created ); event LogFundAnswerBounty( bytes32 indexed question_id, uint256 bounty_added, uint256 bounty, address indexed user ); event LogNewAnswer( bytes32 answer, bytes32 indexed question_id, bytes32 history_hash, address indexed user, uint256 bond, uint256 ts, bool is_commitment ); event LogAnswerReveal( bytes32 indexed question_id, address indexed user, bytes32 indexed answer_hash, bytes32 answer, uint256 nonce, uint256 bond ); event LogNotifyOfArbitrationRequest( bytes32 indexed question_id, address indexed user ); event LogFinalize( bytes32 indexed question_id, bytes32 indexed answer ); event LogClaim( bytes32 indexed question_id, address indexed user, uint256 amount ); struct Question { bytes32 content_hash; address arbitrator; uint32 opening_ts; uint32 timeout; uint32 finalize_ts; bool is_pending_arbitration; uint256 bounty; bytes32 best_answer; bytes32 history_hash; uint256 bond; } // Stored in a mapping indexed by commitment_id, a hash of commitment hash, question, bond. struct Commitment { uint32 reveal_ts; bool is_revealed; bytes32 revealed_answer; } // Only used when claiming more bonds than fits into a transaction // Stored in a mapping indexed by question_id. struct Claim { address payee; uint256 last_bond; uint256 queued_funds; } uint256 nextTemplateID = 0; mapping(uint256 => uint256) public templates; mapping(uint256 => bytes32) public template_hashes; mapping(bytes32 => Question) public questions; mapping(bytes32 => Claim) public question_claims; mapping(bytes32 => Commitment) public commitments; mapping(address => uint256) public arbitrator_question_fees; modifier onlyArbitrator(bytes32 question_id) { require(msg.sender == questions[question_id].arbitrator, "msg.sender must be arbitrator"); _; } modifier stateAny() { _; } modifier stateNotCreated(bytes32 question_id) { require(questions[question_id].timeout == 0, "question must not exist"); _; } modifier stateOpen(bytes32 question_id) { require(questions[question_id].timeout > 0, "question must exist"); require(!questions[question_id].is_pending_arbitration, "question must not be pending arbitration"); uint32 finalize_ts = questions[question_id].finalize_ts; require(finalize_ts == UNANSWERED || finalize_ts > uint32(now), "finalization deadline must not have passed"); uint32 opening_ts = questions[question_id].opening_ts; require(opening_ts == 0 || opening_ts <= uint32(now), "opening date must have passed"); _; } modifier statePendingArbitration(bytes32 question_id) { require(questions[question_id].is_pending_arbitration, "question must be pending arbitration"); _; } modifier stateOpenOrPendingArbitration(bytes32 question_id) { require(questions[question_id].timeout > 0, "question must exist"); uint32 finalize_ts = questions[question_id].finalize_ts; require(finalize_ts == UNANSWERED || finalize_ts > uint32(now), "finalization dealine must not have passed"); uint32 opening_ts = questions[question_id].opening_ts; require(opening_ts == 0 || opening_ts <= uint32(now), "opening date must have passed"); _; } modifier stateFinalized(bytes32 question_id) { require(isFinalized(question_id), "question must be finalized"); _; } modifier bondMustDouble(bytes32 question_id, uint256 tokens) { require(tokens > 0, "bond must be positive"); require(tokens >= (questions[question_id].bond.mul(2)), "bond must be double at least previous bond"); _; } modifier previousBondMustNotBeatMaxPrevious(bytes32 question_id, uint256 max_previous) { if (max_previous > 0) { require(questions[question_id].bond <= max_previous, "bond must exceed max_previous"); } _; } function setToken(IERC20 _token) public { require(token == IERC20(0x0), "Token can only be initialized once"); token = _token; } /// @notice Constructor, sets up some initial templates /// @dev Creates some generalized templates for different question types used in the DApp. constructor() public { createTemplate('{"title": "%s", "type": "bool", "category": "%s", "lang": "%s"}'); createTemplate('{"title": "%s", "type": "uint", "decimals": 18, "category": "%s", "lang": "%s"}'); createTemplate('{"title": "%s", "type": "single-select", "outcomes": [%s], "category": "%s", "lang": "%s"}'); createTemplate('{"title": "%s", "type": "multiple-select", "outcomes": [%s], "category": "%s", "lang": "%s"}'); createTemplate('{"title": "%s", "type": "datetime", "category": "%s", "lang": "%s"}'); } /// @notice Function for arbitrator to set an optional per-question fee. /// @dev The per-question fee, charged when a question is asked, is intended as an anti-spam measure. /// @param fee The fee to be charged by the arbitrator when a question is asked function setQuestionFee(uint256 fee) stateAny() external { arbitrator_question_fees[msg.sender] = fee; emit LogSetQuestionFee(msg.sender, fee); } /// @notice Create a reusable template, which should be a JSON document. /// Placeholders should use gettext() syntax, eg %s. /// @dev Template data is only stored in the event logs, but its block number is kept in contract storage. /// @param content The template content /// @return The ID of the newly-created template, which is created sequentially. function createTemplate(string memory content) stateAny() public returns (uint256) { uint256 id = nextTemplateID; templates[id] = block.number; template_hashes[id] = keccak256(abi.encodePacked(content)); emit LogNewTemplate(id, msg.sender, content); nextTemplateID = id.add(1); return id; } /// @notice Create a new reusable template and use it to ask a question /// @dev Template data is only stored in the event logs, but its block number is kept in contract storage. /// @param content The template content /// @param question A string containing the parameters that will be passed into the template to make the question /// @param arbitrator The arbitration contract that will have the final word on the answer if there is a dispute /// @param timeout How long the contract should wait after the answer is changed before finalizing on that answer /// @param opening_ts If set, the earliest time it should be possible to answer the question. /// @param nonce A user-specified nonce used in the question ID. Change it to repeat a question. /// @return The ID of the newly-created template, which is created sequentially. function createTemplateAndAskQuestion( string memory content, string memory question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce ) // stateNotCreated is enforced by the internal _askQuestion public returns (bytes32) { uint256 template_id = createTemplate(content); return askQuestion(template_id, question, arbitrator, timeout, opening_ts, nonce); } /// @notice Ask a new question without a bounty and return the ID /// @dev Template data is only stored in the event logs, but its block number is kept in contract storage. /// @dev Calling without the token param will only work if there is no arbitrator-set question fee. /// @dev This has the same function signature as askQuestion() in the non-ERC20 version, which is optionally payable. /// @param template_id The ID number of the template the question will use /// @param question A string containing the parameters that will be passed into the template to make the question /// @param arbitrator The arbitration contract that will have the final word on the answer if there is a dispute /// @param timeout How long the contract should wait after the answer is changed before finalizing on that answer /// @param opening_ts If set, the earliest time it should be possible to answer the question. /// @param nonce A user-specified nonce used in the question ID. Change it to repeat a question. /// @return The ID of the newly-created question, created deterministically. function askQuestion(uint256 template_id, string memory question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce) // stateNotCreated is enforced by the internal _askQuestion public returns (bytes32) { require(templates[template_id] > 0, "template must exist"); bytes32 content_hash = keccak256(abi.encodePacked(template_id, opening_ts, question)); bytes32 question_id = keccak256(abi.encodePacked(content_hash, arbitrator, timeout, msg.sender, nonce)); _askQuestion(question_id, content_hash, arbitrator, timeout, opening_ts, 0); emit LogNewQuestion(question_id, msg.sender, template_id, question, content_hash, arbitrator, timeout, opening_ts, nonce, now); return question_id; } /// @notice Ask a new question with a bounty and return the ID /// @dev Template data is only stored in the event logs, but its block number is kept in contract storage. /// @param template_id The ID number of the template the question will use /// @param question A string containing the parameters that will be passed into the template to make the question /// @param arbitrator The arbitration contract that will have the final word on the answer if there is a dispute /// @param timeout How long the contract should wait after the answer is changed before finalizing on that answer /// @param opening_ts If set, the earliest time it should be possible to answer the question. /// @param nonce A user-specified nonce used in the question ID. Change it to repeat a question. /// @param tokens The combined initial question bounty and question fee /// @return The ID of the newly-created question, created deterministically. function askQuestionERC20(uint256 template_id, string memory question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce, uint256 tokens) // stateNotCreated is enforced by the internal _askQuestion public returns (bytes32) { _deductTokensOrRevert(tokens); require(templates[template_id] > 0, "template must exist"); bytes32 content_hash = keccak256(abi.encodePacked(template_id, opening_ts, question)); bytes32 question_id = keccak256(abi.encodePacked(content_hash, arbitrator, timeout, msg.sender, nonce)); _askQuestion(question_id, content_hash, arbitrator, timeout, opening_ts, tokens); emit LogNewQuestion(question_id, msg.sender, template_id, question, content_hash, arbitrator, timeout, opening_ts, nonce, now); return question_id; } function _deductTokensOrRevert(uint256 tokens) internal { if (tokens == 0) { return; } uint256 bal = balanceOf[msg.sender]; // Deduct any tokens you have in your internal balance first if (bal > 0) { if (bal >= tokens) { balanceOf[msg.sender] = bal.sub(tokens); return; } else { tokens = tokens.sub(bal); balanceOf[msg.sender] = 0; } } // Now we need to charge the rest from require(token.transferFrom(msg.sender, address(this), tokens), "Transfer of tokens failed, insufficient approved balance?"); return; } function _askQuestion(bytes32 question_id, bytes32 content_hash, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 tokens) stateNotCreated(question_id) internal { uint256 bounty = tokens; // A timeout of 0 makes no sense, and we will use this to check existence require(timeout > 0, "timeout must be positive"); require(timeout < 365 days, "timeout must be less than 365 days"); require(arbitrator != NULL_ADDRESS, "arbitrator must be set"); // The arbitrator can set a fee for asking a question. // This is intended as an anti-spam defence. // The fee is waived if the arbitrator is asking the question. // This allows them to set an impossibly high fee and make users proxy the question through them. // This would allow more sophisticated pricing, question whitelisting etc. if (msg.sender != arbitrator) { uint256 question_fee = arbitrator_question_fees[arbitrator]; require(bounty >= question_fee, "Tokens provided must cover question fee"); bounty = bounty.sub(question_fee); balanceOf[arbitrator] = balanceOf[arbitrator].add(question_fee); } questions[question_id].content_hash = content_hash; questions[question_id].arbitrator = arbitrator; questions[question_id].opening_ts = opening_ts; questions[question_id].timeout = timeout; questions[question_id].bounty = bounty; } /// @notice Add funds to the bounty for a question /// @dev Add bounty funds after the initial question creation. Can be done any time until the question is finalized. /// @param question_id The ID of the question you wish to fund /// @param tokens The number of tokens to fund function fundAnswerBountyERC20(bytes32 question_id, uint256 tokens) stateOpen(question_id) external { _deductTokensOrRevert(tokens); questions[question_id].bounty = questions[question_id].bounty.add(tokens); emit LogFundAnswerBounty(question_id, tokens, questions[question_id].bounty, msg.sender); } /// @notice Submit an answer for a question. /// @dev Adds the answer to the history and updates the current "best" answer. /// May be subject to front-running attacks; Substitute submitAnswerCommitment()->submitAnswerReveal() to prevent them. /// @param question_id The ID of the question /// @param answer The answer, encoded into bytes32 /// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction. /// @param tokens The amount of tokens to submit function submitAnswerERC20(bytes32 question_id, bytes32 answer, uint256 max_previous, uint256 tokens) stateOpen(question_id) bondMustDouble(question_id, tokens) previousBondMustNotBeatMaxPrevious(question_id, max_previous) external { _deductTokensOrRevert(tokens); _addAnswerToHistory(question_id, answer, msg.sender, tokens, false); _updateCurrentAnswer(question_id, answer, questions[question_id].timeout); } // @notice Verify and store a commitment, including an appropriate timeout // @param question_id The ID of the question to store // @param commitment The ID of the commitment function _storeCommitment(bytes32 question_id, bytes32 commitment_id) internal { require(commitments[commitment_id].reveal_ts == COMMITMENT_NON_EXISTENT, "commitment must not already exist"); uint32 commitment_timeout = questions[question_id].timeout / COMMITMENT_TIMEOUT_RATIO; commitments[commitment_id].reveal_ts = uint32(now).add(commitment_timeout); } /// @notice Submit the hash of an answer, laying your claim to that answer if you reveal it in a subsequent transaction. /// @dev Creates a hash, commitment_id, uniquely identifying this answer, to this question, with this bond. /// The commitment_id is stored in the answer history where the answer would normally go. /// Does not update the current best answer - this is left to the later submitAnswerReveal() transaction. /// @param question_id The ID of the question /// @param answer_hash The hash of your answer, plus a nonce that you will later reveal /// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction. /// @param _answerer If specified, the address to be given as the question answerer. Defaults to the sender. /// @param tokens Number of tokens sent /// @dev Specifying the answerer is useful if you want to delegate the commit-and-reveal to a third-party. function submitAnswerCommitmentERC20(bytes32 question_id, bytes32 answer_hash, uint256 max_previous, address _answerer, uint256 tokens) stateOpen(question_id) bondMustDouble(question_id, tokens) previousBondMustNotBeatMaxPrevious(question_id, max_previous) external { _deductTokensOrRevert(tokens); bytes32 commitment_id = keccak256(abi.encodePacked(question_id, answer_hash, tokens)); address answerer = (_answerer == NULL_ADDRESS) ? msg.sender : _answerer; _storeCommitment(question_id, commitment_id); _addAnswerToHistory(question_id, commitment_id, answerer, tokens, true); } /// @notice Submit the answer whose hash you sent in a previous submitAnswerCommitment() transaction /// @dev Checks the parameters supplied recreate an existing commitment, and stores the revealed answer /// Updates the current answer unless someone has since supplied a new answer with a higher bond /// msg.sender is intentionally not restricted to the user who originally sent the commitment; /// For example, the user may want to provide the answer+nonce to a third-party service and let them send the tx /// NB If we are pending arbitration, it will be up to the arbitrator to wait and see any outstanding reveal is sent /// @param question_id The ID of the question /// @param answer The answer, encoded as bytes32 /// @param nonce The nonce that, combined with the answer, recreates the answer_hash you gave in submitAnswerCommitment() /// @param bond The bond that you paid in your submitAnswerCommitment() transaction function submitAnswerReveal(bytes32 question_id, bytes32 answer, uint256 nonce, uint256 bond) stateOpenOrPendingArbitration(question_id) external { bytes32 answer_hash = keccak256(abi.encodePacked(answer, nonce)); bytes32 commitment_id = keccak256(abi.encodePacked(question_id, answer_hash, bond)); require(!commitments[commitment_id].is_revealed, "commitment must not have been revealed yet"); require(commitments[commitment_id].reveal_ts > uint32(now), "reveal deadline must not have passed"); commitments[commitment_id].revealed_answer = answer; commitments[commitment_id].is_revealed = true; if (bond == questions[question_id].bond) { _updateCurrentAnswer(question_id, answer, questions[question_id].timeout); } emit LogAnswerReveal(question_id, msg.sender, answer_hash, answer, nonce, bond); } function _addAnswerToHistory(bytes32 question_id, bytes32 answer_or_commitment_id, address answerer, uint256 bond, bool is_commitment) internal { bytes32 new_history_hash = keccak256(abi.encodePacked(questions[question_id].history_hash, answer_or_commitment_id, bond, answerer, is_commitment)); // Update the current bond level, if there's a bond (ie anything except arbitration) if (bond > 0) { questions[question_id].bond = bond; } questions[question_id].history_hash = new_history_hash; emit LogNewAnswer(answer_or_commitment_id, question_id, new_history_hash, answerer, bond, now, is_commitment); } function _updateCurrentAnswer(bytes32 question_id, bytes32 answer, uint32 timeout_secs) internal { questions[question_id].best_answer = answer; questions[question_id].finalize_ts = uint32(now).add(timeout_secs); } /// @notice Notify the contract that the arbitrator has been paid for a question, freezing it pending their decision. /// @dev The arbitrator contract is trusted to only call this if they've been paid, and tell us who paid them. /// @param question_id The ID of the question /// @param requester The account that requested arbitration /// @param max_previous If specified, reverts if a bond higher than this was submitted after you sent your transaction. function notifyOfArbitrationRequest(bytes32 question_id, address requester, uint256 max_previous) onlyArbitrator(question_id) stateOpen(question_id) previousBondMustNotBeatMaxPrevious(question_id, max_previous) external { require(questions[question_id].bond > 0, "Question must already have an answer when arbitration is requested"); questions[question_id].is_pending_arbitration = true; emit LogNotifyOfArbitrationRequest(question_id, requester); } /// @notice Submit the answer for a question, for use by the arbitrator. /// @dev Doesn't require (or allow) a bond. /// If the current final answer is correct, the account should be whoever submitted it. /// If the current final answer is wrong, the account should be whoever paid for arbitration. /// However, the answerer stipulations are not enforced by the contract. /// @param question_id The ID of the question /// @param answer The answer, encoded into bytes32 /// @param answerer The account credited with this answer for the purpose of bond claims function submitAnswerByArbitrator(bytes32 question_id, bytes32 answer, address answerer) onlyArbitrator(question_id) statePendingArbitration(question_id) external { require(answerer != NULL_ADDRESS, "answerer must be provided"); emit LogFinalize(question_id, answer); questions[question_id].is_pending_arbitration = false; _addAnswerToHistory(question_id, answer, answerer, 0, false); _updateCurrentAnswer(question_id, answer, 0); } /// @notice Report whether the answer to the specified question is finalized /// @param question_id The ID of the question /// @return Return true if finalized function isFinalized(bytes32 question_id) view public returns (bool) { uint32 finalize_ts = questions[question_id].finalize_ts; return ( !questions[question_id].is_pending_arbitration && (finalize_ts > UNANSWERED) && (finalize_ts <= uint32(now)) ); } /// @notice (Deprecated) Return the final answer to the specified question, or revert if there isn't one /// @param question_id The ID of the question /// @return The answer formatted as a bytes32 function getFinalAnswer(bytes32 question_id) stateFinalized(question_id) external view returns (bytes32) { return questions[question_id].best_answer; } /// @notice Return the final answer to the specified question, or revert if there isn't one /// @param question_id The ID of the question /// @return The answer formatted as a bytes32 function resultFor(bytes32 question_id) stateFinalized(question_id) external view returns (bytes32) { return questions[question_id].best_answer; } /// @notice Return the final answer to the specified question, provided it matches the specified criteria. /// @dev Reverts if the question is not finalized, or if it does not match the specified criteria. /// @param question_id The ID of the question /// @param content_hash The hash of the question content (template ID + opening time + question parameter string) /// @param arbitrator The arbitrator chosen for the question (regardless of whether they are asked to arbitrate) /// @param min_timeout The timeout set in the initial question settings must be this high or higher /// @param min_bond The bond sent with the final answer must be this high or higher /// @return The answer formatted as a bytes32 function getFinalAnswerIfMatches( bytes32 question_id, bytes32 content_hash, address arbitrator, uint32 min_timeout, uint256 min_bond ) stateFinalized(question_id) external view returns (bytes32) { require(content_hash == questions[question_id].content_hash, "content hash must match"); require(arbitrator == questions[question_id].arbitrator, "arbitrator must match"); require(min_timeout <= questions[question_id].timeout, "timeout must be long enough"); require(min_bond <= questions[question_id].bond, "bond must be high enough"); return questions[question_id].best_answer; } /// @notice Assigns the winnings (bounty and bonds) to everyone who gave the accepted answer /// Caller must provide the answer history, in reverse order /// @dev Works up the chain and assign bonds to the person who gave the right answer /// If someone gave the winning answer earlier, they must get paid from the higher bond /// That means we can't pay out the bond added at n until we have looked at n-1 /// The first answer is authenticated by checking against the stored history_hash. /// One of the inputs to history_hash is the history_hash before it, so we use that to authenticate the next entry, etc /// Once we get to a null hash we'll know we're done and there are no more answers. /// Usually you would call the whole thing in a single transaction, but if not then the data is persisted to pick up later. /// @param question_id The ID of the question /// @param history_hashes Second-last-to-first, the hash of each history entry. (Final one should be empty). /// @param addrs Last-to-first, the address of each answerer or commitment sender /// @param bonds Last-to-first, the bond supplied with each answer or commitment /// @param answers Last-to-first, each answer supplied, or commitment ID if the answer was supplied with commit->reveal function claimWinnings( bytes32 question_id, bytes32[] memory history_hashes, address[] memory addrs, uint256[] memory bonds, bytes32[] memory answers ) stateFinalized(question_id) public { require(history_hashes.length > 0, "at least one history hash entry must be provided"); // These are only set if we split our claim over multiple transactions. address payee = question_claims[question_id].payee; uint256 last_bond = question_claims[question_id].last_bond; uint256 queued_funds = question_claims[question_id].queued_funds; // Starts as the hash of the final answer submitted. It'll be cleared when we're done. // If we're splitting the claim over multiple transactions, it'll be the hash where we left off last time bytes32 last_history_hash = questions[question_id].history_hash; bytes32 best_answer = questions[question_id].best_answer; uint256 i; for (i = 0; i < history_hashes.length; i++) { // Check input against the history hash, and see which of 2 possible values of is_commitment fits. bool is_commitment = _verifyHistoryInputOrRevert(last_history_hash, history_hashes[i], answers[i], bonds[i], addrs[i]); queued_funds = queued_funds.add(last_bond); (queued_funds, payee) = _processHistoryItem( question_id, best_answer, queued_funds, payee, addrs[i], bonds[i], answers[i], is_commitment); // Line the bond up for next time, when it will be added to somebody's queued_funds last_bond = bonds[i]; last_history_hash = history_hashes[i]; } if (last_history_hash != NULL_HASH) { // We haven't yet got to the null hash (1st answer), ie the caller didn't supply the full answer chain. // Persist the details so we can pick up later where we left off later. // If we know who to pay we can go ahead and pay them out, only keeping back last_bond // (We always know who to pay unless all we saw were unrevealed commits) if (payee != NULL_ADDRESS) { _payPayee(question_id, payee, queued_funds); queued_funds = 0; } question_claims[question_id].payee = payee; question_claims[question_id].last_bond = last_bond; question_claims[question_id].queued_funds = queued_funds; } else { // There is nothing left below us so the payee can keep what remains _payPayee(question_id, payee, queued_funds.add(last_bond)); delete question_claims[question_id]; } questions[question_id].history_hash = last_history_hash; } function _payPayee(bytes32 question_id, address payee, uint256 value) internal { balanceOf[payee] = balanceOf[payee].add(value); emit LogClaim(question_id, payee, value); } function _verifyHistoryInputOrRevert( bytes32 last_history_hash, bytes32 history_hash, bytes32 answer, uint256 bond, address addr ) internal pure returns (bool) { if (last_history_hash == keccak256(abi.encodePacked(history_hash, answer, bond, addr, true)) ) { return true; } if (last_history_hash == keccak256(abi.encodePacked(history_hash, answer, bond, addr, false)) ) { return false; } revert("History input provided did not match the expected hash"); } function _processHistoryItem( bytes32 question_id, bytes32 best_answer, uint256 queued_funds, address payee, address addr, uint256 bond, bytes32 answer, bool is_commitment ) internal returns (uint256, address) { // For commit-and-reveal, the answer history holds the commitment ID instead of the answer. // We look at the referenced commitment ID and switch in the actual answer. if (is_commitment) { bytes32 commitment_id = answer; // If it's a commit but it hasn't been revealed, it will always be considered wrong. if (!commitments[commitment_id].is_revealed) { delete commitments[commitment_id]; return (queued_funds, payee); } else { answer = commitments[commitment_id].revealed_answer; delete commitments[commitment_id]; } } if (answer == best_answer) { if (payee == NULL_ADDRESS) { // The entry is for the first payee we come to, ie the winner. // They get the question bounty. payee = addr; queued_funds = queued_funds.add(questions[question_id].bounty); questions[question_id].bounty = 0; } else if (addr != payee) { // Answerer has changed, ie we found someone lower down who needs to be paid // The lower answerer will take over receiving bonds from higher answerer. // They should also be paid the takeover fee, which is set at a rate equivalent to their bond. // (This is our arbitrary rule, to give consistent right-answerers a defence against high-rollers.) // There should be enough for the fee, but if not, take what we have. // There's an edge case involving weird arbitrator behaviour where we may be short. uint256 answer_takeover_fee = (queued_funds >= bond) ? bond : queued_funds; // Settle up with the old (higher-bonded) payee _payPayee(question_id, payee, queued_funds.sub(answer_takeover_fee)); // Now start queued_funds again for the new (lower-bonded) payee payee = addr; queued_funds = answer_takeover_fee; } } return (queued_funds, payee); } /// @notice Convenience function to assign bounties/bonds for multiple questions in one go, then withdraw all your funds. /// Caller must provide the answer history for each question, in reverse order /// @dev Can be called by anyone to assign bonds/bounties, but funds are only withdrawn for the user making the call. /// @param question_ids The IDs of the questions you want to claim for /// @param lengths The number of history entries you will supply for each question ID /// @param hist_hashes In a single list for all supplied questions, the hash of each history entry. /// @param addrs In a single list for all supplied questions, the address of each answerer or commitment sender /// @param bonds In a single list for all supplied questions, the bond supplied with each answer or commitment /// @param answers In a single list for all supplied questions, each answer supplied, or commitment ID function claimMultipleAndWithdrawBalance( bytes32[] memory question_ids, uint256[] memory lengths, bytes32[] memory hist_hashes, address[] memory addrs, uint256[] memory bonds, bytes32[] memory answers ) stateAny() // The finalization checks are done in the claimWinnings function public { uint256 qi; uint256 i; for (qi = 0; qi < question_ids.length; qi++) { bytes32 qid = question_ids[qi]; uint256 ln = lengths[qi]; bytes32[] memory hh = new bytes32[](ln); address[] memory ad = new address[](ln); uint256[] memory bo = new uint256[](ln); bytes32[] memory an = new bytes32[](ln); uint256 j; for (j = 0; j < ln; j++) { hh[j] = hist_hashes[i]; ad[j] = addrs[i]; bo[j] = bonds[i]; an[j] = answers[i]; i++; } claimWinnings(qid, hh, ad, bo, an); } withdraw(); } /// @notice Returns the questions's content hash, identifying the question content /// @param question_id The ID of the question function getContentHash(bytes32 question_id) public view returns(bytes32) { return questions[question_id].content_hash; } /// @notice Returns the arbitrator address for the question /// @param question_id The ID of the question function getArbitrator(bytes32 question_id) public view returns(address) { return questions[question_id].arbitrator; } /// @notice Returns the timestamp when the question can first be answered /// @param question_id The ID of the question function getOpeningTS(bytes32 question_id) public view returns(uint32) { return questions[question_id].opening_ts; } /// @notice Returns the timeout in seconds used after each answer /// @param question_id The ID of the question function getTimeout(bytes32 question_id) public view returns(uint32) { return questions[question_id].timeout; } /// @notice Returns the timestamp at which the question will be/was finalized /// @param question_id The ID of the question function getFinalizeTS(bytes32 question_id) public view returns(uint32) { return questions[question_id].finalize_ts; } /// @notice Returns whether the question is pending arbitration /// @param question_id The ID of the question function isPendingArbitration(bytes32 question_id) public view returns(bool) { return questions[question_id].is_pending_arbitration; } /// @notice Returns the current total unclaimed bounty /// @dev Set back to zero once the bounty has been claimed /// @param question_id The ID of the question function getBounty(bytes32 question_id) public view returns(uint256) { return questions[question_id].bounty; } /// @notice Returns the current best answer /// @param question_id The ID of the question function getBestAnswer(bytes32 question_id) public view returns(bytes32) { return questions[question_id].best_answer; } /// @notice Returns the history hash of the question /// @param question_id The ID of the question /// @dev Updated on each answer, then rewound as each is claimed function getHistoryHash(bytes32 question_id) public view returns(bytes32) { return questions[question_id].history_hash; } /// @notice Returns the highest bond posted so far for a question /// @param question_id The ID of the question function getBond(bytes32 question_id) public view returns(uint256) { return questions[question_id].bond; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } }
Removes liquidity to a market - external claiming any pending fees re-balancing fees pool part of the liquidity is exchanged for outcome shares if market is not balanced
function removeLiquidity(uint256 marketId, uint256 shares) external payable timeTransitions(marketId) atState(marketId, MarketState.open) { Market storage market = markets[marketId]; require(market.liquidityShares[msg.sender] >= shares, "user does not have enough balance"); claimFees(marketId); rebalanceFeesPool(marketId, shares, MarketAction.removeLiquidity); uint256[] memory outcomesShares = getMarketOutcomesShares(marketId); uint256[] memory sendAmounts = new uint256[](outcomesShares.length); uint256 poolWeight = MAX_UINT_256; for (uint256 i = 0; i < outcomesShares.length; i++) { uint256 outcomeShares = outcomesShares[i]; if (poolWeight > outcomeShares) poolWeight = outcomeShares; } uint256 liquidityAmount = shares.mul(poolWeight).div(market.liquidity); for (uint256 i = 0; i < outcomesShares.length; i++) { sendAmounts[i] = outcomesShares[i].mul(shares) / market.liquidity; sendAmounts[i] = sendAmounts[i].sub(liquidityAmount); } market.liquidity = market.liquidity.sub(shares); for (uint256 i = 0; i < outcomesShares.length; i++) { if (sendAmounts[i] > 0) { uint256 marketShares = market.sharesAvailable; uint256 outcomeShares = market.outcomes[i].shares.available; transferOutcomeSharesfromPool(msg.sender, marketId, i, sendAmounts[i]); emit MarketActionTx( msg.sender, MarketAction.buy, marketId, i, sendAmounts[i], now ); } } emit MarketActionTx(msg.sender, MarketAction.removeLiquidity, marketId, 0, shares, liquidityAmount, now); emit MarketLiquidity(marketId, market.liquidity, getMarketLiquidityPrice(marketId), now); }
5,999,285
./full_match/1/0xF7873f6F603b3C3d2C8a5e2b123A386373F2095f/sources/contracts/LoanPriceOracle.sol
Set collateral collateral oracle Emits a {CollateralOracleUpdated} event. collateralOracle_ Collateral oracle contract/
function setCollateralOracle(address collateralOracle_) external onlyRole(DEFAULT_ADMIN_ROLE) { if (IERC20Metadata(address(ICollateralOracle(collateralOracle_).currencyToken())).decimals() != 18) revert UnsupportedTokenDecimals(); collateralOracle = ICollateralOracle(collateralOracle_); emit CollateralOracleUpdated(collateralOracle_); }
17,037,614
./partial_match/1/0xa0d7a729544A4BE2287F8943d5fdDEf5c319D81b/sources/SteroidsGame.sol
Checks if the swaps of game token for stable token are stopped return true if the swaps are stopped, else - false
function isSellsTurnedOff() public view returns (bool) { return _triggerActionForAtLeastKTimes(settings.swapDays); }
4,490,481
./partial_match/1/0x72a56f7BbEe939a8C441C891e1754BB795eE0B21/sources/CROWN.sol
Begin the self-destruction counter of this contract. Once the delay has elapsed, the contract may be self-destructed. Only the contract owner may call this, and only if self-destruct has not been initiated./
function initiateSelfDestruct() external onlyOwner { require(!selfDestructInitiated, "Self-destruct already initiated."); selfDestructInitiationTime = now; selfDestructInitiated = true; emit SelfDestructInitiated(SELFDESTRUCT_DELAY); }
4,093,053
/** * @title: Idle Rebalancer contract * @summary: Used for calculating amounts to lend on each implemented protocol. * This implementation works with Compound and Fulcrum only, * when a new protocol will be added this should be replaced * @author: Idle Labs Inc., idle.finance */ pragma solidity 0.5.16; import "./interfaces/IIdleRebalancer.sol"; import "@openzeppelin/contracts/ownership/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract IdleRebalancerManaged is IIdleRebalancer, Ownable { using SafeMath for uint256; // IdleToken address address public idleToken; // protocol token (cToken) address address public cToken; // protocol token (iToken) address address public iToken; // protocol token (aToken) address address public aToken; uint256[] public lastAmounts = new uint256[](3); address public rebalancerManager; /** * @param _cToken : cToken address * @param _iToken : iToken address * @param _aToken : aToken address */ constructor(address _cToken, address _iToken, address _aToken) public { require(_cToken != address(0) && _iToken != address(0) && _aToken != address(0), 'some addr is 0'); cToken = _cToken; iToken = _iToken; aToken = _aToken; lastAmounts = [10000, 0, 0]; } /** * Throws if called by any account other than IdleToken contract. */ modifier onlyIdle() { require(msg.sender == idleToken, "Ownable: caller is not IdleToken contract"); _; } /** * Throws if called by any account other than rebalancerManager. */ modifier onlyRebalancer() { require(msg.sender == rebalancerManager, "Only rebalacer "); _; } // onlyOwner /** * sets idleToken address * NOTE: can be called only once. It's not on the constructor because we are deploying this contract * after the IdleToken contract * @param _idleToken : idleToken address */ function setIdleToken(address _idleToken) external onlyOwner { require(idleToken == address(0), "idleToken addr already set"); require(_idleToken != address(0), "_idleToken addr is 0"); idleToken = _idleToken; } /** * It allows owner to set the allowed rebalancer address * * @param _rebalancerManager : iToken address */ function setRebalancerManager(address _rebalancerManager) external onlyOwner { rebalancerManager = _rebalancerManager; } // end onlyOwner /** * Used by Rebalance manager to set the new allocations * * @param _allocations : array with allocations in percentages (100% => 10000) */ function setAllocations(uint256[] calldata _allocations) external onlyRebalancer { require(_allocations[0].add(_allocations[1]).add(_allocations[2]) == 10000, "Not allocating 100%"); lastAmounts[0] = _allocations[0]; lastAmounts[1] = _allocations[1]; lastAmounts[2] = _allocations[2]; } /** * Used by IdleToken contract to calculate the amount to be lended * on each protocol in order to get the best available rate for all funds. * * @param _rebalanceParams : first param is the total amount to be rebalanced, * all other elements are client side calculated amounts to put on each lending protocol * @return tokenAddresses : array with all token addresses used, * currently [cTokenAddress, iTokenAddress] * @return amounts : array with all amounts for each protocol in order, * currently [amountCompound, amountFulcrum] */ function calcRebalanceAmounts(uint256[] calldata _rebalanceParams) external view onlyIdle returns (address[] memory tokenAddresses, uint256[] memory amounts) { uint256 totAmountToRebalance = _rebalanceParams[0]; tokenAddresses = new address[](3); tokenAddresses[0] = cToken; tokenAddresses[1] = iToken; tokenAddresses[2] = aToken; amounts = new uint256[](3); amounts[0] = totAmountToRebalance.mul(lastAmounts[0]).div(10000); amounts[1] = totAmountToRebalance.mul(lastAmounts[1]).div(10000); amounts[2] = totAmountToRebalance.sub(amounts[0]).sub(amounts[1]); return (tokenAddresses, amounts); } }
Used by IdleToken contract to calculate the amount to be lended on each protocol in order to get the best available rate for all funds. _rebalanceParams : first param is the total amount to be rebalanced, all other elements are client side calculated amounts to put on each lending protocol return tokenAddresses : array with all token addresses used, currently [cTokenAddress, iTokenAddress] return amounts : array with all amounts for each protocol in order, currently [amountCompound, amountFulcrum]/
function calcRebalanceAmounts(uint256[] calldata _rebalanceParams) external view onlyIdle returns (address[] memory tokenAddresses, uint256[] memory amounts) { uint256 totAmountToRebalance = _rebalanceParams[0]; tokenAddresses = new address[](3); tokenAddresses[0] = cToken; tokenAddresses[1] = iToken; tokenAddresses[2] = aToken; amounts = new uint256[](3); amounts[0] = totAmountToRebalance.mul(lastAmounts[0]).div(10000); amounts[1] = totAmountToRebalance.mul(lastAmounts[1]).div(10000); amounts[2] = totAmountToRebalance.sub(amounts[0]).sub(amounts[1]); return (tokenAddresses, amounts); }
7,304,217
pragma solidity ^0.4.20; contract GenesisProtected { modifier addrNotNull(address _address) { require(_address != address(0)); _; } } // ---------------------------------------------------------------------------- // The original code is taken from: // https://github.com/OpenZeppelin/zeppelin-solidity: // master branch from zeppelin-solidity/contracts/ownership/Ownable.sol // Changed function name: transferOwnership -> setOwner. // Added inheritance from GenesisProtected (address != 0x0). // setOwner refactored for emitting after owner replacing. // ---------------------------------------------------------------------------- /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable is GenesisProtected { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a _new. * @param a The address to transfer ownership to. */ function setOwner(address a) external onlyOwner addrNotNull(a) { owner = a; emit OwnershipReplaced(msg.sender, a); } event OwnershipReplaced( address indexed previousOwner, address indexed newOwner ); } contract Enums { // Type for mapping uint (index) => name for baskets types described in WP enum BasketType { unknown, // 0 unknown team, // 1 Team foundation, // 2 Foundation arr, // 3 Advertisement, Referral program, Reward advisors, // 4 Advisors bounty, // 5 Bounty referral, // 6 Referral referrer // 7 Referrer } } contract WPTokensBaskets is Ownable, Enums { // This mapping holds all accounts ever used as baskets forever mapping (address => BasketType) internal types; // Baskets for tokens address public team; address public foundation; address public arr; address public advisors; address public bounty; // Public constructor function WPTokensBaskets( address _team, address _foundation, address _arr, address _advisors, address _bounty ) public { setTeam(_team); setFoundation(_foundation); setARR(_arr); setAdvisors(_advisors); setBounty(_bounty); } // Fallback function - do not apply any ether to this contract. function () external payable { revert(); } // Last resort to return ether. // See the last warning at // http://solidity.readthedocs.io/en/develop/contracts.html#fallback-function // for such cases. function transferEtherTo(address a) external onlyOwner addrNotNull(a) { a.transfer(address(this).balance); } function typeOf(address a) public view returns (BasketType) { return types[a]; } // Return truth if given address is not registered as token basket. function isUnknown(address a) public view returns (bool) { return types[a] == BasketType.unknown; } function isTeam(address a) public view returns (bool) { return types[a] == BasketType.team; } function isFoundation(address a) public view returns (bool) { return types[a] == BasketType.foundation; } function setTeam(address a) public onlyOwner addrNotNull(a) { require(isUnknown(a)); types[team = a] = BasketType.team; } function setFoundation(address a) public onlyOwner addrNotNull(a) { require(isUnknown(a)); types[foundation = a] = BasketType.foundation; } function setARR(address a) public onlyOwner addrNotNull(a) { require(isUnknown(a)); types[arr = a] = BasketType.arr; } function setAdvisors(address a) public onlyOwner addrNotNull(a) { require(isUnknown(a)); types[advisors = a] = BasketType.advisors; } function setBounty(address a) public onlyOwner addrNotNull(a) { require(types[a] == BasketType.unknown); types[bounty = a] = BasketType.bounty; } } // ---------------------------------------------------------------------------- // The original code is taken from: // https://github.com/OpenZeppelin/zeppelin-solidity: // master branch from zeppelin-solidity/contracts/math/SafeMath.sol // ---------------------------------------------------------------------------- /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is * greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // The original code is taken from: // https://theethereum.wiki/w/index.php/ERC20_Token_Standard // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address tokenOwner) public constant returns (uint balance); function allowance(address tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval( address indexed tokenOwner, address indexed spender, uint tokens ); } contract Token is Ownable, ERC20Interface, Enums { using SafeMath for uint; // Token full name string private constant NAME = "EnvisionX EXCHAIN Token"; // Token symbol name string private constant SYMBOL = "EXT"; // Token max fraction, in decimal signs after the point uint8 private constant DECIMALS = 18; // Tokens max supply, in EXTwei uint public constant MAX_SUPPLY = 3000000000 * (10**uint(DECIMALS)); // Tokens balances map mapping(address => uint) internal balances; // Maps with allowed amounts fot TransferFrom mapping (address => mapping (address => uint)) internal allowed; // Total amount of issued tokens, in EXTwei uint internal _totalSupply; // Map with Ether founds amount by address (using when refunds) mapping(address => uint) internal etherFunds; uint internal _earnedFunds; // Map with refunded addreses (Black List) mapping(address => bool) internal refunded; // Address of sale agent (a contract) which can mint new tokens address public mintAgent; // Token transfer allowed only when token minting is finished bool public isMintingFinished = false; // When minting was finished uint public mintingStopDate; // Total amount of tokens minted to team basket, in EXTwei. // This will not include tokens, transferred to team basket // after minting is finished. uint public teamTotal; // Amount of tokens spent by team in first 96 weeks since // minting finish date. Used to calculate team spend // restrictions according to ICO White Paper. uint public spentByTeam; // Address of WPTokensBaskets contract WPTokensBaskets public wpTokensBaskets; // Constructor function Token(WPTokensBaskets baskets) public { wpTokensBaskets = baskets; mintAgent = owner; } // Fallback function - do not apply any ether to this contract. function () external payable { revert(); } // Last resort to return ether. // See the last warning at // http://solidity.readthedocs.io/en/develop/contracts.html#fallback-function // for such cases. function transferEtherTo(address a) external onlyOwner addrNotNull(a) { a.transfer(address(this).balance); } /** ---------------------------------------------------------------------- ERC20 Interface implementation */ // Return token full name function name() public pure returns (string) { return NAME; } // Return token symbol name function symbol() public pure returns (string) { return SYMBOL; } // Return amount of decimals after point function decimals() public pure returns (uint8) { return DECIMALS; } // Return total amount of issued tokens, in EXTwei function totalSupply() public constant returns (uint) { return _totalSupply; } // Return account balance in tokens (in EXTwei) function balanceOf(address _address) public constant returns (uint) { return balances[_address]; } // Transfer tokens to another account function transfer(address to, uint value) public addrNotNull(to) returns (bool) { if (balances[msg.sender] < value) return false; if (isFrozen(wpTokensBaskets.typeOf(msg.sender), value)) return false; balances[msg.sender] = balances[msg.sender].sub(value); balances[to] = balances[to].add(value); saveTeamSpent(msg.sender, value); emit Transfer(msg.sender, to, value); return true; } // Transfer tokens from one account to another, // using permissions defined with approve() method. function transferFrom(address from, address to, uint value) public addrNotNull(to) returns (bool) { if (balances[from] < value) return false; if (allowance(from, msg.sender) < value) return false; if (isFrozen(wpTokensBaskets.typeOf(from), value)) return false; balances[from] = balances[from].sub(value); balances[to] = balances[to].add(value); allowed[from][msg.sender] = allowed[from][msg.sender].sub(value); saveTeamSpent(from, value); emit Transfer(from, to, value); return true; } // Allow to transfer given amount of tokens (in EXTwei) // to account which is not owner. function approve(address spender, uint value) public returns (bool) { if (msg.sender == spender) return false; allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } // Return amount of tokens (in EXTwei) which allowed to // be transferred by non-owner spender function allowance(address _owner, address spender) public constant returns (uint) { return allowed[_owner][spender]; } /** ---------------------------------------------------------------------- Other methods */ // Return account funds in ether (in wei) function etherFundsOf(address _address) public constant returns (uint) { return etherFunds[_address]; } // Return total amount of funded ether, in wei function earnedFunds() public constant returns (uint) { return _earnedFunds; } // Return true if given address have been refunded function isRefunded(address _address) public view returns (bool) { return refunded[_address]; } // Set new address of sale agent contract. // Will be called for each sale stage: PrivateSale, PreSale, MainSale. function setMintAgent(address a) public onlyOwner addrNotNull(a) { emit MintAgentReplaced(mintAgent, a); mintAgent = a; } // Interface for sale agent contract - mint new tokens function mint(address to, uint256 extAmount, uint256 etherAmount) public { require(!isMintingFinished); require(msg.sender == mintAgent); require(!refunded[to]); _totalSupply = _totalSupply.add(extAmount); require(_totalSupply <= MAX_SUPPLY); balances[to] = balances[to].add(extAmount); if (wpTokensBaskets.isUnknown(to)) { _earnedFunds = _earnedFunds.add(etherAmount); etherFunds[to] = etherFunds[to].add(etherAmount); } else if (wpTokensBaskets.isTeam(to)) { teamTotal = teamTotal.add(extAmount); } emit Mint(to, extAmount); emit Transfer(msg.sender, to, extAmount); } // Destroy minted tokens and refund ether spent by investor. // Used in AML (Anti Money Laundering) workflow. // Will be called only by humans because there is no way // to withdraw crowdfunded ether from Beneficiary account // from context of this account. // Important note: all tokens minted to team, foundation etc. // will NOT be burned, because they in general are spent // during the sale and its too expensive to track all these // transactions. function burnTokensAndRefund(address _address) external payable addrNotNull(_address) onlyOwner() { require(msg.value > 0 && msg.value == etherFunds[_address]); _totalSupply = _totalSupply.sub(balances[_address]); balances[_address] = 0; _earnedFunds = _earnedFunds.sub(msg.value); etherFunds[_address] = 0; refunded[_address] = true; _address.transfer(msg.value); } // Stop tokens minting forever. function finishMinting() external onlyOwner { require(!isMintingFinished); isMintingFinished = true; mintingStopDate = now; emit MintingFinished(); } /** ---------------------------------------------------------------------- Tokens freeze logic, according to ICO White Paper */ // Return truth if given _value amount of tokens (in EXTwei) // cannot be transferred from account due to spend restrictions // defined in ICO White Paper. // !!!Caveat of current implementaion!!! // Say, // 1. There was 100 tokens minted to the team basket; // 2. Minting was finished and 24 weeks elapsed, and now // team can spend up to 25 tokens till next 24 weeks; // 3. Someone transfers another 100 tokens to the team basket; // 4. ... // Problem is, actually, you can't spend any of these extra 100 // tokens until 96 weeks will elapse since minting finish date. // That's because after next 24 weeks will be unlocked only // 25 tokens more (25% of *minted* tokens) and so on. // So, DO NOT send tokens to the team basket until 96 weeks elapse! function isFrozen( BasketType _basketType, uint _value ) public view returns (bool) { if (!isMintingFinished) { // Allow spend only after minting is finished return true; } if (_basketType == BasketType.foundation) { // Allow to spend foundation tokens only after // 48 weeks after minting is finished return now < mintingStopDate + 48 weeks; } if (_basketType == BasketType.team) { // Team allowed to spend tokens: // 25% - after minting finished date + 24 weeks; // 50% - after minting finished date + 48 weeks; // 75% - after minting finished date + 72 weeks; // 100% - after minting finished date + 96 weeks. if (mintingStopDate + 96 weeks <= now) { return false; } if (now < mintingStopDate + 24 weeks) return true; // Calculate fraction as percents multipled to 10^10. // Without this owner will be able to spend fractions // less than 1% per transaction. uint fractionSpent = spentByTeam.add(_value).mul(1000000000000).div(teamTotal); if (now < mintingStopDate + 48 weeks) { return 250000000000 < fractionSpent; } if (now < mintingStopDate + 72 weeks) { return 500000000000 < fractionSpent; } // from 72 to 96 weeks elapsed return 750000000000 < fractionSpent; } // No restrictions for other token holders return false; } // Save amount of spent tokens by team till 96 weeks after minting // finish date. This is vital because without the check we'll eventually // overflow the uint256. function saveTeamSpent(address _owner, uint _value) internal { if (wpTokensBaskets.isTeam(_owner)) { if (now < mintingStopDate + 96 weeks) spentByTeam = spentByTeam.add(_value); } } /** ---------------------------------------------------------------------- Events */ // Emitted when mint agent (address of a sale contract) // replaced with new one event MintAgentReplaced( address indexed previousMintAgent, address indexed newMintAgent ); // Emitted when new tokens were created and funded to account event Mint(address indexed to, uint256 amount); // Emitted when tokens minting is finished. event MintingFinished(); } contract Killable is Ownable { function kill(address a) external onlyOwner addrNotNull(a) { selfdestruct(a); } } contract Beneficiary is Killable { // Address of account which will receive all ether // gathered from ICO address public beneficiary; // Constructor function Beneficiary() public { beneficiary = owner; } // Fallback function - do not apply any ether to this contract. function () external payable { revert(); } // Set new beneficiary for ICO function setBeneficiary(address a) external onlyOwner addrNotNull(a) { beneficiary = a; } } contract TokenSale is Killable, Enums { using SafeMath for uint256; // Type describing: // - the address of the beneficiary of the tokens; // - the final amount of tokens calculated according to the // terms of the WP; // - the amount of Ether (in Wei) if the beneficiary is an investor // This type is used in arrays[8] that should be declare in the heir // contracts. struct tokens { address beneficiary; uint256 extAmount; uint256 ethAmount; } // Sale stage start date/time, Unix timestamp uint32 public start; // Sale stage stop date/time, Unix timestamp uint32 public stop; // Min ether amount for purchase uint256 public minBuyingAmount; // Price of one token, in wei uint256 public currentPrice; // Amount of tokens available, in EXTwei uint256 public remainingSupply; // Amount of earned funds, in wei uint256 public earnedFunds; // Address of Token contract Token public token; // Address of Beneficiary contract - a container // for the beneficiary address Beneficiary internal _beneficiary; // Equals to 10^decimals. // Internally tokens stored as EXTwei (token count * 10^decimals). // Used to convert EXT to EXTwei and vice versa. uint256 internal dec; // Constructor function TokenSale( Token _token, // address of EXT ERC20 token contract Beneficiary beneficiary, // address of container for Ether beneficiary uint256 _supplyAmount // in EXT ) public { token = _token; _beneficiary = beneficiary; // Factor for convertation EXT to EXTwei and vice versa dec = 10 ** uint256(token.decimals()); // convert to EXTwei remainingSupply = _supplyAmount.mul(dec); } // Fallback function. Here we'll receive all investments. function() external payable { purchase(); } // Investments receive logic. Must be overrided in // arbitrary sale agent (per each sale stage). function purchase() public payable; // Return truth if purchase with given _value of ether // (in wei) can be made function canPurchase(uint256 _value) public view returns (bool) { return start <= now && now <= stop && minBuyingAmount <= _value && toEXTwei(_value) <= remainingSupply; } // Return address of crowdfunding beneficiary address. function beneficiary() public view returns (address) { return _beneficiary.beneficiary(); } // Return truth if there are tokens which can be purchased. function isActive() public view returns (bool) { return canPurchase(minBuyingAmount); } // Initialize tokensArray records with actual addresses of WP tokens baskets function setBaskets(tokens[8] memory _tokensArray) internal view { _tokensArray[uint8(BasketType.unknown)].beneficiary = msg.sender; _tokensArray[uint8(BasketType.team)].beneficiary = token.wpTokensBaskets().team(); _tokensArray[uint8(BasketType.foundation)].beneficiary = token.wpTokensBaskets().foundation(); _tokensArray[uint8(BasketType.arr)].beneficiary = token.wpTokensBaskets().arr(); _tokensArray[uint8(BasketType.advisors)].beneficiary = token.wpTokensBaskets().advisors(); _tokensArray[uint8(BasketType.bounty)].beneficiary = token.wpTokensBaskets().bounty(); } // Return amount of tokens (in EXTwei) which can be purchased // at the moment for given amount of ether (in wei). function toEXTwei(uint256 _value) public view returns (uint256) { return _value.mul(dec).div(currentPrice); } // Return amount of bonus tokens (in EXTwei) // Receive amount of tokens (in EXTwei) that will be sale, and bonus percent function bonus(uint256 _tokens, uint8 _bonus) internal pure returns (uint256) { return _tokens.mul(_bonus).div(100); } // Initialize tokensArray records with actual amounts of tokens function calcWPTokens(tokens[8] memory a, uint8 _bonus) internal pure { a[uint8(BasketType.unknown)].extAmount = a[uint8(BasketType.unknown)].extAmount.add( bonus( a[uint8(BasketType.unknown)].extAmount, _bonus ) ); uint256 n = a[uint8(BasketType.unknown)].extAmount; a[uint8(BasketType.team)].extAmount = n.mul(24).div(40); a[uint8(BasketType.foundation)].extAmount = n.mul(20).div(40); a[uint8(BasketType.arr)].extAmount = n.mul(10).div(40); a[uint8(BasketType.advisors)].extAmount = n.mul(4).div(40); a[uint8(BasketType.bounty)].extAmount = n.mul(2).div(40); } // Send received ether (in wei) to beneficiary function transferFunds(uint256 _value) internal { beneficiary().transfer(_value); earnedFunds = earnedFunds.add(_value); } // Method for call mint() in EXT ERC20 contract. // mint() will be called for each record if amount of tokens > 0 function createTokens(tokens[8] memory _tokensArray) internal { for (uint i = 0; i < _tokensArray.length; i++) { if (_tokensArray[i].extAmount > 0) { token.mint( _tokensArray[i].beneficiary, _tokensArray[i].extAmount, _tokensArray[i].ethAmount ); } } } } contract PrivateSale is TokenSale { using SafeMath for uint256; // List of investors allowed to buy tokens at PrivateSale mapping(address => bool) internal allowedInvestors; function PrivateSale(Token _token, Beneficiary _beneficiary) TokenSale(_token, _beneficiary, uint256(400000000)) public { start = 1522627620; stop = 1525046399; minBuyingAmount = 70 szabo; currentPrice = 70 szabo; } function purchase() public payable { require(isInvestorAllowed(msg.sender)); require(canPurchase(msg.value)); transferFunds(msg.value); tokens[8] memory tokensArray; tokensArray[uint8(BasketType.unknown)].extAmount = toEXTwei(msg.value); setBaskets(tokensArray); remainingSupply = remainingSupply.sub( tokensArray[uint8(BasketType.unknown)].extAmount ); calcWPTokens(tokensArray, 30); tokensArray[uint8(BasketType.unknown)].ethAmount = msg.value; createTokens(tokensArray); } // Register new investor function allowInvestor(address a) public onlyOwner addrNotNull(a) { allowedInvestors[a] = true; } // Discard existing investor function denyInvestor(address a) public onlyOwner addrNotNull(a) { delete allowedInvestors[a]; } // Return truth if given account is allowed to buy tokens function isInvestorAllowed(address a) public view returns (bool) { return allowedInvestors[a]; } }
Allow to transfer given amount of tokens (in EXTwei) to account which is not owner.
function approve(address spender, uint value) public returns (bool) { if (msg.sender == spender) return false; allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; }
13,433,372
// File: contracts/zeppelin/upgradable/Initializable.sol pragma solidity >=0.4.24 <0.6.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance is already initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. uint256 cs; assembly { cs := extcodesize(address) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } // File: contracts/zeppelin/upgradable/utils/ReentrancyGuard.sol pragma solidity ^0.5.2; /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <remco@2π.com>, Eenae <alexey@mixbytes.io> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard is Initializable { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; function initialize() public initializer { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: no reentrant allowed"); } } // File: contracts/zeppelin/GSN/Context.sol pragma solidity ^0.5.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts/zeppelin/access/Roles.sol pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account doesn't have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: contracts/zeppelin/upgradable/access/roles/UpgradablePauserRole.sol pragma solidity ^0.5.0; contract UpgradablePauserRole is Initializable, Context { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; function initialize(address sender) public initializer { if (!isPauser(sender)) { _addPauser(sender); } } modifier onlyPauser() { require(isPauser(_msgSender()), "PauserRole: caller doesn't have the role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(_msgSender()); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } // File: contracts/zeppelin/upgradable/lifecycle/UpgradablePausable.sol pragma solidity ^0.5.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ contract UpgradablePausable is Initializable, Context, UpgradablePauserRole { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ function initialize(address sender) public initializer { UpgradablePauserRole.initialize(sender); _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: contracts/zeppelin/upgradable/ownership/UpgradableOwnable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be aplied to your functions to restrict their use to * the owner. */ contract UpgradableOwnable is Initializable, Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function initialize(address sender) public initializer { _owner = sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * > Note: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/zeppelin/introspection/IERC1820Registry.sol pragma solidity ^0.5.0; /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as `account`'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } // File: contracts/zeppelin/token/ERC777/IERC777Recipient.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of `IERC777` tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * [ERC1820 global registry](https://eips.ethereum.org/EIPS/eip-1820). * * See `IERC1820Registry` and `ERC1820Implementer`. */ interface IERC777Recipient { /** * @dev Called by an `IERC777` token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * `IERC777.balanceOf`, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint amount, bytes calldata userData, bytes calldata operatorData ) external; } // File: contracts/zeppelin/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/zeppelin/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/zeppelin/utils/Address.sol pragma solidity ^0.5.0; /** * @dev Collection of functions related to the address type, */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } } // File: contracts/zeppelin/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/zeppelin/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.0; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } } // File: contracts/IBridge_v1.sol pragma solidity ^0.5.0; interface IBridge_v1 { function version() external pure returns (string memory); function getFeePercentage() external view returns(uint); function calcMaxWithdraw() external view returns (uint); /** * ERC-20 tokens approve and transferFrom pattern * See https://eips.ethereum.org/EIPS/eip-20#transferfrom */ function receiveTokens(address tokenToUse, uint256 amount) external returns(bool); /** * ERC-777 tokensReceived hook allows to send tokens to a contract and notify it in a single transaction * See https://eips.ethereum.org/EIPS/eip-777#motivation for details */ function tokensReceived ( address operator, address from, address to, uint amount, bytes calldata userData, bytes calldata operatorData ) external; /** * Accepts the transaction from the other chain that was voted and sent by the federation contract */ function acceptTransfer( address originalTokenAddress, address receiver, uint256 amount, string calldata symbol, bytes32 blockHash, bytes32 transactionHash, uint32 logIndex, uint8 decimals, uint256 granularity ) external returns(bool); event Cross(address indexed _tokenAddress, address indexed _to, uint256 _amount, string _symbol, bytes _userData, uint8 _decimals, uint256 _granularity); event NewSideToken(address indexed _newSideTokenAddress, address indexed _originalTokenAddress, string _newSymbol, uint256 _granularity); event AcceptedCrossTransfer(address indexed _tokenAddress, address indexed _to, uint256 _amount, uint8 _decimals, uint256 _granularity, uint256 _formattedAmount, uint8 _calculatedDecimals, uint256 _calculatedGranularity); event FeePercentageChanged(uint256 _amount); } // File: contracts/ISideToken.sol pragma solidity ^0.5.0; interface ISideToken { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external pure returns (uint8); function granularity() external view returns (uint256); function burn(uint256 amount, bytes calldata data) external; function mint(address account, uint256 amount, bytes calldata userData, bytes calldata operatorData) external; function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256); function send(address recipient, uint256 amount, bytes calldata data) external; function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); } // File: contracts/ISideTokenFactory.sol pragma solidity ^0.5.0; interface ISideTokenFactory { function createSideToken(string calldata name, string calldata symbol, uint256 granularity) external returns(address); event SideTokenCreated(address indexed sideToken, string symbol, uint256 granularity); } // File: contracts/zeppelin/ownership/Ownable.sol pragma solidity ^0.5.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { _owner = _msgSender(); emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _msgSender() == _owner; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts/AllowTokens.sol pragma solidity >=0.4.21 <0.6.0; contract AllowTokens is Ownable { using SafeMath for uint256; address constant private NULL_ADDRESS = address(0); mapping (address => bool) public allowedTokens; bool private validateAllowedTokens; uint256 private maxTokensAllowed; uint256 private minTokensAllowed; uint256 public dailyLimit; event AllowedTokenAdded(address indexed _tokenAddress); event AllowedTokenRemoved(address indexed _tokenAddress); event AllowedTokenValidation(bool _enabled); event MaxTokensAllowedChanged(uint256 _maxTokens); event MinTokensAllowedChanged(uint256 _minTokens); event DailyLimitChanged(uint256 dailyLimit); modifier notNull(address _address) { require(_address != NULL_ADDRESS, "AllowTokens: Address cannot be empty"); _; } constructor(address _manager) public { transferOwnership(_manager); validateAllowedTokens = true; maxTokensAllowed = 10000 ether; minTokensAllowed = 1 ether; dailyLimit = 100000 ether; } function isValidatingAllowedTokens() external view returns(bool) { return validateAllowedTokens; } function getMaxTokensAllowed() external view returns(uint256) { return maxTokensAllowed; } function getMinTokensAllowed() external view returns(uint256) { return minTokensAllowed; } function allowedTokenExist(address token) private view notNull(token) returns (bool) { return allowedTokens[token]; } function isTokenAllowed(address token) public view notNull(token) returns (bool) { if (validateAllowedTokens) { return allowedTokenExist(token); } return true; } function addAllowedToken(address token) external onlyOwner { require(!allowedTokenExist(token), "AllowTokens: Token already exists in allowedTokens"); allowedTokens[token] = true; emit AllowedTokenAdded(token); } function removeAllowedToken(address token) external onlyOwner { require(allowedTokenExist(token), "AllowTokens: Token does not exis in allowedTokenst"); allowedTokens[token] = false; emit AllowedTokenRemoved(token); } function enableAllowedTokensValidation() external onlyOwner { validateAllowedTokens = true; emit AllowedTokenValidation(validateAllowedTokens); } function disableAllowedTokensValidation() external onlyOwner { // Before disabling Allowed Tokens Validations some kind of contract validation system // should be implemented on the Bridge for the methods receiveTokens, tokenFallback and tokensReceived validateAllowedTokens = false; emit AllowedTokenValidation(validateAllowedTokens); } function setMaxTokensAllowed(uint256 maxTokens) external onlyOwner { require(maxTokens >= minTokensAllowed, "AllowTokens: Max Tokens should be equal or bigger than Min Tokens"); maxTokensAllowed = maxTokens; emit MaxTokensAllowedChanged(maxTokensAllowed); } function setMinTokensAllowed(uint256 minTokens) external onlyOwner { require(maxTokensAllowed >= minTokens, "AllowTokens: Min Tokens should be equal or smaller than Max Tokens"); minTokensAllowed = minTokens; emit MinTokensAllowedChanged(minTokensAllowed); } function changeDailyLimit(uint256 _dailyLimit) external onlyOwner { require(_dailyLimit >= maxTokensAllowed, "AllowTokens: Daily Limit should be equal or bigger than Max Tokens"); dailyLimit = _dailyLimit; emit DailyLimitChanged(_dailyLimit); } // solium-disable-next-line max-len function isValidTokenTransfer(address tokenToUse, uint amount, uint spentToday, bool isSideToken) external view returns (bool) { if(amount > maxTokensAllowed) return false; if(amount < minTokensAllowed) return false; if (spentToday + amount > dailyLimit || spentToday + amount < spentToday) return false; if(!isSideToken && !isTokenAllowed(tokenToUse)) return false; return true; } function calcMaxWithdraw(uint spentToday) external view returns (uint) { uint maxWithrow = dailyLimit - spentToday; if (dailyLimit < spentToday) return 0; if(maxWithrow > maxTokensAllowed) maxWithrow = maxTokensAllowed; return maxWithrow; } } // File: contracts/zeppelin/token/ERC777/IERC777.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * [ERC1820 registry standard](https://eips.ethereum.org/EIPS/eip-1820) to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See `IERC1820Registry` and * `ERC1820Implementer`. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See `IERC777Sender` and `IERC777Recipient`. * * Emits a `Sent` event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the `tokensReceived` * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See `IERC777Sender`. * * Emits a `Burned` event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See `operatorSend` and `operatorBurn`. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See `isOperatorFor`. * * Emits an `AuthorizedOperator` event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Make an account an operator of the caller. * * See `isOperatorFor` and `defaultOperators`. * * Emits a `RevokedOperator` event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if `authorizeOperator` was never called on * them. * * This list is immutable, but individual holders may revoke these via * `revokeOperator`, in which case `isOperatorFor` will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See `IERC777Sender` and `IERC777Recipient`. * * Emits a `Sent` event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the `tokensReceived` * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destoys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See `IERC777Sender`. * * Emits a `Burned` event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } // File: contracts/Utils.sol pragma solidity ^0.5.0; library Utils { using SafeMath for uint256; IERC1820Registry constant private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); // keccak256("ERC777Token") bytes32 constant private TOKENS_ERC777_HASH = 0xac7fbab5f54a3ca8194167523c6753bfeb96a445279294b6125b68cce2177054; function getTokenInfo(address tokenToUse) external view returns (uint8 decimals, uint256 granularity, string memory symbol) { decimals = getDecimals(tokenToUse); granularity = getGranularity(tokenToUse); symbol = getSymbol(tokenToUse); } function getSymbol(address tokenToUse) public view returns (string memory symbol) { //support 32 bytes or string symbol (bool success, bytes memory data) = tokenToUse.staticcall(abi.encodeWithSignature("symbol()")); require(success, "Utils: Token hasn't symbol()"); if (data.length == 32) { symbol = bytes32ToString(abi.decode(data, (bytes32))); } else { symbol = abi.decode(data, (string)); } require(bytes(symbol).length > 0, "Utils: Token empty symbol"); return symbol; } function getDecimals(address tokenToUse) public view returns (uint8) { //support decimals as uint256 or uint8 (bool success, bytes memory data) = tokenToUse.staticcall(abi.encodeWithSignature("decimals()")); require(success, "Utils: No decimals"); require(data.length == 32, "Utils: Decimals not uint<M>"); // uint<M>: enc(X) is the big-endian encoding of X, //padded on the higher-order (left) side with zero-bytes such that the length is 32 bytes. uint256 decimalsDecoded = abi.decode(data, (uint256)); require(decimalsDecoded <= 18, "Utils: Decimals not in 0 to 18"); return uint8(decimalsDecoded); } function getGranularity(address tokenToUse) public view returns (uint256 granularity) { granularity = 1; //support granularity if ERC777 address implementer = _erc1820.getInterfaceImplementer(tokenToUse, TOKENS_ERC777_HASH); if (implementer != address(0)) { granularity = IERC777(implementer).granularity(); //Verify granularity is power of 10 to keep it compatible with ERC20 decimals granularityToDecimals(granularity); } return granularity; } /* bytes32 (fixed-size array) to string (dynamically-sized array) */ function bytes32ToString(bytes32 _bytes32) internal pure returns (string memory) { uint8 i = 0; while(i < 32 && _bytes32[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && _bytes32[i] != 0; i++) { bytesArray[i] = _bytes32[i]; } return string(bytesArray); } function decimalsToGranularity(uint8 decimals) public pure returns (uint256) { require(decimals <= 18, "Utils: Decimals not in 0 to 18"); return uint256(10)**(18-decimals); } function granularityToDecimals(uint256 granularity) public pure returns (uint8) { if(granularity == 1) return 18; if(granularity == 10) return 17; if(granularity == 100) return 16; if(granularity == 1000) return 15; if(granularity == 10000) return 14; if(granularity == 100000) return 13; if(granularity == 1000000) return 12; if(granularity == 10000000) return 11; if(granularity == 100000000) return 10; if(granularity == 1000000000) return 9; if(granularity == 10000000000) return 8; if(granularity == 100000000000) return 7; if(granularity == 1000000000000) return 6; if(granularity == 10000000000000) return 5; if(granularity == 100000000000000) return 4; if(granularity == 1000000000000000) return 3; if(granularity == 10000000000000000) return 2; if(granularity == 100000000000000000) return 1; if(granularity == 1000000000000000000) return 0; require(false, "Utils: invalid granularity"); } function calculateGranularityAndAmount(uint8 decimals, uint256 granularity, uint256 amount) external pure returns(uint256 calculatedGranularity, uint256 formattedAmount) { if(decimals == 18) { //tokenAddress is a ERC20 with 18 decimals should have 1 granularity //tokenAddress is a ERC777 token we give the same granularity calculatedGranularity = granularity; formattedAmount = amount; } else { //tokenAddress is a ERC20 with other than 18 decimals calculatedGranularity = decimalsToGranularity(decimals); formattedAmount = amount.mul(calculatedGranularity); } } function calculateDecimalsAndAmount(address tokenAddress, uint256 granularity, uint256 amount) external view returns (uint8 calculatedDecimals, uint256 formattedAmount) { uint8 tokenDecimals = getDecimals(tokenAddress); //As side tokens are ERC777 we need to convert granularity to decimals calculatedDecimals = granularityToDecimals(granularity); require(tokenDecimals == calculatedDecimals, "Utils: Token decimals differ from decimals obtained from granularity"); formattedAmount = amount.div(granularity); } } // File: contracts/Bridge_v1.sol pragma solidity ^0.5.0; // Import base Initializable contract // Import interface and library from OpenZeppelin contracts contract Bridge_v1 is Initializable, IBridge_v1, IERC777Recipient, UpgradablePausable, UpgradableOwnable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; using Address for address; address constant private NULL_ADDRESS = address(0); bytes32 constant private NULL_HASH = bytes32(0); IERC1820Registry constant private erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); address private federation; uint256 private feePercentage; string public symbolPrefix; uint256 public lastDay; uint256 public spentToday; mapping (address => ISideToken) public mappedTokens; // OirignalToken => SideToken mapping (address => address) public originalTokens; // SideToken => OriginalToken mapping (address => bool) public knownTokens; // OriginalToken => true mapping(bytes32 => bool) public processed; // ProcessedHash => true AllowTokens public allowTokens; ISideTokenFactory public sideTokenFactory; //Bridge_v1 variables bool public isUpgrading; uint256 constant public feePercentageDivider = 10000; // Porcentage with up to 2 decimals event FederationChanged(address _newFederation); event SideTokenFactoryChanged(address _newSideTokenFactory); event Upgrading(bool isUpgrading); function initialize( address _manager, address _federation, address _allowTokens, address _sideTokenFactory, string memory _symbolPrefix ) public initializer { UpgradableOwnable.initialize(_manager); UpgradablePausable.initialize(_manager); symbolPrefix = _symbolPrefix; allowTokens = AllowTokens(_allowTokens); _changeSideTokenFactory(_sideTokenFactory); _changeFederation(_federation); //keccak256("ERC777TokensRecipient") erc1820.setInterfaceImplementer(address(this), 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b, address(this)); } function version() external pure returns (string memory) { return "v1"; } modifier onlyFederation() { require(msg.sender == federation, "Bridge: Sender not Federation"); _; } modifier whenNotUpgrading() { require(!isUpgrading, "Bridge: Upgrading"); _; } function acceptTransfer( address tokenAddress, address receiver, uint256 amount, string calldata symbol, bytes32 blockHash, bytes32 transactionHash, uint32 logIndex, uint8 decimals, uint256 granularity ) external onlyFederation whenNotPaused nonReentrant returns(bool) { require(tokenAddress != NULL_ADDRESS, "Bridge: Token is null"); require(receiver != NULL_ADDRESS, "Bridge: Receiver is null"); require(amount > 0, "Bridge: Amount 0"); require(bytes(symbol).length > 0, "Bridge: Empty symbol"); require(blockHash != NULL_HASH, "Bridge: BlockHash is null"); require(transactionHash != NULL_HASH, "Bridge: Transaction is null"); require(decimals <= 18, "Bridge: Decimals bigger 18"); require(Utils.granularityToDecimals(granularity) <= 18, "Bridge: invalid granularity"); _processTransaction(blockHash, transactionHash, receiver, amount, logIndex); if (knownTokens[tokenAddress]) { _acceptCrossBackToToken(receiver, tokenAddress, decimals, granularity, amount); } else { _acceptCrossToSideToken(receiver, tokenAddress, decimals, granularity, amount, symbol); } return true; } function _acceptCrossToSideToken( address receiver, address tokenAddress, uint8 decimals, uint256 granularity, uint256 amount, string memory symbol ) private { (uint256 calculatedGranularity,uint256 formattedAmount) = Utils.calculateGranularityAndAmount(decimals, granularity, amount); ISideToken sideToken = mappedTokens[tokenAddress]; if (address(sideToken) == NULL_ADDRESS) { sideToken = _createSideToken(tokenAddress, symbol, calculatedGranularity); } else { require(calculatedGranularity == sideToken.granularity(), "Bridge: Granularity differ from side token"); } sideToken.mint(receiver, formattedAmount, "", ""); emit AcceptedCrossTransfer(tokenAddress, receiver, amount, decimals, granularity, formattedAmount, 18, calculatedGranularity); } function _acceptCrossBackToToken(address receiver, address tokenAddress, uint8 decimals, uint256 granularity, uint256 amount) private { require(decimals == 18, "Bridge: Invalid decimals cross back"); //As side tokens are ERC777 we need to convert granularity to decimals (uint8 calculatedDecimals, uint256 formattedAmount) = Utils.calculateDecimalsAndAmount(tokenAddress, granularity, amount); IERC20(tokenAddress).safeTransfer(receiver, formattedAmount); emit AcceptedCrossTransfer(tokenAddress, receiver, amount, decimals, granularity, formattedAmount, calculatedDecimals, 1); } /** * ERC-20 tokens approve and transferFrom pattern * See https://eips.ethereum.org/EIPS/eip-20#transferfrom */ function receiveTokens(address tokenToUse, uint256 amount) external whenNotUpgrading whenNotPaused nonReentrant returns(bool) { address sender = _msgSender(); require(!sender.isContract(), "Bridge: Sender can't be a contract"); //Transfer the tokens on IERC20, they should be already Approved for the bridge Address to use them IERC20(tokenToUse).safeTransferFrom(_msgSender(), address(this), amount); crossTokens(tokenToUse, sender, amount, ""); return true; } /** * ERC-777 tokensReceived hook allows to send tokens to a contract and notify it in a single transaction * See https://eips.ethereum.org/EIPS/eip-777#motivation for details */ function tokensReceived ( address operator, address from, address to, uint amount, bytes calldata userData, bytes calldata ) external whenNotPaused whenNotUpgrading { //Hook from ERC777address if(operator == address(this)) return; // Avoid loop from bridge calling to ERC77transferFrom require(to == address(this), "Bridge: Not to address"); address tokenToUse = _msgSender(); //This can only be used with trusted contracts crossTokens(tokenToUse, from, amount, userData); } function crossTokens(address tokenToUse, address from, uint256 amount, bytes memory userData) private { bool isASideToken = originalTokens[tokenToUse] != NULL_ADDRESS; //Send the payment to the MultiSig of the Federation uint256 fee = 0; if(feePercentage > 0) { fee = amount.mul(feePercentage).div(feePercentageDivider); IERC20(tokenToUse).safeTransfer(owner(), fee); } uint256 amountMinusFees = amount - fee; if (isASideToken) { verifyWithAllowTokens(tokenToUse, amount, isASideToken); //Side Token Crossing ISideToken(tokenToUse).burn(amountMinusFees, userData); // solium-disable-next-line max-len emit Cross(originalTokens[tokenToUse], from, amountMinusFees, ISideToken(tokenToUse).symbol(), userData, ISideToken(tokenToUse).decimals(), ISideToken(tokenToUse).granularity()); } else { //Main Token Crossing knownTokens[tokenToUse] = true; (uint8 decimals, uint256 granularity, string memory symbol) = Utils.getTokenInfo(tokenToUse); uint formattedAmount = amount; if(decimals != 18) { formattedAmount = amount.mul(uint256(10)**(18-decimals)); } //We consider the amount before fees converted to 18 decimals to check the limits verifyWithAllowTokens(tokenToUse, formattedAmount, isASideToken); emit Cross(tokenToUse, from, amountMinusFees, symbol, userData, decimals, granularity); } } function _createSideToken(address token, string memory symbol, uint256 granularity) private returns (ISideToken sideToken){ string memory newSymbol = string(abi.encodePacked(symbolPrefix, symbol)); address sideTokenAddress = sideTokenFactory.createSideToken(newSymbol, newSymbol, granularity); sideToken = ISideToken(sideTokenAddress); mappedTokens[token] = sideToken; originalTokens[sideTokenAddress] = token; emit NewSideToken(sideTokenAddress, token, newSymbol, granularity); return sideToken; } function verifyWithAllowTokens(address tokenToUse, uint256 amount, bool isASideToken) private { // solium-disable-next-line security/no-block-members if (now > lastDay + 24 hours) { // solium-disable-next-line security/no-block-members lastDay = now; spentToday = 0; } require(allowTokens.isValidTokenTransfer(tokenToUse, amount, spentToday, isASideToken), "Bridge: Bigger than limit"); spentToday = spentToday.add(amount); } function getTransactionId( bytes32 _blockHash, bytes32 _transactionHash, address _receiver, uint256 _amount, uint32 _logIndex ) public pure returns(bytes32) { return keccak256(abi.encodePacked(_blockHash, _transactionHash, _receiver, _amount, _logIndex)); } function _processTransaction( bytes32 _blockHash, bytes32 _transactionHash, address _receiver, uint256 _amount, uint32 _logIndex ) private { bytes32 compiledId = getTransactionId(_blockHash, _transactionHash, _receiver, _amount, _logIndex); require(!processed[compiledId], "Bridge: Already processed"); processed[compiledId] = true; } function setFeePercentage(uint amount) external onlyOwner whenNotPaused { require(amount < (feePercentageDivider/10), "Bridge: bigger than 10%"); feePercentage = amount; emit FeePercentageChanged(feePercentage); } function getFeePercentage() external view returns(uint) { return feePercentage; } function calcMaxWithdraw() external view returns (uint) { uint spent = spentToday; // solium-disable-next-line security/no-block-members if (now > lastDay + 24 hours) spent = 0; return allowTokens.calcMaxWithdraw(spent); } function changeFederation(address newFederation) external onlyOwner returns(bool) { _changeFederation(newFederation); return true; } function _changeFederation(address newFederation) internal { require(newFederation != NULL_ADDRESS, "Bridge: Federation is empty"); federation = newFederation; emit FederationChanged(federation); } function getFederation() external view returns(address) { return federation; } function changeSideTokenFactory(address newSideTokenFactory) external onlyOwner returns(bool) { _changeSideTokenFactory(newSideTokenFactory); return true; } function _changeSideTokenFactory(address newSideTokenFactory) internal { require(newSideTokenFactory != NULL_ADDRESS, "Bridge: SideTokenFactory is empty"); sideTokenFactory = ISideTokenFactory(newSideTokenFactory); emit SideTokenFactoryChanged(newSideTokenFactory); } //This method is only for testnet to erase the Chain Link Token and recreate it with the new version that is ERC677 compatible. //It wont be in the mainnet release function clearSideToken(address originalToken) external onlyOwner returns(bool){ address sideToken = address(mappedTokens[originalToken]); originalTokens[sideToken] = NULL_ADDRESS; mappedTokens[originalToken] = ISideToken(NULL_ADDRESS); return true; } function startUpgrade() external onlyOwner { isUpgrading = true; emit Upgrading(isUpgrading); } function endUpgrade() external onlyOwner { isUpgrading = false; emit Upgrading(isUpgrading); } }
Transfers ownership of the contract to a new account (`newOwner`)./
function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; }
5,452,500
./full_match/5/0xD9228105ec3fBCbeD83706d7e19f88D6FaFd3481/sources/project_/contracts/ERC721LScaffoldV2.sol
Only allow from linking manager These checks are performed by the LinkingManager Backend require( ownerOf(_wearableTokenId) == msg.sender, "ERC721L: You must own the wearable NFT to unlink it from a parent NFT" ); Check if the parent NFT is owned by the msg.sender require( IERC721(parentNFTContractAddress[_wearableTokenId]).ownerOf( _parentTokenId ) == msg.sender, "ERC721L: You must own the parent NFT to unlink it from a wearable NFT" ); Prevent unlinking if the wearable is not linked to the parent NFT
function w_unlink(uint256 _wearableTokenId, uint256 _parentTokenId) public { require( wearableTokenIdToParentTokenId[_wearableTokenId] == _parentTokenId, "ERC721L: The wearable NFT is not linked to the parent NFT" ); isLinked[_wearableTokenId] = false; parentNFTContractAddress[_wearableTokenId] = address(0); wearableTokenIdToParentTokenId[_wearableTokenId] = 0; emit TokenUnlinked(_wearableTokenId, _parentTokenId); }
11,624,023
// SPDX-License-Identifier: Unlicense pragma solidity ^0.8.2; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Base64.sol"; import "./PonziRugsGenerator.sol"; contract PonziRugs is ERC721, Ownable{ // On Tupac's Soul uint256 public MAX_SUPPLY = 1250; uint256 public GET_RUGGED_IN_ETHER = 0.06 ether; uint256 public RUG_GIVEAWAY = 16; uint256 public totalSupply; uint256 RUG_RANDOM_SEED = 0; bool public hasRuggeningStarted = false; mapping(string => bool) isMinted; mapping(uint256 => uint256[]) idToCombination; constructor() ERC721("PonziRugs", "RUG") {} function toggleRuggening() public onlyOwner { hasRuggeningStarted = !hasRuggeningStarted; } function devRug(uint rugs) public onlyOwner { require(totalSupply + rugs <= RUG_GIVEAWAY, "Exceeded giveaway limit"); rugPull(rugs); } function getRugged(uint256 rugs) public payable { require(hasRuggeningStarted, "The ruggening has not started"); require(rugs > 0 && rugs <= 2, "You can only get rugged twice per transaction"); require(GET_RUGGED_IN_ETHER * rugs == msg.value, "Ether Amount invalid to get rugged do: getRuggedInEther * rugs"); rugPull(rugs); } function rugPull(uint256 rugPulls) internal { require(totalSupply + rugPulls < MAX_SUPPLY); require(!PonziRugsGenerator.isTryingToRug(msg.sender)); for (uint256 i; i < rugPulls; i++) { idToCombination[totalSupply] = craftRug(totalSupply); _mint(msg.sender, totalSupply); totalSupply++; } } function craftRug(uint256 tokenId) internal returns (uint256[] memory colorCombination) { uint256[] memory colors = new uint256[](5); colors[0] = random(tokenId) % 1000; for (uint8 i = 1; i < 5; i++) { RUG_RANDOM_SEED++; colors[i] = random(tokenId) % 21; } string memory combination = string(abi.encodePacked(colors[0], colors[1], colors[2], colors[3], colors[4])); if(isMinted[combination]) craftRug(tokenId + 1); isMinted[combination] = true; return colors; } function random(uint256 seed) internal view returns (uint256) { return uint256(keccak256(abi.encodePacked(block.timestamp, block.difficulty, msg.sender, seed, RUG_RANDOM_SEED))); } function tokenURI(uint256 tokenId) override public view returns (string memory) { require(tokenId >= 0 && tokenId <= totalSupply, "Invalid token ID"); PonziRugsGenerator.PonziRugsStruct memory rug; string memory svg; (rug, svg) = PonziRugsGenerator.getRugForSeed(idToCombination[tokenId]); string memory json = Base64.encode(bytes(string(abi.encodePacked( '{"name": "Ponzi Rugs #', Utils.uint2str(tokenId), '", "description": "Ever been rugged before? Good, Now you can do it on chain! No IPFS, no API, all images and metadata exist on the blockchain.",', '"image": "data:image/svg+xml;base64,', Base64.encode(bytes(svg)),'",', rug.metadata,'}' )))); return string(abi.encodePacked('data:application/json;base64,', json)); } function withdrawAll() public payable onlyOwner { require(payable(msg.sender).send(address(this).balance)); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /// @title Base64 /// @author Brecht Devos - <[email protected]> /// @notice Provides functions for encoding/decoding base64 library Base64 { string internal constant TABLE_ENCODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; bytes internal constant TABLE_DECODE = hex"0000000000000000000000000000000000000000000000000000000000000000" hex"00000000000000000000003e0000003f3435363738393a3b3c3d000000000000" hex"00000102030405060708090a0b0c0d0e0f101112131415161718190000000000" hex"001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132330000000000"; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE_ENCODE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { // read 3 bytes dataPtr := add(dataPtr, 3) let input := mload(dataPtr) // write 4 characters mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr( 6, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and( input, 0x3F)))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } function decode(string memory _data) internal pure returns (bytes memory) { bytes memory data = bytes(_data); if (data.length == 0) return new bytes(0); require(data.length % 4 == 0, "invalid base64 decoder input"); // load the table into memory bytes memory table = TABLE_DECODE; // every 4 characters represent 3 bytes uint256 decodedLen = (data.length / 4) * 3; // add some extra buffer at the end required for the writing bytes memory result = new bytes(decodedLen + 32); assembly { // padding with '=' let lastBytes := mload(add(data, mload(data))) if eq(and(lastBytes, 0xFF), 0x3d) { decodedLen := sub(decodedLen, 1) if eq(and(lastBytes, 0xFFFF), 0x3d3d) { decodedLen := sub(decodedLen, 1) } } // set the actual output length mstore(result, decodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 4 characters at a time for {} lt(dataPtr, endPtr) {} { // read 4 characters dataPtr := add(dataPtr, 4) let input := mload(dataPtr) // write 3 bytes let output := add( add( shl(18, and(mload(add(tablePtr, and(shr(24, input), 0xFF))), 0xFF)), shl(12, and(mload(add(tablePtr, and(shr(16, input), 0xFF))), 0xFF))), add( shl( 6, and(mload(add(tablePtr, and(shr( 8, input), 0xFF))), 0xFF)), and(mload(add(tablePtr, and( input , 0xFF))), 0xFF) ) ) mstore(resultPtr, shl(232, output)) resultPtr := add(resultPtr, 3) } } return result; } } //SPDX-License-Identifier: Unlicense /// @title: PonziRugs library /// @author: Rug Dev pragma solidity ^0.8.0; library PonziRugsGenerator { struct PonziRugsStruct { uint pattern; uint background; uint colorOne; uint colorTwo; uint colorThree; bool set; string metadata; string combination; } struct RandValues { uint256 patternSelect; uint256 backgroundSelect; } function getRugForSeed(uint256[] memory combination) external pure returns (PonziRugsStruct memory, string memory) { PonziRugsStruct memory rug; RandValues memory rand; string[10] memory patterns = ["Ether", "Circles", "Hoots", "Kaiju", "Heart", "Persian", "Encore", "Kubrick", "Mozaic", "NGMI"]; string[21] memory colors = ["deeppink", "darkturquoise", "orange", "gold", "white", "silver", "green", "darkviolet", "orangered", "lawngreen", "mediumvioletred", "red", "olivedrab", "bisque", "cornsilk", "darkorange", "slateblue", "floralwhite", "khaki", "crimson", "thistle"]; string[21] memory ngmiPalette = ["black", "red", "green", "blue", "maroon", "violet", "tan", "turquoise", "cyan", "darkred", "darkorange", "crimson", "darkviolet", "goldenrod", "forestgreen", "lime", "magenta", "springgreen", "teal", "navy", "indigo"]; // Determine the Pattern for the rug rand.patternSelect = combination[0]; if(rand.patternSelect < 1) rug.pattern = 9; else if (rand.patternSelect < 60) rug.pattern = 8; else if (rand.patternSelect < 100) rug.pattern = 7; else if (rand.patternSelect < 160) rug.pattern = 6; else if (rand.patternSelect < 240) rug.pattern = 5; else if (rand.patternSelect < 340) rug.pattern = 4; else if (rand.patternSelect < 460) rug.pattern = 3; else if (rand.patternSelect < 580) rug.pattern = 2; else if (rand.patternSelect < 780) rug.pattern = 1; else rug.pattern = 0; // Rug Traits rug.background = combination[1]; rug.colorOne = combination[2]; rug.colorTwo = combination[3]; rug.colorThree = combination[4]; rug.set = (rug.colorOne == rug.colorTwo) && (rug.colorTwo == rug.colorThree); rug.combination = string(abi.encodePacked(Utils.uint2str(rug.pattern), Utils.uint2str(rug.background), Utils.uint2str(rug.colorOne), Utils.uint2str(rug.colorTwo) , Utils.uint2str(rug.colorThree))); // Build the SVG from various parts string memory svg = string(abi.encodePacked('<svg customPattern = "', Utils.uint2str(rug.pattern), '" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 128 55" >')); //svg = string(abi.encodePacked(svg, id)); string memory currentSvg = ""; if(rug.pattern == 0) { //ETHERS currentSvg = string(abi.encodePacked('<pattern id="rug" viewBox="5.5,0,10,10" width="24%" height="20%"><polygon points="-10,-10 -10,30 30,30 30,-10" fill ="', colors[rug.background],'"/><polygon points="0,5 9,1 10,1 10,2 8,4 1,5 8,6 10,8 10,9 9,9 0,5"/><polygon points="10,5 13,1 14,1 21,5 14,9 13,9 10,5"/><polygon points="13.25,2.25 14.5,5 13.25,7.75 11,5" fill="', colors[rug.colorOne],'"/><polygon points="14.5,2.5 15.5,4.5 18.5,4.5" fill="', colors[rug.colorTwo],'"/><polygon points="18.5,5.5 15.5,5.5 14.5,7.5" fill="', colors[rug.colorThree],'"/><polygon points="18.5,5.5 15.5,5.5 14.5,7.5" transform="scale(-1,-1) translate(-35,-15)"/><polygon points="14.5,2.5 15.5,4.5 18.5,4.5" transform="scale(-1,-1) translate(-35,-5)"/><polygon points="13.25,2.25 14.5,5 13.25,7.75 11,5" transform="scale(-1,-1) translate(-35,-15)"/><polygon points="13.25,2.25 14.5,5 13.25,7.75 11,5" transform="scale(-1,-1) translate(-35,-5)"/><polygon points="2,5 10,5 13,9 10,9 8,6" transform="scale(-1,-1) translate(-9,-15)"/><polygon points="2,5 8,4 10,1 13,1 10,5" transform="scale(-1,-1) translate(-9,-5)"/><animate attributeName="x" from="0" to="2.4" dur="20s" repeatCount="indefinite"/></pattern><rect width="128" height="55" fill="url(#rug)" stroke-width="3" stroke="black"/>')); } else if(rug.pattern == 1) { //CIRCLES string[3] memory parts = [ string(abi.encodePacked ( '<pattern id="star" viewBox="0,0,12,12" width="11%" height="25%"><circle cx="12" cy="0" r="4" fill="', colors[rug.colorOne],'" stroke="black" stroke-width="1"/><circle cx="12" cy="0" r="2" fill="', colors[rug.colorThree],'" stroke="black" stroke-width="1"/><circle cx="0" cy="12" r="4" fill="', colors[rug.colorOne],'" stroke="black" stroke-width="1"/><circle cx="0" cy="12" r="2" fill="', colors[rug.colorThree],'" stroke="black" stroke-width="1"/>' )), string(abi.encodePacked ( '<circle cx="6" cy="6" r="6" fill="', colors[rug.colorTwo],'" stroke="black" stroke-width="1"/><circle cx="6" cy="6" r="4" fill="', colors[rug.colorOne],'" stroke="black" stroke-width="1"/><circle cx="6" cy="6" r="2" fill="', colors[rug.background],'" stroke="black" stroke-width="1"/><circle cx="0" cy="0" r="6" fill="', colors[rug.colorTwo],'" stroke="black" stroke-width="1"/><circle cx="0" cy="0" r="4" fill="', colors[rug.colorOne],'" stroke="black" stroke-width="1"/><circle cx="0" cy="0" r="2" fill="', colors[rug.colorThree],'" stroke="black" stroke-width="1"/>' )), string(abi.encodePacked ( '<circle cx="12" cy="12" r="6" fill="', colors[rug.colorTwo],'" stroke="black" stroke-width="1"/><circle cx="12" cy="12" r="4" fill="', colors[rug.colorOne],'" stroke="black" stroke-width="1"/><circle cx="12" cy="12" r="2" fill="', colors[rug.colorThree],'" stroke="black" stroke-width="1"/><animate attributeName="x" from="0" to="1.1" dur="9s" repeatCount="indefinite"/></pattern><rect width="128" height="55" fill="url(#star)" stroke="black" stroke-width="3"/>' )) ]; currentSvg = string(abi.encodePacked(abi.encodePacked(parts[0], parts[1]), parts[2])); } else if(rug.pattern == 2) { //HOOTS string[4] memory parts = [ string(abi.encodePacked ( '<pattern id="e" viewBox="13,-1,10,15" width="15%" height="95%"><polygon points="-99,-99 -99,99 99,99 99,-99" fill ="', colors[rug.background],'"/> <g stroke="black" stroke-width="0.75"><polygon points="5,5 18,10 23,5 18,0" fill ="', colors[rug.colorTwo],'"/><polygon points="21,0 26,5 21,10 33,5" fill ="', colors[rug.colorThree],'"/> </g><animate attributeName="x" from="0" to="0.3" dur="2.5s" repeatCount="indefinite"/> </pattern>' )), string(abi.encodePacked ( '<pattern id="h" viewBox="10,0,20,25" width="15%" height="107%"><polygon points="-99,-99 -99,99 99,99 99,-99" fill ="', colors[rug.background],'"/><polygon points="9,4 14,9 14,18 9,23 26,23 31,18 31,9 26,4" fill ="', colors[rug.colorOne],'" stroke="black" stroke-width="1"/><g fill ="', colors[rug.background],'" stroke="black" stroke-width="0.5"><circle cx="20" cy="10" r="2.5"/><circle cx="20" cy="17" r="2.5"/><polygon points="24,11 24,16 29,13.5"/></g><circle cx="20" cy="10" r="1.75" fill="black"/><circle cx="20" cy="17" r="1.75" fill="black"/>' )), string(abi.encodePacked ( '<animate attributeName="x" from="0" to="0.6" dur="5s" repeatCount="indefinite"/></pattern><pattern id="c" viewBox="13,4,10,20" width="15%" height="135%"><polygon points="-99,-99 -99,99 99,99 99,-99" fill="', colors[rug.background],'"/><polygon points="7,3 7,18 32,18 32,3" fill="black"/><polygon points="11,7 11,15 28,15 28,7" fill="', colors[rug.background],'"/><g fill="black" stroke="', colors[rug.background],'" stroke-width="1">' )), string(abi.encodePacked ( '<polygon points="-3,9 -3,13 16,13 16,9"/><polygon points="23,9 23,13 41,13 41,9"/></g><animate attributeName="x" from="2.4" to="0" dur="40s" repeatCount="indefinite"/></pattern><rect width="128" height="55" fill="', colors[rug.background],'"/><rect x="0" y="2" width="128" height="9" fill="url(#e)"/><rect x="0" y="10" width="128" height="9" fill="url(#c)"/><rect x="0" y="19" width="128" height="15" fill="url(#h)"/><rect x="0" y="36.5" width="128" height="9" fill="url(#c)"/><rect x="0" y="46.25" width="128" height="9" fill="url(#e)"/><rect width="128" height="55" fill="transparent" stroke="black" stroke-width="3"/>' )) ]; currentSvg = string(abi.encodePacked(abi.encodePacked(parts[0], parts[1]), parts[2], parts[3])); } else if(rug.pattern == 3) { //SCALES string[3] memory parts = [ string(abi.encodePacked ( '<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%"><stop offset="0%" stop-color="', colors[rug.background],'"/><stop offset="100%" stop-color="', colors[rug.colorOne],'"/></linearGradient>' )), string(abi.encodePacked ( '<pattern id="R" viewBox="0 0 16 16" width="11.4%" height="25%"><g fill="url(#grad1)" stroke-width="1" stroke="black"><polygon points="8,-2 26,-2 26,18 8,18"/><circle cx="8" cy="8" r="8"/><circle cx="0" cy="0" r="8"/><circle cx="0" cy="16" r="8"/><circle cx="8" cy="8" r="3" fill="', colors[rug.colorThree],'"/><circle cx="0" cy="0" r="3" fill="', colors[rug.colorTwo],'"/><circle cx="0" cy="16" r="3" fill="', colors[rug.colorTwo],'"/><circle cx="17" cy="0" r="3" fill="', colors[rug.colorTwo],'"/>' )), string(abi.encodePacked( '<circle cx="17" cy="16" r="3" fill="', colors[rug.colorTwo],'"/></g><animate attributeName="x" from="0" to="0.798" dur="6.6s" repeatCount="indefinite"/></pattern><rect width="128" height="55" fill="url(#R)" stroke-width="3" stroke="black"/>' )) ]; currentSvg = string(abi.encodePacked(abi.encodePacked(parts[0], parts[1]), parts[2])); } else if(rug.pattern == 4) { //HEART currentSvg = string(abi.encodePacked('<pattern id="star" viewBox="5.5,-50,100,100" width="25%" height="25%"><g stroke="black" stroke-width="2"><polygon points="-99,-99 -99,99 999,99 999,-99" fill ="', colors[rug.background],'"/> <polygon points="0,-50 -60,-15.36 -60,-84.64" fill="', colors[rug.colorOne],'"/><polygon points="0,50 -60,84.64 -60,15.36" fill="', colors[rug.colorOne],'"/><circle cx="120" cy="0" r="30" fill ="', colors[rug.colorTwo],'" /><path fill="', colors[rug.colorThree],'" id="star" d="M0,0 C37.5,62.5 75,25 50,0 C75,-25 37.5,-62.5 0,0 z"/></g><g transform="translate(0,40)" id="star"></g><animate attributeName="x" from="0" to="0.5" dur="4.1s" repeatCount="indefinite"/></pattern><rect width="128" height="55" fill="url(#star)" stroke="black" stroke-width="3"/>')); } else if(rug.pattern == 5) { //SQUARES string[2] memory parts = [ string(abi.encodePacked ( '<pattern id="moon" viewBox="0,-0.5,10,10" width="100%" height="100%"><rect width="10" height="10" fill="', colors[rug.colorOne],'" stroke="black" stroke-width="2" transform="translate(0.05,-0.5)"/><rect width="5" height="5" stroke="', colors[rug.colorTwo],'" fill="', colors[rug.colorOne],'" transform="translate(2.5,2)"/><rect width="4" height="4" stroke="black" fill="', colors[rug.colorOne],'" transform="translate(3,2.5)" stroke-width="0.3"/>' )), string(abi.encodePacked ( '<rect width="6" height="6" stroke="black" fill="none" transform="translate(2,1.5)" stroke-width="0.3"/><circle cx="5" cy="4.5" r="1" stroke="', colors[rug.colorTwo],'" fill="', colors[rug.colorThree],'"/><g stroke="black" stroke-width="0.3" fill="none"><circle cx="5" cy="4.5" r="1.5"/><circle cx="5" cy="4.5" r="0.5"/> </g></pattern><pattern id="star" viewBox="7,-0.5,7,10" width="17%" height="20%"><g fill="url(#moon)" stroke="', colors[rug.background],'"><rect width="10" height="10" transform="translate(0,-0.5)"/><rect width="10" height="10" transform="translate(10,4.5)"/><rect width="10" height="10" transform="translate(10,-5.5)"/></g><animate attributeName="x" from="0" to="0.17" dur="1.43s" repeatCount="indefinite"/></pattern><rect width="128" height="55" fill="url(#star)" stroke-width="3" stroke="black"/>' )) ]; currentSvg = string(abi.encodePacked(abi.encodePacked(parts[0], parts[1]))); } else if(rug.pattern == 6) { //ENCORE string[3] memory parts = [ string(abi.encodePacked ( '<radialGradient id="a" x1="0%" y1="0%" x2="100%" y2="0%"><stop offset="0%" stop-color="', colors[rug.background],'" stop-opacity="1" /><stop offset="100%" stop-color="', colors[rug.colorOne],'" stop-opacity="1" /></radialGradient><radialGradient id="b" x1="0%" y1="0%" x2="100%" y2="0%"><stop offset="0%" stop-color="', colors[rug.colorTwo],'" stop-opacity="1" /><stop offset="100%" stop-color="', colors[rug.colorThree],'" stop-opacity="1" /></radialGradient>' )), string(abi.encodePacked ( '<pattern id="R" viewBox="0 0 16 16" width="13.42%" height="33%"><g stroke-width="1" stroke="black" fill="url(#a)"><circle cx="16" cy="16" r="8"/><circle cx="16" cy="14.9" r="6"/><circle cx="16" cy="13" r="4"/><circle cx="16" cy="12" r="2"/><circle cx="0" cy="16" r="8"/><circle cx="0" cy="14.9" r="6"/><circle cx="0" cy="13" r="4"/><circle cx="0" cy="12" r="2"/><circle cx="8" cy="8" r="8" fill="url(#b)"/><circle cx="8" cy="6.5" r="6" fill="url(#b)"/><circle cx="8" cy="5" r="4" fill="url(#b)"/><circle cx="8" cy="4" r="2" fill="url(#b)"/><circle cx="16" cy="0" r="8"/><circle cx="16" cy="-2" r="6"/>' )), string(abi.encodePacked ( '<circle cx="16" cy="-3.9" r="4"/><circle cx="0" cy="0" r="8"/><circle cx="0" cy="-2" r="6"/><circle cx="0" cy="-3.9" r="4"/></g><animate attributeName="x" from="0" to="0.4025" dur="3.35s" repeatCount="indefinite"/></pattern><rect width="128" height="55" fill="url(#R)" stroke-width="3" stroke="black"/>' )) ]; currentSvg = string(abi.encodePacked(abi.encodePacked(parts[0], parts[1]), parts[2])); } else if(rug.pattern == 7) { //Kubrik string[3] memory parts = [ string(abi.encodePacked ( '<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%"><stop offset="0%" stop-color="', colors[rug.colorOne],'" stop-opacity="1" /><stop offset="100%" stop-color="', colors[rug.colorTwo],'" stop-opacity="1" /></linearGradient><polygon points="0,0 0,55 128,55 128,0" fill ="url(#grad1)"/> <pattern id="star" viewBox="5,-2.9,16,16" width="12%" height="20%">' )), string(abi.encodePacked ( '<polygon points="13,6 10.5,10 5.5,10 2.5,5 5.5,0 10.5,0 13,4 21,4 26,-5 28,-5 22.5,5 29,17 27,17 21,6" fill="', colors[rug.background],'" stroke="black" stroke-width="0.3"/> <polygon points="5,0 10,0 13,5 10,10 5,10 2,5" fill="', colors[rug.colorThree],'" stroke="black" stroke-width="0.6" transform="translate(4.3 2.5) scale(0.5 0.5)"/> <polygon points="21,6 12.5,6 10,10 5,10 2,5 5,0 10,0 12.5,4 20.5,4 25.5,-5 28,-5 22,5" transform="translate(24.5 8) scale(-1,1)" fill="', colors[rug.background],'" stroke="black" stroke-width="0.3"/>' )), string(abi.encodePacked ( '<polygon points="5,0 10,0 13,5 10,10 5,10 2,5" fill="', colors[rug.colorThree],'" stroke="black" stroke-width="0.6" transform="translate(13.3 10.5) scale(0.5 0.5)"/> <polygon points="20.5,6 12.5,6 10,10 5,10 2,5 5,0 10,0 12.5,4 21,4 22,5 28,17 26.5,17" transform="translate(24.5 -8) scale(-1,1)" fill="', colors[rug.background],'" stroke="black" stroke-width="0.3"/> <polygon points="5,0 10,0 13,5 10,10 5,10 2,5" fill="', colors[rug.colorThree],'" stroke="black" stroke-width="0.6" transform="translate(13.3 -5.5) scale(0.5 0.5)"/> <animate attributeName="x" from="0" to="1.2" dur="9.8s" repeatCount="indefinite"/> </pattern><rect width="128" height="55" fill="url(#star)" stroke="black" stroke-width="3"/>' )) ]; currentSvg = string(abi.encodePacked(abi.encodePacked(parts[0], parts[1]), parts[2])); } else if(rug.pattern == 8) { //TRIANGLES string[2] memory parts = [ string(abi.encodePacked ( '<polygon points="0,0 128,0 128,55 0,55" fill="', colors[rug.background],'"/><pattern id="R" viewBox="0 0 20 24" width="11.8%" height="33%"><g stroke-width="0.3" stroke="black"><polygon points="0,24 10,18 10,30" fill="', colors[rug.colorOne],'"/><polygon points="0,0 10,6 10,-6" fill="', colors[rug.colorOne],'"/><polygon points="10,6 20,12 20,0" fill="', colors[rug.colorTwo],'"/>' )), string(abi.encodePacked ( '<polygon points="3,6 13,12 3,18" fill="', colors[rug.colorThree],'"/><polygon points="-7,12 3,18 -7,24" fill="', colors[rug.colorOne],'"/><polygon points="23,18 13,24 13,12" fill="', colors[rug.colorOne],'"/></g><animate attributeName="x" from="0" to="0.7085" dur="5.9s" repeatCount="indefinite"/></pattern><rect width="128" height="55" fill="url(#R)" stroke-width="3" stroke="black"/>' )) ]; currentSvg = string(abi.encodePacked(abi.encodePacked(parts[0], parts[1]))); } else if(rug.pattern == 9) { rug.background = combination[1]; rug.colorOne = combination[2]; rug.colorTwo = combination[3]; rug.colorThree = combination[4]; rug.set = (rug.colorOne == rug.colorTwo) && (rug.colorTwo == rug.colorThree); rug.combination = string(abi.encodePacked(Utils.uint2str(rug.pattern), Utils.uint2str(rug.background), Utils.uint2str(rug.colorOne), Utils.uint2str(rug.colorTwo) , Utils.uint2str(rug.colorThree))); string[1] memory parts = [ string(abi.encodePacked ( '<pattern id="star" viewBox="5.5,-50,100,100" width="40%" height="50%"><polygon points="-100,-100 -100,300 300,300 300,-100" fill="white"/> <polyline points="11 1,7 1,7 5,11 5,11 3, 10 3" fill="none" stroke="', ngmiPalette[rug.background],'"/><polyline points="1 5,1 1,5 5,5 1" fill="none" stroke="', ngmiPalette[rug.colorOne],'"/><polyline points="13 5,13 1,15 3,17 1, 17 5" fill="none" stroke="', ngmiPalette[rug.colorTwo],'"/><polyline points="19 1, 23 1, 21 1, 21 5, 19 5, 23 5" fill="none" stroke="', ngmiPalette[rug.colorThree],'"/><animate attributeName="x" from="0" to="0.4" dur="3s" repeatCount="indefinite"/> </pattern> <rect width="128" height="55" fill="url(#star)" stroke="black" stroke-width="3"/>' )) ]; currentSvg = string(abi.encodePacked(abi.encodePacked(parts[0]))); } svg = string(abi.encodePacked(svg, currentSvg)); svg = string(abi.encodePacked(svg, '</svg>')); // Keep track of each pn So we can add a trait for each color string memory traits = string(abi.encodePacked('"attributes": [{"trait_type": "Pattern","value":"', patterns[rug.pattern],'"},')); if(rug.set) traits = string(abi.encodePacked(traits, string(abi.encodePacked('{"trait_type": "Set","value":"True"},')))); string memory traits2 = string(abi.encodePacked('{"trait_type": "Background","value":"', colors[rug.background],'"},{"trait_type": "Color One","value": "', colors[rug.colorOne],'"},{"trait_type": "Color Two","value": "', colors[rug.colorTwo],'"},{"trait_type": "Color Three","value": "', colors[rug.colorThree],'"}]')); string memory allTraits = string(abi.encodePacked(traits,traits2)); rug.metadata = allTraits; return (rug, svg); } function isTryingToRug(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } } library Utils { function uint2str(uint256 _i) internal pure returns (string memory str) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 length; while (j != 0) { length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length; j = _i; while (j != 0) { bstr[--k] = bytes1(uint8(48 + j % 10)); j /= 10; } str = string(bstr); return str; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Determine the Pattern for the rug Rug Traits Build the SVG from various partssvg = string(abi.encodePacked(svg, id));ETHERSCIRCLESHOOTSSCALESHEARTSQUARESENCOREKubrikTRIANGLES
function getRugForSeed(uint256[] memory combination) external pure returns (PonziRugsStruct memory, string memory) { PonziRugsStruct memory rug; RandValues memory rand; string[10] memory patterns = ["Ether", "Circles", "Hoots", "Kaiju", "Heart", "Persian", "Encore", "Kubrick", "Mozaic", "NGMI"]; string[21] memory colors = ["deeppink", "darkturquoise", "orange", "gold", "white", "silver", "green", "darkviolet", "orangered", "lawngreen", "mediumvioletred", "red", "olivedrab", "bisque", "cornsilk", "darkorange", "slateblue", "floralwhite", "khaki", "crimson", "thistle"]; string[21] memory ngmiPalette = ["black", "red", "green", "blue", "maroon", "violet", "tan", "turquoise", "cyan", "darkred", "darkorange", "crimson", "darkviolet", "goldenrod", "forestgreen", "lime", "magenta", "springgreen", "teal", "navy", "indigo"]; rand.patternSelect = combination[0]; if(rand.patternSelect < 1) rug.pattern = 9; else if (rand.patternSelect < 60) rug.pattern = 8; else if (rand.patternSelect < 100) rug.pattern = 7; else if (rand.patternSelect < 160) rug.pattern = 6; else if (rand.patternSelect < 240) rug.pattern = 5; else if (rand.patternSelect < 340) rug.pattern = 4; else if (rand.patternSelect < 460) rug.pattern = 3; else if (rand.patternSelect < 580) rug.pattern = 2; else if (rand.patternSelect < 780) rug.pattern = 1; else rug.pattern = 0; rug.background = combination[1]; rug.colorOne = combination[2]; rug.colorTwo = combination[3]; rug.colorThree = combination[4]; rug.set = (rug.colorOne == rug.colorTwo) && (rug.colorTwo == rug.colorThree); rug.combination = string(abi.encodePacked(Utils.uint2str(rug.pattern), Utils.uint2str(rug.background), Utils.uint2str(rug.colorOne), Utils.uint2str(rug.colorTwo) , Utils.uint2str(rug.colorThree))); string memory currentSvg = ""; if(rug.pattern == 0) { currentSvg = string(abi.encodePacked('<pattern id="rug" viewBox="5.5,0,10,10" width="24%" height="20%"><polygon points="-10,-10 -10,30 30,30 30,-10" fill ="', colors[rug.background],'"/><polygon points="0,5 9,1 10,1 10,2 8,4 1,5 8,6 10,8 10,9 9,9 0,5"/><polygon points="10,5 13,1 14,1 21,5 14,9 13,9 10,5"/><polygon points="13.25,2.25 14.5,5 13.25,7.75 11,5" fill="', colors[rug.colorOne],'"/><polygon points="14.5,2.5 15.5,4.5 18.5,4.5" fill="', colors[rug.colorTwo],'"/><polygon points="18.5,5.5 15.5,5.5 14.5,7.5" fill="', colors[rug.colorThree],'"/><polygon points="18.5,5.5 15.5,5.5 14.5,7.5" transform="scale(-1,-1) translate(-35,-15)"/><polygon points="14.5,2.5 15.5,4.5 18.5,4.5" transform="scale(-1,-1) translate(-35,-5)"/><polygon points="13.25,2.25 14.5,5 13.25,7.75 11,5" transform="scale(-1,-1) translate(-35,-15)"/><polygon points="13.25,2.25 14.5,5 13.25,7.75 11,5" transform="scale(-1,-1) translate(-35,-5)"/><polygon points="2,5 10,5 13,9 10,9 8,6" transform="scale(-1,-1) translate(-9,-15)"/><polygon points="2,5 8,4 10,1 13,1 10,5" transform="scale(-1,-1) translate(-9,-5)"/><animate attributeName="x" from="0" to="2.4" dur="20s" repeatCount="indefinite"/></pattern><rect width="128" height="55" fill="url(#rug)" stroke-width="3" stroke="black"/>')); } else if(rug.pattern == 1) { string[3] memory parts = [ string(abi.encodePacked ( '<pattern id="star" viewBox="0,0,12,12" width="11%" height="25%"><circle cx="12" cy="0" r="4" fill="', colors[rug.colorOne],'" stroke="black" stroke-width="1"/><circle cx="12" cy="0" r="2" fill="', colors[rug.colorThree],'" stroke="black" stroke-width="1"/><circle cx="0" cy="12" r="4" fill="', colors[rug.colorOne],'" stroke="black" stroke-width="1"/><circle cx="0" cy="12" r="2" fill="', colors[rug.colorThree],'" stroke="black" stroke-width="1"/>' )), string(abi.encodePacked ( '<circle cx="6" cy="6" r="6" fill="', colors[rug.colorTwo],'" stroke="black" stroke-width="1"/><circle cx="6" cy="6" r="4" fill="', colors[rug.colorOne],'" stroke="black" stroke-width="1"/><circle cx="6" cy="6" r="2" fill="', colors[rug.background],'" stroke="black" stroke-width="1"/><circle cx="0" cy="0" r="6" fill="', colors[rug.colorTwo],'" stroke="black" stroke-width="1"/><circle cx="0" cy="0" r="4" fill="', colors[rug.colorOne],'" stroke="black" stroke-width="1"/><circle cx="0" cy="0" r="2" fill="', colors[rug.colorThree],'" stroke="black" stroke-width="1"/>' )), string(abi.encodePacked ( '<circle cx="12" cy="12" r="6" fill="', colors[rug.colorTwo],'" stroke="black" stroke-width="1"/><circle cx="12" cy="12" r="4" fill="', colors[rug.colorOne],'" stroke="black" stroke-width="1"/><circle cx="12" cy="12" r="2" fill="', colors[rug.colorThree],'" stroke="black" stroke-width="1"/><animate attributeName="x" from="0" to="1.1" dur="9s" repeatCount="indefinite"/></pattern><rect width="128" height="55" fill="url(#star)" stroke="black" stroke-width="3"/>' )) ]; currentSvg = string(abi.encodePacked(abi.encodePacked(parts[0], parts[1]), parts[2])); } else if(rug.pattern == 2) { string[4] memory parts = [ string(abi.encodePacked ( '<pattern id="e" viewBox="13,-1,10,15" width="15%" height="95%"><polygon points="-99,-99 -99,99 99,99 99,-99" fill ="', colors[rug.background],'"/> <g stroke="black" stroke-width="0.75"><polygon points="5,5 18,10 23,5 18,0" fill ="', colors[rug.colorTwo],'"/><polygon points="21,0 26,5 21,10 33,5" fill ="', colors[rug.colorThree],'"/> </g><animate attributeName="x" from="0" to="0.3" dur="2.5s" repeatCount="indefinite"/> </pattern>' )), string(abi.encodePacked ( '<pattern id="h" viewBox="10,0,20,25" width="15%" height="107%"><polygon points="-99,-99 -99,99 99,99 99,-99" fill ="', colors[rug.background],'"/><polygon points="9,4 14,9 14,18 9,23 26,23 31,18 31,9 26,4" fill ="', colors[rug.colorOne],'" stroke="black" stroke-width="1"/><g fill ="', colors[rug.background],'" stroke="black" stroke-width="0.5"><circle cx="20" cy="10" r="2.5"/><circle cx="20" cy="17" r="2.5"/><polygon points="24,11 24,16 29,13.5"/></g><circle cx="20" cy="10" r="1.75" fill="black"/><circle cx="20" cy="17" r="1.75" fill="black"/>' )), string(abi.encodePacked ( '<animate attributeName="x" from="0" to="0.6" dur="5s" repeatCount="indefinite"/></pattern><pattern id="c" viewBox="13,4,10,20" width="15%" height="135%"><polygon points="-99,-99 -99,99 99,99 99,-99" fill="', colors[rug.background],'"/><polygon points="7,3 7,18 32,18 32,3" fill="black"/><polygon points="11,7 11,15 28,15 28,7" fill="', colors[rug.background],'"/><g fill="black" stroke="', colors[rug.background],'" stroke-width="1">' )), string(abi.encodePacked ( '<polygon points="-3,9 -3,13 16,13 16,9"/><polygon points="23,9 23,13 41,13 41,9"/></g><animate attributeName="x" from="2.4" to="0" dur="40s" repeatCount="indefinite"/></pattern><rect width="128" height="55" fill="', colors[rug.background],'"/><rect x="0" y="2" width="128" height="9" fill="url(#e)"/><rect x="0" y="10" width="128" height="9" fill="url(#c)"/><rect x="0" y="19" width="128" height="15" fill="url(#h)"/><rect x="0" y="36.5" width="128" height="9" fill="url(#c)"/><rect x="0" y="46.25" width="128" height="9" fill="url(#e)"/><rect width="128" height="55" fill="transparent" stroke="black" stroke-width="3"/>' )) ]; currentSvg = string(abi.encodePacked(abi.encodePacked(parts[0], parts[1]), parts[2], parts[3])); } else if(rug.pattern == 3) { string[3] memory parts = [ string(abi.encodePacked ( '<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%"><stop offset="0%" stop-color="', colors[rug.background],'"/><stop offset="100%" stop-color="', colors[rug.colorOne],'"/></linearGradient>' )), string(abi.encodePacked ( '<pattern id="R" viewBox="0 0 16 16" width="11.4%" height="25%"><g fill="url(#grad1)" stroke-width="1" stroke="black"><polygon points="8,-2 26,-2 26,18 8,18"/><circle cx="8" cy="8" r="8"/><circle cx="0" cy="0" r="8"/><circle cx="0" cy="16" r="8"/><circle cx="8" cy="8" r="3" fill="', colors[rug.colorThree],'"/><circle cx="0" cy="0" r="3" fill="', colors[rug.colorTwo],'"/><circle cx="0" cy="16" r="3" fill="', colors[rug.colorTwo],'"/><circle cx="17" cy="0" r="3" fill="', colors[rug.colorTwo],'"/>' )), string(abi.encodePacked( '<circle cx="17" cy="16" r="3" fill="', colors[rug.colorTwo],'"/></g><animate attributeName="x" from="0" to="0.798" dur="6.6s" repeatCount="indefinite"/></pattern><rect width="128" height="55" fill="url(#R)" stroke-width="3" stroke="black"/>' )) ]; currentSvg = string(abi.encodePacked(abi.encodePacked(parts[0], parts[1]), parts[2])); } else if(rug.pattern == 4) { currentSvg = string(abi.encodePacked('<pattern id="star" viewBox="5.5,-50,100,100" width="25%" height="25%"><g stroke="black" stroke-width="2"><polygon points="-99,-99 -99,99 999,99 999,-99" fill ="', colors[rug.background],'"/> <polygon points="0,-50 -60,-15.36 -60,-84.64" fill="', colors[rug.colorOne],'"/><polygon points="0,50 -60,84.64 -60,15.36" fill="', colors[rug.colorOne],'"/><circle cx="120" cy="0" r="30" fill ="', colors[rug.colorTwo],'" /><path fill="', colors[rug.colorThree],'" id="star" d="M0,0 C37.5,62.5 75,25 50,0 C75,-25 37.5,-62.5 0,0 z"/></g><g transform="translate(0,40)" id="star"></g><animate attributeName="x" from="0" to="0.5" dur="4.1s" repeatCount="indefinite"/></pattern><rect width="128" height="55" fill="url(#star)" stroke="black" stroke-width="3"/>')); } else if(rug.pattern == 5) { string[2] memory parts = [ string(abi.encodePacked ( '<pattern id="moon" viewBox="0,-0.5,10,10" width="100%" height="100%"><rect width="10" height="10" fill="', colors[rug.colorOne],'" stroke="black" stroke-width="2" transform="translate(0.05,-0.5)"/><rect width="5" height="5" stroke="', colors[rug.colorTwo],'" fill="', colors[rug.colorOne],'" transform="translate(2.5,2)"/><rect width="4" height="4" stroke="black" fill="', colors[rug.colorOne],'" transform="translate(3,2.5)" stroke-width="0.3"/>' )), string(abi.encodePacked ( '<rect width="6" height="6" stroke="black" fill="none" transform="translate(2,1.5)" stroke-width="0.3"/><circle cx="5" cy="4.5" r="1" stroke="', colors[rug.colorTwo],'" fill="', colors[rug.colorThree],'"/><g stroke="black" stroke-width="0.3" fill="none"><circle cx="5" cy="4.5" r="1.5"/><circle cx="5" cy="4.5" r="0.5"/> </g></pattern><pattern id="star" viewBox="7,-0.5,7,10" width="17%" height="20%"><g fill="url(#moon)" stroke="', colors[rug.background],'"><rect width="10" height="10" transform="translate(0,-0.5)"/><rect width="10" height="10" transform="translate(10,4.5)"/><rect width="10" height="10" transform="translate(10,-5.5)"/></g><animate attributeName="x" from="0" to="0.17" dur="1.43s" repeatCount="indefinite"/></pattern><rect width="128" height="55" fill="url(#star)" stroke-width="3" stroke="black"/>' )) ]; currentSvg = string(abi.encodePacked(abi.encodePacked(parts[0], parts[1]))); } else if(rug.pattern == 6) { string[3] memory parts = [ string(abi.encodePacked ( '<radialGradient id="a" x1="0%" y1="0%" x2="100%" y2="0%"><stop offset="0%" stop-color="', colors[rug.background],'" stop-opacity="1" /><stop offset="100%" stop-color="', colors[rug.colorOne],'" stop-opacity="1" /></radialGradient><radialGradient id="b" x1="0%" y1="0%" x2="100%" y2="0%"><stop offset="0%" stop-color="', colors[rug.colorTwo],'" stop-opacity="1" /><stop offset="100%" stop-color="', colors[rug.colorThree],'" stop-opacity="1" /></radialGradient>' )), string(abi.encodePacked ( '<pattern id="R" viewBox="0 0 16 16" width="13.42%" height="33%"><g stroke-width="1" stroke="black" fill="url(#a)"><circle cx="16" cy="16" r="8"/><circle cx="16" cy="14.9" r="6"/><circle cx="16" cy="13" r="4"/><circle cx="16" cy="12" r="2"/><circle cx="0" cy="16" r="8"/><circle cx="0" cy="14.9" r="6"/><circle cx="0" cy="13" r="4"/><circle cx="0" cy="12" r="2"/><circle cx="8" cy="8" r="8" fill="url(#b)"/><circle cx="8" cy="6.5" r="6" fill="url(#b)"/><circle cx="8" cy="5" r="4" fill="url(#b)"/><circle cx="8" cy="4" r="2" fill="url(#b)"/><circle cx="16" cy="0" r="8"/><circle cx="16" cy="-2" r="6"/>' )), string(abi.encodePacked ( '<circle cx="16" cy="-3.9" r="4"/><circle cx="0" cy="0" r="8"/><circle cx="0" cy="-2" r="6"/><circle cx="0" cy="-3.9" r="4"/></g><animate attributeName="x" from="0" to="0.4025" dur="3.35s" repeatCount="indefinite"/></pattern><rect width="128" height="55" fill="url(#R)" stroke-width="3" stroke="black"/>' )) ]; currentSvg = string(abi.encodePacked(abi.encodePacked(parts[0], parts[1]), parts[2])); } else if(rug.pattern == 7) { string[3] memory parts = [ string(abi.encodePacked ( '<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%"><stop offset="0%" stop-color="', colors[rug.colorOne],'" stop-opacity="1" /><stop offset="100%" stop-color="', colors[rug.colorTwo],'" stop-opacity="1" /></linearGradient><polygon points="0,0 0,55 128,55 128,0" fill ="url(#grad1)"/> <pattern id="star" viewBox="5,-2.9,16,16" width="12%" height="20%">' )), string(abi.encodePacked ( '<polygon points="13,6 10.5,10 5.5,10 2.5,5 5.5,0 10.5,0 13,4 21,4 26,-5 28,-5 22.5,5 29,17 27,17 21,6" fill="', colors[rug.background],'" stroke="black" stroke-width="0.3"/> <polygon points="5,0 10,0 13,5 10,10 5,10 2,5" fill="', colors[rug.colorThree],'" stroke="black" stroke-width="0.6" transform="translate(4.3 2.5) scale(0.5 0.5)"/> <polygon points="21,6 12.5,6 10,10 5,10 2,5 5,0 10,0 12.5,4 20.5,4 25.5,-5 28,-5 22,5" transform="translate(24.5 8) scale(-1,1)" fill="', colors[rug.background],'" stroke="black" stroke-width="0.3"/>' )), string(abi.encodePacked ( '<polygon points="5,0 10,0 13,5 10,10 5,10 2,5" fill="', colors[rug.colorThree],'" stroke="black" stroke-width="0.6" transform="translate(13.3 10.5) scale(0.5 0.5)"/> <polygon points="20.5,6 12.5,6 10,10 5,10 2,5 5,0 10,0 12.5,4 21,4 22,5 28,17 26.5,17" transform="translate(24.5 -8) scale(-1,1)" fill="', colors[rug.background],'" stroke="black" stroke-width="0.3"/> <polygon points="5,0 10,0 13,5 10,10 5,10 2,5" fill="', colors[rug.colorThree],'" stroke="black" stroke-width="0.6" transform="translate(13.3 -5.5) scale(0.5 0.5)"/> <animate attributeName="x" from="0" to="1.2" dur="9.8s" repeatCount="indefinite"/> </pattern><rect width="128" height="55" fill="url(#star)" stroke="black" stroke-width="3"/>' )) ]; currentSvg = string(abi.encodePacked(abi.encodePacked(parts[0], parts[1]), parts[2])); } else if(rug.pattern == 8) { string[2] memory parts = [ string(abi.encodePacked ( '<polygon points="0,0 128,0 128,55 0,55" fill="', colors[rug.background],'"/><pattern id="R" viewBox="0 0 20 24" width="11.8%" height="33%"><g stroke-width="0.3" stroke="black"><polygon points="0,24 10,18 10,30" fill="', colors[rug.colorOne],'"/><polygon points="0,0 10,6 10,-6" fill="', colors[rug.colorOne],'"/><polygon points="10,6 20,12 20,0" fill="', colors[rug.colorTwo],'"/>' )), string(abi.encodePacked ( '<polygon points="3,6 13,12 3,18" fill="', colors[rug.colorThree],'"/><polygon points="-7,12 3,18 -7,24" fill="', colors[rug.colorOne],'"/><polygon points="23,18 13,24 13,12" fill="', colors[rug.colorOne],'"/></g><animate attributeName="x" from="0" to="0.7085" dur="5.9s" repeatCount="indefinite"/></pattern><rect width="128" height="55" fill="url(#R)" stroke-width="3" stroke="black"/>' )) ]; currentSvg = string(abi.encodePacked(abi.encodePacked(parts[0], parts[1]))); } else if(rug.pattern == 9) { rug.background = combination[1]; rug.colorOne = combination[2]; rug.colorTwo = combination[3]; rug.colorThree = combination[4]; rug.set = (rug.colorOne == rug.colorTwo) && (rug.colorTwo == rug.colorThree); rug.combination = string(abi.encodePacked(Utils.uint2str(rug.pattern), Utils.uint2str(rug.background), Utils.uint2str(rug.colorOne), Utils.uint2str(rug.colorTwo) , Utils.uint2str(rug.colorThree))); string[1] memory parts = [ string(abi.encodePacked ( '<pattern id="star" viewBox="5.5,-50,100,100" width="40%" height="50%"><polygon points="-100,-100 -100,300 300,300 300,-100" fill="white"/> <polyline points="11 1,7 1,7 5,11 5,11 3, 10 3" fill="none" stroke="', ngmiPalette[rug.background],'"/><polyline points="1 5,1 1,5 5,5 1" fill="none" stroke="', ngmiPalette[rug.colorOne],'"/><polyline points="13 5,13 1,15 3,17 1, 17 5" fill="none" stroke="', ngmiPalette[rug.colorTwo],'"/><polyline points="19 1, 23 1, 21 1, 21 5, 19 5, 23 5" fill="none" stroke="', ngmiPalette[rug.colorThree],'"/><animate attributeName="x" from="0" to="0.4" dur="3s" repeatCount="indefinite"/> </pattern> <rect width="128" height="55" fill="url(#star)" stroke="black" stroke-width="3"/>' )) ]; currentSvg = string(abi.encodePacked(abi.encodePacked(parts[0]))); } svg = string(abi.encodePacked(svg, currentSvg)); svg = string(abi.encodePacked(svg, '</svg>')); if(rug.set) string memory allTraits = string(abi.encodePacked(traits,traits2)); rug.metadata = allTraits; return (rug, svg); }
340,608
./full_match/97/0xF7Df059F5bCFe50A458cCF459fb99EFd20eF7400/sources/project_/contracts/strf-token-staker/STRFStaker.sol
Sets a new time for the contract lock durration. Admin accessible function used to reassign the lock duration variable. _lockDuration New time for the token locking period (in seconds)./
function setLockDuration( uint256 _lockDuration ) external onlyRole(DEFAULT_ADMIN_ROLE) { lockDuration = _lockDuration; emit SetLockDuration(_lockDuration); }
3,275,295
pragma solidity ^0.6.0; import "../side-entrance/SideEntranceLenderPool.sol"; contract Switcharoo is IFlashLoanEtherReceiver { SideEntranceLenderPool private pool; receive() external payable {} constructor(address payable poolAddress) public { pool = SideEntranceLenderPool(poolAddress); } function steal(uint256 amount) external { pool.flashLoan(amount); // after flashloan is complete // widthdraw and transfer to the attacker pool.withdraw(); msg.sender.send(amount); } // this will be called by the pool during flashLoan() function execute() external override payable { // deposit recieved flash loan back into pool // this passes the desposit retuned check pool.deposit{value: msg.value}(); } }
after flashloan is complete widthdraw and transfer to the attacker
function steal(uint256 amount) external { pool.flashLoan(amount); pool.withdraw(); msg.sender.send(amount); }
12,549,520
./partial_match/1/0x9d7BB476c40D1055771fCA982876b1E2A72B54F9/sources/BatonZapRouterV1.sol
Withdraw staked tokens from the farm amount Amount of the Pair position to withdraw/ remove the amount unstaked from the total balance if the fee is more then 0 send the fee to batonMonitor transfer the tokens to user
function withdraw(uint256 amount) public updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); require(amount <= _balances[msg.sender], "Cannot withdraw more then you have staked"); _totalSupply = _totalSupply - amount; _balances[msg.sender] = _balances[msg.sender] - amount; if (batonFeeAmount > 0) { stakingToken.safeTransfer(batonMonitor, batonFeeAmount); } uint256 amountToWithdrawal = amount - batonFeeAmount; if (amountToWithdrawal > 0) { stakingToken.safeTransfer(msg.sender, amountToWithdrawal); } emit Withdrawn(msg.sender, amountToWithdrawal); } GET REWARDS
3,890,625
//SPDX-License-Identifier: MIT pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract WaffleMaker { using SafeMath for uint; uint constant PRIZE_POOL_COST_PERCENTAGE = 90; // The rest is given to the owner address as a dev fee uint constant MAX_NAME_BYTES = 32; uint constant MAX_WAFFLE_LAYERS = 5; uint constant MAX_VOTES_PER_ACCOUNT = 3; uint constant LEADERBOARD_WAFFLE_COUNT = 10; uint constant COMPETITION_DURATION = 60 * 60 * 24 * 30; uint constant BAKE_DURATION = 60 * 60 * 24; uint constant CUSTOMIZE_DURATION = 60 * 60 * 24; uint constant CUSTOMIZATION_STEPS_COUNT = 6; uint constant CUSTOMIZATION_STEP_WINDOW_DURATION = 60 * 60; uint constant CREATE_WAFFLE_CURRENCY_COST = 5 * 10 ** 15; uint[CUSTOMIZATION_STEPS_COUNT] CUSTOMIZATION_STEP_WINDOWS = [ 0, 60 * 60, 60 * 60 * 9, 60 * 60 * 17, 60 * 60 * 24, 0 ]; address public owner; address payable public grandPrize; address payable public dev; uint public competitionEndTimestamp; ERC20 currency; // Asset used to pay for waffle creation WaffleItem[] public toppings; WaffleItem[] public bases; WaffleItem[] public plates; WaffleItem[] public extras; Waffle[] waffles; uint[] publishedWaffleIds; mapping (uint => uint) public leaderboardWaffleIds; mapping(address => AccountProfile) profiles; uint finalWeiPrizeAmount; uint finalCurrencyPrizeAmount; bool competitionConcluded = false; event CreateWaffle(address owner, uint waffleId); event BakeWaffleLayer(address owner, uint waffleId); event SubmitWaffleCustomization( address owner, uint waffleId, uint baseId, uint toppingId, uint extraId, uint plateId ); event AdvanceWaffleCustomizationStep(address owner, uint waffleId); event PublishWaffle(address owner, uint waffleId); event VoteWaffle(address owner, uint waffleId); enum CustomizationStep { NOT_CUSTOMIZED, PLATE, BASE, TOPPING, EXTRA, DONE } struct WaffleItem { string name; uint weiCost; } struct WaffleLayer { uint baseId; uint toppingId; } struct Waffle { address owner; uint votes; string name; uint plateId; uint extraId; mapping(uint => WaffleLayer) layers; uint layersCount; bool published; CustomizationStep customizationStep; uint processEnd; // Saves the Unix timestamp at which either the baking or customization ends } struct AccountProfile { mapping(uint => uint) ownedWaffleIds; uint ownedWafflesCount; mapping(uint => uint) votedWaffleIds; uint votedWafflesCount; bool canVote; } // ******************** MODIFIERS ***********************\ modifier isOwner { require(msg.sender == owner, "Caller is not the owner"); _; } modifier competitionIsOngoing { require(block.timestamp < competitionEndTimestamp, "Competition must be ongoing"); _; } modifier competitionHasEnded { require(block.timestamp >= competitionEndTimestamp, "Competition must have ended"); _; } modifier waffleExists(uint _waffleId) { require(_waffleId < waffles.length, "This waffle doesn't exist"); _; } modifier waffleIsBeingProcessed(bool _positive, uint _waffleId) { require((block.timestamp < waffles[_waffleId].processEnd) == _positive, "Invalid waffle processing state"); _; } modifier waffleIsPublished(bool _positive, uint _waffleId) { require(waffles[_waffleId].published == _positive, "Invalid published state"); _; } modifier senderOwnsWaffle(bool _positive, uint _waffleId) { bool waffleOwned = false; for (uint i = 0; i < profiles[msg.sender].ownedWafflesCount; i++) { if (profiles[msg.sender].ownedWaffleIds[i] == _waffleId) { waffleOwned = true; } } require(waffleOwned == _positive, "Invalid waffle owner"); _; } constructor (ERC20 _currency, address _grandPrize, address _dev) public { require(_grandPrize != address(0), "_grandPrize is zero"); require(_dev != address(0), "_dev is zero"); owner = msg.sender; grandPrize = payable(_grandPrize); dev = payable(_dev); competitionEndTimestamp = block.timestamp + COMPETITION_DURATION; currency = _currency; bases.push(WaffleItem('Empty', 0)); toppings.push(WaffleItem('Empty', 0)); plates.push(WaffleItem('Plain Plate', 0)); extras.push(WaffleItem('Empty', 0)); } /** * Add a new topping that can be used by waffles **/ function createTopping (string memory _name, uint _weiCost) external isOwner { toppings.push(WaffleItem(_name, _weiCost)); } /** * Add a new base that can be used by waffles **/ function createBase (string memory _name, uint _weiCost) external isOwner { bases.push(WaffleItem(_name, _weiCost)); } /** * Add a new extra that can be used by waffles **/ function createExtra (string memory _name, uint _weiCost) external isOwner { extras.push(WaffleItem(_name, _weiCost)); } /** * Add a new plate that can be used by waffles **/ function createPlate (string memory _name, uint _weiCost) external isOwner { plates.push(WaffleItem(_name, _weiCost)); } /** * Bake a new waffle with a BAKE_DURATION time to completion * * Costs CREATE_WAFFLE_CURRENCY_COST of the contract currency **/ function createWaffle() external competitionIsOngoing { waffles.push(Waffle({ owner: msg.sender, votes: 0, name: "", plateId: 0, extraId: 0, layersCount: 0, published: false, processEnd: block.timestamp + BAKE_DURATION, customizationStep: CustomizationStep.NOT_CUSTOMIZED })); addWaffleLayer(waffles.length - 1); profiles[msg.sender].ownedWaffleIds[profiles[msg.sender].ownedWafflesCount++] = waffles.length - 1; emit CreateWaffle(msg.sender, waffles.length - 1); } /** * Add a new layer to the waffleId provided if the waffle is owned by the sender and if last * layer has been customized **/ function bakeWaffleLayer(uint _waffleId) external competitionIsOngoing waffleExists(_waffleId) senderOwnsWaffle(true, _waffleId) waffleIsBeingProcessed(false, _waffleId) { require(waffles[_waffleId].customizationStep == CustomizationStep.DONE, "Last layer must be customized"); waffles[_waffleId].processEnd = block.timestamp + BAKE_DURATION; addWaffleLayer(_waffleId); emit BakeWaffleLayer(msg.sender, _waffleId); } /** * Submit the customization for the top layer of a waffle if the top layer is not yet customized * * Every layer can be given a base and a topping, but only the first layer can be given an extra and a plate **/ function submitWaffleCustomization ( uint _waffleId, string memory _name, uint _baseId, uint _toppingId, uint _extraId, uint _plateId ) external payable competitionIsOngoing waffleExists(_waffleId) senderOwnsWaffle(true, _waffleId) waffleIsBeingProcessed(false, _waffleId) { require(waffles[_waffleId].customizationStep == CustomizationStep.NOT_CUSTOMIZED, "Last layer must not already be customized"); require(_baseId < bases.length, "Invalid base"); require(_toppingId < toppings.length, "Invalid topping"); checkCustomizationCosts(_waffleId, _baseId, _toppingId, _extraId, _plateId); if (waffles[_waffleId].layersCount <= 1) { require(bytes(_name).length > 0, "Waffle name can't be empty"); require(bytes(_name).length <= MAX_NAME_BYTES, "Max name length exceeded"); require(_extraId < extras.length, "Invalid extra"); require(_plateId < plates.length, "Invalid plate"); waffles[_waffleId].name = _name; waffles[_waffleId].plateId = _plateId; waffles[_waffleId].extraId = _extraId; } uint lastLayerIndex = waffles[_waffleId].layersCount - 1; waffles[_waffleId].layers[lastLayerIndex].baseId = _baseId; waffles[_waffleId].layers[lastLayerIndex].toppingId = _toppingId; waffles[_waffleId].processEnd = block.timestamp + CUSTOMIZE_DURATION; calculateNextWaffleCustomizationStep(_waffleId); emit SubmitWaffleCustomization(msg.sender, _waffleId, _baseId, _toppingId, _extraId, _plateId); } /** * Adds the ingredient of a waffle if within a customization window * * This needs to be called once for every ingredient added to a waffle * * If not called in time, the waffle will burn **/ function advanceWaffleCustomizationStep(uint _waffleId) external competitionIsOngoing waffleExists(_waffleId) senderOwnsWaffle(true, _waffleId) waffleIsPublished(false, _waffleId) { require(waffles[_waffleId].customizationStep < CustomizationStep.DONE, 'All customization steps done'); uint stepNumber = uint(waffles[_waffleId].customizationStep); uint processStart = waffles[_waffleId].processEnd - CUSTOMIZE_DURATION; uint customizationWindowEnd = processStart + CUSTOMIZATION_STEP_WINDOWS[stepNumber]; uint customizationWindowStart = customizationWindowEnd - CUSTOMIZATION_STEP_WINDOW_DURATION; require(block.timestamp > customizationWindowStart, 'Cannot advance customization step yet'); require(block.timestamp < customizationWindowEnd, 'Waffle burned'); calculateNextWaffleCustomizationStep(_waffleId); emit AdvanceWaffleCustomizationStep(msg.sender, _waffleId); } /** * Makes a waffle available for voting and blocks further customization **/ function publishWaffle(uint _waffleId) external competitionIsOngoing waffleExists(_waffleId) senderOwnsWaffle(true, _waffleId) waffleIsPublished(false, _waffleId) waffleIsBeingProcessed(false, _waffleId) { require(waffles[_waffleId].customizationStep == CustomizationStep.DONE, 'At least one layer must be customized'); waffles[_waffleId].published = true; publishedWaffleIds.push(_waffleId); profiles[msg.sender].canVote = true; emit PublishWaffle(msg.sender, _waffleId); } /** * Cast a vote for the waffleId provided from the sender account. * * Waffle must be published by calling publishWaffle to be voted on * * No more than MAX_VOTES_PER_ACCOUNT votes can be cast per account. **/ function voteWaffle(uint _waffleId) external competitionIsOngoing waffleExists(_waffleId) senderOwnsWaffle(false, _waffleId) waffleIsPublished(true, _waffleId) { require(profiles[msg.sender].canVote, "Must have published at least one waffle to vote"); require(profiles[msg.sender].votedWafflesCount < MAX_VOTES_PER_ACCOUNT, "Max votes on this account exceeded"); require(!addressHasVotedOnWaffle(msg.sender, _waffleId), "Can't vote for the same waffle twice"); waffles[_waffleId].votes++; profiles[msg.sender].votedWaffleIds[profiles[msg.sender].votedWafflesCount++] = _waffleId; uint votes = waffles[_waffleId].votes; uint lastWaffleId = leaderboardWaffleIds[LEADERBOARD_WAFFLE_COUNT - 1]; if (waffles[lastWaffleId].votes >= votes) return; for (uint i = 0; i < LEADERBOARD_WAFFLE_COUNT; i++) { // find where to insert the new score if (waffles[leaderboardWaffleIds[i]].votes < votes) { for (uint j = LEADERBOARD_WAFFLE_COUNT; i < j; j--) { leaderboardWaffleIds[j] = leaderboardWaffleIds[j - 1]; } // insert leaderboardWaffleIds[i] = _waffleId; // delete last from list delete leaderboardWaffleIds[LEADERBOARD_WAFFLE_COUNT]; return; } } emit VoteWaffle(msg.sender, _waffleId); } /** * Transfer the accumulated funds to the dev address and the grand prize address * and save the final prize pool values * * Can be called by anyone **/ function concludeCompetition() external competitionHasEnded { require(!competitionConcluded, "Competition has already been concluded"); uint weiBalance = address(this).balance; uint poolWeiAmount = weiBalance.mul(PRIZE_POOL_COST_PERCENTAGE).div(100); uint devWeiAmount = weiBalance - poolWeiAmount; uint currencyBalance = currency.balanceOf(address(this)); uint poolCurrencyAmount = currencyBalance.mul(PRIZE_POOL_COST_PERCENTAGE).div(100); uint devCurrencyAmount = currencyBalance - poolCurrencyAmount; competitionConcluded = true; finalWeiPrizeAmount = poolWeiAmount; finalCurrencyPrizeAmount = poolCurrencyAmount; grandPrize.transfer(poolWeiAmount); dev.transfer(devWeiAmount); require(currency.transfer(grandPrize, poolCurrencyAmount), "Something went wrong with the prize pool currency transfer"); require(currency.transfer(dev, devCurrencyAmount), "Something went wrong with the dev currency transfer"); } /** * Returns either the wei grand prize to be or the final recorded wei prize * pool if the competition is over **/ function getWeiPrizeAmount() external view returns(uint) { if (competitionConcluded) { return finalWeiPrizeAmount; } else { uint weiBalance = address(this).balance; return weiBalance.mul(PRIZE_POOL_COST_PERCENTAGE).div(100); } } /** * Returns either the currency grand prize to be or the final recorded currency prize * pool if the competition is over **/ function getCurrencyPrizeAmount() external view returns(uint) { if (competitionConcluded) { return finalCurrencyPrizeAmount; } else { uint currencyBalance = currency.balanceOf(address(this)); return currencyBalance.mul(PRIZE_POOL_COST_PERCENTAGE).div(100); } } /** * Returns the address of the creator of a waffle **/ function getWaffleOwner(uint _waffleId) external view waffleExists(_waffleId) returns (address) { return waffles[_waffleId].owner; } /** * Returns the data of the waffle associated to a waffle id **/ function getWaffleInfo(uint _waffleId) public view waffleExists(_waffleId) returns ( uint id, string memory name, uint votes, uint extraId, uint plateId, uint processEnd, bool published, CustomizationStep customizationStep, WaffleLayer[] memory layers ) { Waffle memory waffle = waffles[_waffleId]; WaffleLayer[] memory waffleLayers = new WaffleLayer[](waffle.layersCount); for (uint i = 0; i < waffle.layersCount; i++) { waffleLayers[i] = waffles[_waffleId].layers[i]; } return ( _waffleId, waffle.name, waffle.votes, waffle.extraId, waffle.plateId, waffle.processEnd, waffle.published, waffle.customizationStep, waffleLayers ); } /** * Returns the data of the waffle associated to a published waffle index **/ function getPublishedWaffleInfo(uint _publishedWaffleIndex) external view returns ( uint id, string memory name, uint votes, uint extraId, uint plateId, uint processEnd, bool published, CustomizationStep customizationStep, WaffleLayer[] memory layers ) { require(_publishedWaffleIndex < publishedWaffleIds.length, "Published waffle doesn't exist"); uint waffleId = publishedWaffleIds[_publishedWaffleIndex]; return getWaffleInfo(waffleId); } /** * Returns the data of the waffle associated to a leaderboard index **/ function getLeaderboardWaffleInfo(uint _leaderboardWaffleIndex) external view returns ( uint id, string memory name, uint votes, uint extraId, uint plateId, uint processEnd, bool published, CustomizationStep customizationStep, WaffleLayer[] memory layers ) { require(_leaderboardWaffleIndex < LEADERBOARD_WAFFLE_COUNT && _leaderboardWaffleIndex < waffles.length, "Leaderboard waffle doesn't exist"); uint waffleId = leaderboardWaffleIds[_leaderboardWaffleIndex]; return getWaffleInfo(waffleId); } /** * Returns the profile data associated to an address **/ function getProfileInfo(address _addr) external view returns ( uint[] memory ownedWaffleIds, uint[] memory votedWaffleIds, bool canVote ) { uint[] memory profileOwnedWaffles = new uint[](profiles[_addr].ownedWafflesCount); for (uint i = 0; i < profiles[_addr].ownedWafflesCount; i++) { profileOwnedWaffles[i] = profiles[_addr].ownedWaffleIds[i]; } uint[] memory profileVotedWaffles = new uint[](profiles[_addr].votedWafflesCount); for (uint i = 0; i < profiles[_addr].votedWafflesCount; i++) { profileVotedWaffles[i] = profiles[_addr].votedWaffleIds[i]; } return (profileOwnedWaffles, profileVotedWaffles, profiles[_addr].canVote); } /** * Returns the number of published waffles **/ function getPublishedWafflesCount() external view returns(uint) { return publishedWaffleIds.length; } /** * Returns the number of possible toppings for waffles **/ function getToppingsCount() external view returns(uint) { return toppings.length; } /** * Returns the number of possible bases for waffles **/ function getBasesCount() external view returns(uint) { return bases.length; } /** * Returns the number of possible plates for waffles **/ function getPlatesCount() external view returns(uint) { return plates.length; } /** * Returns the number of possible extras for waffles **/ function getExtrasCount() external view returns(uint) { return extras.length; } function getWaffleLayers(uint _waffleId) internal view returns(WaffleLayer[] memory) { uint layersCount = waffles[_waffleId].layersCount; WaffleLayer[] memory waffleLayers = new WaffleLayer[](layersCount); for (uint i = 0; i < layersCount; i++) { waffleLayers[i] = waffles[_waffleId].layers[i]; } return waffleLayers; } function spendCurrency(uint amount) internal { uint balance = currency.balanceOf(address(msg.sender)); require(balance >= amount, "Currency balance too low for this action"); uint allowance = currency.allowance(address(msg.sender), address(this)); require(allowance >= amount, "Currency allowance too low for this action"); bool returnValue = currency.transferFrom(address(msg.sender), address(this), amount); require(returnValue, "Something went wrong in the currency transfer"); } function checkCustomizationCosts ( uint _waffleId, uint _baseId, uint _toppingId, uint _extraId, uint _plateId ) internal { uint weiCost = 0; if (waffles[_waffleId].layersCount <= 1) { weiCost = weiCost.add(plates[_plateId].weiCost + extras[_extraId].weiCost); } weiCost = weiCost.add(bases[_baseId].weiCost + toppings[_toppingId].weiCost); require(msg.sender.balance >= weiCost, "Wei balance too low for this customization"); require(msg.value == weiCost, "Sent value doesn't match expected value for this waffle customization"); } function addWaffleLayer(uint _waffleId) internal { require(waffles[_waffleId].layersCount < MAX_WAFFLE_LAYERS, "You can't add more layers to this waffle"); waffles[_waffleId].layers[waffles[_waffleId].layersCount++] = WaffleLayer(0,0); waffles[_waffleId].customizationStep = CustomizationStep.NOT_CUSTOMIZED; spendCurrency(CREATE_WAFFLE_CURRENCY_COST); } function waffleCustomizationStepCanBeSkipped(uint _waffleId) internal view returns(bool) { if (waffles[_waffleId].layersCount == 1) { if (waffles[_waffleId].customizationStep == CustomizationStep.PLATE && waffles[_waffleId].plateId == 0) { return true; } else if(waffles[_waffleId].customizationStep == CustomizationStep.EXTRA && waffles[_waffleId].extraId == 0) { return true; } else if(waffles[_waffleId].customizationStep == CustomizationStep.BASE && waffles[_waffleId].layers[waffles[_waffleId].layersCount - 1].baseId == 0) { return true; } else if(waffles[_waffleId].customizationStep == CustomizationStep.TOPPING && waffles[_waffleId].layers[waffles[_waffleId].layersCount - 1].toppingId == 0) { return true; } else { return false; } } else { if (waffles[_waffleId].customizationStep == CustomizationStep.PLATE) { return true; } else if(waffles[_waffleId].customizationStep == CustomizationStep.EXTRA) { return true; } else if(waffles[_waffleId].customizationStep == CustomizationStep.BASE && waffles[_waffleId].layers[waffles[_waffleId].layersCount - 1].baseId == 0) { return true; } else if(waffles[_waffleId].customizationStep == CustomizationStep.TOPPING && waffles[_waffleId].layers[waffles[_waffleId].layersCount - 1].toppingId == 0) { return true; } else { return false; } } } function calculateNextWaffleCustomizationStep(uint _waffleId) internal { do { uint newStepNumber = uint(waffles[_waffleId].customizationStep) + 1; waffles[_waffleId].customizationStep = CustomizationStep(newStepNumber); } while (waffleCustomizationStepCanBeSkipped(_waffleId)); } function addressHasVotedOnWaffle(address _addr, uint _waffleId) internal view returns(bool) { for (uint i = 0; i < profiles[_addr].votedWafflesCount; i++) { if (profiles[_addr].votedWaffleIds[i] == _waffleId) { return true; } } return false; } }
Returns the address of the creator of a waffle/
function getWaffleOwner(uint _waffleId) external view waffleExists(_waffleId) returns (address) { return waffles[_waffleId].owner; }
7,230,155
pragma solidity ^0.6.0; import '@openzeppelin/contracts/math/Math.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/SafeERC20.sol'; import '@openzeppelin/contracts/utils/ReentrancyGuard.sol'; import './interfaces/IOracle.sol'; import './interfaces/IBoardroom.sol'; import './interfaces/IBasisAsset.sol'; import './interfaces/ISimpleERCFund.sol'; import './lib/Babylonian.sol'; import './lib/FixedPoint.sol'; import './lib/Safe112.sol'; import './owner/Operator.sol'; import './utils/Epoch.sol'; import './utils/ContractGuard.sol'; import './ChainLinkOracle.sol'; /** * @title Big Mac Index Treasury contract * @notice Monetary policy logic to adjust supplies of Big Mac Index assets * @author Summer Smith & Rick Sanchez */ contract Treasury is ContractGuard, Epoch { using FixedPoint for *; using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; using Safe112 for uint112; /* ========== STATE VARIABLES ========== */ // ========== FLAGS bool public migrated = false; bool public initialized = false; // ========== CORE address public fund; address public macIndex; address public bond; address public share; address public boardroom; IOracle public macIndexOracle; ChainlinkOracle public tmcOracle; //total market cap oracle // ========== PARAMS uint256 private accumulatedSeigniorage = 0; uint256 public fundAllocationRate = 2; // % /* ========== CONSTRUCTOR ========== */ constructor( address _macIndex, address _bond, address _share, IOracle _macIndexOracle, ChainlinkOracle _tmcOracle, address _boardroom, address _fund, uint256 _startTime ) public Epoch(8 hours, _startTime, 0) { macIndex = _macIndex; bond = _bond; share = _share; macIndexOracle = _macIndexOracle; tmcOracle = _tmcOracle; boardroom = _boardroom; fund = _fund; } /* =================== Modifier =================== */ modifier checkMigration { require(!migrated, 'Treasury: migrated'); _; } modifier checkOperator { require( IBasisAsset(macIndex).operator() == address(this) && IBasisAsset(bond).operator() == address(this) && IBasisAsset(share).operator() == address(this) && Operator(boardroom).operator() == address(this), 'Treasury: need more permission' ); _; } /* ========== Oracle FUNCTIONS ========== */ function getOraclePrice(ChainlinkOracle _oracle) public virtual view returns (uint256 price) { price = _oracle.getLatestAnswer().toUint256().mul(oracleDigits); } /* ========== VIEW FUNCTIONS ========== */ // budget function getReserve() public view returns (uint256) { return accumulatedSeigniorage; } function getMacIndexPrice() public view returns (uint256) { try macIndexOracle.price1Last() returns (uint256 price) { return price; } catch { revert('Treasury: failed to consult macIndex price from the oracle'); } } /** * @notice Returns the target price of the MCI token * @return target price of the MCI Token * @dev MCI token is 18 decimals * @dev oracle getTotalMarketCap must be in wei format * @dev P = M / d * P = Target MCI Token Price * M = Total Crypto Market Cap * d = Divisor */ function getTargetPrice() public virtual view returns (uint256 targetPrice) { uint256 totalMarketPrice = getOraclePrice(tmcOracle); targetPrice = totalMarketPrice.div(10**12); } function macIndexPriceCeiling() public view returns(uint256) { return getTargetPrice().mul(uint256(105)).div(100); } /* ========== GOVERNANCE ========== */ function initialize() public checkOperator { require(!initialized, 'Treasury: initialized'); // burn all of it's balance IBasisAsset(macIndex).burn(IERC20(macIndex).balanceOf(address(this))); // set accumulatedSeigniorage to it's balance accumulatedSeigniorage = IERC20(macIndex).balanceOf(address(this)); initialized = true; emit Initialized(msg.sender, block.number); } function migrate(address target) public onlyOperator checkOperator { require(!migrated, 'Treasury: migrated'); // macIndex Operator(macIndex).transferOperator(target); Operator(macIndex).transferOwnership(target); IERC20(macIndex).transfer(target, IERC20(macIndex).balanceOf(address(this))); // bond Operator(bond).transferOperator(target); Operator(bond).transferOwnership(target); IERC20(bond).transfer(target, IERC20(bond).balanceOf(address(this))); // share Operator(share).transferOperator(target); Operator(share).transferOwnership(target); IERC20(share).transfer(target, IERC20(share).balanceOf(address(this))); migrated = true; emit Migration(target); } function setFund(address newFund) public onlyOperator { fund = newFund; emit ContributionPoolChanged(msg.sender, newFund); } function setFundAllocationRate(uint256 rate) public onlyOperator { fundAllocationRate = rate; emit ContributionPoolRateChanged(msg.sender, rate); } /* ========== MUTABLE FUNCTIONS ========== */ function _updatemacIndexPrice() internal { try macIndexOracle.update() {} catch {} } function buyBonds(uint256 amount, uint256 desiredPurchasePrice) external onlyOneBlock checkMigration checkStartTime checkOperator { require(amount > 0, 'Treasury: cannot purchase bonds with zero amount'); uint256 macIndexPrice = getMacIndexPrice(); uint256 targetPrice = getTargetPrice(); require(macIndexPrice == desiredPurchasePrice, 'Treasury: macIndex price moved'); require( macIndexPrice < targetPrice, 'Treasury: macIndexPrice not eligible for bond purchase' ); uint256 priceRatio = macIndexPrice.mul(1e18).div(getTargetPrice()); IBasisAsset(macIndex).burnFrom(msg.sender, amount); IBasisAsset(bond).mint(msg.sender, amount.mul(1e18).div(priceRatio)); _updatemacIndexPrice(); emit BoughtBonds(msg.sender, amount); } function redeemBonds(uint256 amount, uint256 desiredPurchasePrice) external onlyOneBlock checkMigration checkStartTime checkOperator { require(amount > 0, 'Treasury: cannot redeem bonds with zero amount'); uint256 macIndexPrice = getMacIndexPrice(); require(macIndexPrice == targetPrice, 'Treasury: macIndex price moved'); require( macIndexPrice > macIndexPriceCeiling(), // price > realmacIndexPrice * 1.05 'Treasury: macIndexPrice not eligible for bond purchase' ); require( IERC20(macIndex).balanceOf(address(this)) >= amount, 'Treasury: treasury has no more budget' ); accumulatedSeigniorage = accumulatedSeigniorage.sub( Math.min(accumulatedSeigniorage, amount) ); IBasisAsset(bond).burnFrom(msg.sender, amount); IERC20(macIndex).safeTransfer(msg.sender, amount); _updatemacIndexPrice(); emit RedeemedBonds(msg.sender, amount); } function allocateSeigniorage() external onlyOneBlock checkMigration checkStartTime checkEpoch checkOperator { _updatemacIndexPrice(); uint256 macIndexPrice = getMacIndexPrice(); if (macIndexPrice <= macIndexPriceCeiling()) { return; // just advance epoch instead revert } // circulating supply uint256 macIndexSupply = IERC20(macIndex).totalSupply().sub( accumulatedSeigniorage ); uint256 percentage = (macIndexPrice.mul(1e18).div(getTargetPrice())).sub(1e18); uint256 seigniorage = macIndexSupply.mul(percentage).div(1e18); IBasisAsset(macIndex).mint(address(this), seigniorage); // ======================== BIP-3 uint256 fundReserve = seigniorage.mul(fundAllocationRate).div(100); if (fundReserve > 0) { IERC20(macIndex).safeApprove(fund, fundReserve); ISimpleERCFund(fund).deposit( macIndex, fundReserve, 'Treasury: Seigniorage Allocation' ); emit ContributionPoolFunded(now, fundReserve); } seigniorage = seigniorage.sub(fundReserve); // ======================== BIP-4 uint256 treasuryReserve = Math.min( seigniorage, IERC20(bond).totalSupply().sub(accumulatedSeigniorage) ); if (treasuryReserve > 0) { accumulatedSeigniorage = accumulatedSeigniorage.add( treasuryReserve ); emit TreasuryFunded(now, treasuryReserve); } // boardroom uint256 boardroomReserve = seigniorage.sub(treasuryReserve); if (boardroomReserve > 0) { IERC20(macIndex).safeApprove(boardroom, boardroomReserve); IBoardroom(boardroom).allocateSeigniorage(boardroomReserve); emit BoardroomFunded(now, boardroomReserve); } } // GOV event Initialized(address indexed executor, uint256 at); event Migration(address indexed target); event ContributionPoolChanged(address indexed operator, address newFund); event ContributionPoolRateChanged( address indexed operator, uint256 newRate ); // CORE event RedeemedBonds(address indexed from, uint256 amount); event BoughtBonds(address indexed from, uint256 amount); event TreasuryFunded(uint256 timestamp, uint256 seigniorage); event BoardroomFunded(uint256 timestamp, uint256 seigniorage); event ContributionPoolFunded(uint256 timestamp, uint256 seigniorage); }
burn all of it's balance set accumulatedSeigniorage to it's balance
function initialize() public checkOperator { require(!initialized, 'Treasury: initialized'); IBasisAsset(macIndex).burn(IERC20(macIndex).balanceOf(address(this))); accumulatedSeigniorage = IERC20(macIndex).balanceOf(address(this)); initialized = true; emit Initialized(msg.sender, block.number); }
12,912,047
//SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "./interfaces/ICalibrator.sol"; import "hardhat/console.sol"; /// @title Calibrator contract Calibrator is ICalibrator { address public owner; IERC20 public base; IUniswapV2Router01 public router; string public dex; struct Pool { uint256 reserveBase; uint256 reserveQuote; uint256 totalSupply; uint256 kLast; } struct Wallet { uint256 amountBase; uint256 amountQuote; uint256 liquidity; } constructor( IERC20 _base, IUniswapV2Router01 _router, string memory _dex ) { owner = msg.sender; base = _base; router = _router; require( (equal(_dex, "MDEX")) || (equal(_dex, "QUICK")) || (equal(_dex, "SPIRIT")) || (equal(_dex, "SPOOKY")) || (equal(_dex, "SUSHI")) || (equal(_dex, "PANGOLIN")) || (equal(_dex, "HONEY")) || (equal(_dex, "SUSHI")) || (equal(_dex, "CAKE")), "dex unknown" ); dex = _dex; } function setOwner(address _owner) external { require(msg.sender == owner, "ACW"); owner = _owner; } // **** CALIBRATE FUNCTIONS **** function calibrate3( IUniswapV2Pair pool1, uint256 liquidity1, uint256 amountBaseBuy1, IUniswapV2Pair pool2, uint256 liquidity2, uint256 amountBaseBuy2, IUniswapV2Pair pool3, uint256 liquidity3, uint256 amountBaseBuy3, address to ) external { calibrate(pool1, liquidity1, amountBaseBuy1, to); calibrate(pool2, liquidity2, amountBaseBuy2, to); calibrate(pool3, liquidity3, amountBaseBuy3, to); } function calibrate2( IUniswapV2Pair pool1, uint256 liquidity1, uint256 amountBaseBuy1, IUniswapV2Pair pool2, uint256 liquidity2, uint256 amountBaseBuy2, address to ) external { calibrate(pool1, liquidity1, amountBaseBuy1, to); calibrate(pool2, liquidity2, amountBaseBuy2, to); } function calibrateSafe( IUniswapV2Pair pool, uint256 liquidity, uint256 amountBuy, address to, uint256 price // price * 10000; 60.12 = 612000; 0.652 = 6520; 0.0632 = 632 ) public { // remove `liquidity` (uint256 reserveBase, uint256 reserveQuote, , ) = estimateNow( pool, liquidity, amountBuy ); require((reserveBase * 10000) / reserveQuote < price, "C1"); IERC20 token = tokenFromPool(pool); remove(pool, token, liquidity); // buy base for `amountBuy` buy(pool, token, amountBuy); // add liquidity for all quote token and have some base left add(pool, token); // send base and lp to `to` retrieve(pool, to, token); } function calibrateDown( IUniswapV2Pair pool, uint256 liquidity, uint256 amountSell, address to ) override public { IERC20 token = tokenFromPool(pool); remove(pool, token, liquidity); sell(pool, token, amountSell); add(pool, token); retrieve(pool, to, token); } function calibrate( IUniswapV2Pair pool, uint256 liquidity, uint256 amountBuy, address to ) override public { // remove `liquidity` IERC20 token = tokenFromPool(pool); remove(pool, token, liquidity); // console.log("amountBuy: %s", amountBuy); // console.log("balance before - b: %s, q: %s", base.balanceOf(address(this)), token.balanceOf(address(this))); // buy base for `amountBuy` buy(pool, token, amountBuy); // console.log("balance after - b: %s, q: %s", base.balanceOf(address(this)), token.balanceOf(address(this))); // add liquidity for all quote token and have some base left add(pool, token); // send base and lp to `to` retrieve(pool, to, token); } function removeThenBuy( IUniswapV2Pair pool, uint256 liquidity, uint256 amountBuy, address to ) public { // remove `liquidity` IERC20 token = tokenFromPool(pool); remove(pool, token, liquidity); // buy base for `amountBuy` buy(pool, token, amountBuy); // send base and lp to `to` retrieve(pool, to, token); } function remove( IUniswapV2Pair pool, IERC20 token, uint256 liquidityRemove ) public { // transfer `liquidity` from msg.sender pool.transferFrom(msg.sender, address(this), liquidityRemove); // log(pool, "=========== before remove ==========="); uint256 liquidity = pool.balanceOf(address(this)); uint256 totalSupply = pool.totalSupply(); uint256 kLast = pool.kLast(); (uint256 reserveBase, uint256 reserveQuote) = getReserves( pool, address(base), address(token) ); ( , , , , uint256 amountBaseAfter, uint256 amountQuoteAfter ) = estimateRemove( reserveBase, reserveQuote, totalSupply, kLast, liquidity ); uint256 deadline = block.timestamp + 86400; console.log("remove liquidity", amountBaseAfter, amountQuoteAfter, liquidity); pool.approve(address(router), liquidity); router.removeLiquidity( address(base), address(token), liquidity, amountBaseAfter, amountQuoteAfter, address(this), deadline ); // log(pool, "=========== after remove ==========="); } function sell( IUniswapV2Pair pool, IERC20 token, uint256 amountSell ) public { base.approve(address(router), base.balanceOf(address(this))); token.approve(address(router), token.balanceOf(address(this))); address[] memory pathToBase = new address[](2); pathToBase[0] = address(base); pathToBase[1] = address(token); uint256 deadline = block.timestamp + 86400; uint256[] memory amounts = router.getAmountsOut(amountSell, pathToBase); router.swapTokensForExactTokens( amountSell, amounts[0], pathToBase, address(this), deadline ); // log(pool, "=========== after buy ==========="); } function buy( IUniswapV2Pair pool, IERC20 token, uint256 amountBuy ) public { // log(pool, "=========== before buy ==========="); base.approve(address(router), base.balanceOf(address(this))); token.approve(address(router), token.balanceOf(address(this))); address[] memory pathToBase = new address[](2); pathToBase[0] = address(token); pathToBase[1] = address(base); uint256 deadline = block.timestamp + 86400; uint256[] memory amounts = router.getAmountsIn(amountBuy, pathToBase); // console.log("swap base for token", amountBuy, amounts[0]); router.swapTokensForExactTokens( amountBuy, amounts[0], pathToBase, address(this), deadline ); // log(pool, "=========== after buy ==========="); } function add(IUniswapV2Pair pool, IERC20 token) public { // log(pool, "=========== before add ==========="); uint256 balanceOfToken = token.balanceOf(address(this)); uint256 balanceOfBase = base.balanceOf(address(this)); base.approve(address(router), balanceOfToken); token.approve(address(router), balanceOfToken); uint256 amountQuoteAdd = balanceOfToken; uint256 amountBaseAdd = balanceOfBase; if (amountBaseAdd == 0 || amountQuoteAdd == 0) { return; } address[] memory pathToBase = new address[](2); pathToBase[0] = address(token); pathToBase[1] = address(base); uint256 deadline = block.timestamp + 86400; (uint256 reserveBase, uint256 reserveQuote) = getReserves( pool, address(base), address(token) ); amountBaseAdd = quote( amountQuoteAdd, reserveQuote, reserveBase ); if (amountBaseAdd == 0) { return; } // console.log("balances base and token", balanceOfBase, balanceOfToken); // console.log("add liquidity", amountBaseAdd, amountQuoteAdd); /** * Due to a fact that after swap amountBaseAdd may be much more than balanceOfBase * this `if` statement handles the case of `base` token disbalance * with further recalculations. * * Moreover, case of `amountBaseAdd <= balanceOfBase` is handled by default. */ if (amountBaseAdd > balanceOfBase) { amountBaseAdd = balanceOfBase; amountQuoteAdd = quote( amountBaseAdd, reserveBase, reserveQuote ); // recalculate because base is taken first into consideration on `addLiquidity` amountBaseAdd = quote( amountQuoteAdd, reserveQuote, reserveBase ); } (uint256 amountA, uint256 amountB, uint256 liq) = router.addLiquidity( address(token), address(base), amountQuoteAdd, amountBaseAdd, amountQuoteAdd, amountBaseAdd, address(this), deadline ); console.log("add liquidity", amountA, amountB, liq); // log(pool, "=========== after add ==========="); } function retrieve(IUniswapV2Pair pool, address to, IERC20 token) internal { require(to != address(0), "can't send to 0"); pool.transfer(to, pool.balanceOf(address(this))); base.transfer(to, base.balanceOf(address(this))); token.transfer(to, token.balanceOf(address(this))); } // **** ESTIMATE FUNCTIONS **** function estimateNow( IUniswapV2Pair pool, uint256 liquidityRemove, uint256 amountBuy ) public view returns ( uint256 reserveBase, uint256 reserveQuote, uint256 amountBase, uint256 liquidityAfter ) { Pool memory pBefore; IERC20 token = tokenFromPool(pool); (pBefore.reserveBase, pBefore.reserveQuote) = getReserves( pool, address(base), address(token) ); pBefore.totalSupply = pool.totalSupply(); pBefore.kLast = pool.kLast(); (Pool memory pAfter, Wallet memory wAfter) = estimate( pBefore, liquidityRemove, amountBuy ); return ( pAfter.reserveBase, pAfter.reserveQuote, wAfter.amountBase, wAfter.liquidity ); } function estimateBuyNow(IUniswapV2Pair pool, uint256 amountBaseBuy) external view returns ( uint256 reserveBase, uint256 reserveQuote, uint256 amountTokenSell ) { IERC20 token = tokenFromPool(pool); (uint256 reserveBaseBefore, uint256 reserveQuoteBefore) = getReserves( pool, address(base), address(token) ); (reserveBase, reserveQuote, amountTokenSell) = estimateBuy( reserveBaseBefore, reserveQuoteBefore, amountBaseBuy ); return (reserveBase, reserveQuote, amountTokenSell); } function estimateSellNow(IUniswapV2Pair pool, uint256 amountBaseSell) external view returns ( uint256 reserveBase, uint256 reserveQuote, uint256 amountTokenBuy ) { IERC20 token = tokenFromPool(pool); (uint256 reserveBaseBefore, uint256 reserveQuoteBefore) = getReserves( pool, address(base), address(token) ); (reserveBase, reserveQuote, amountTokenBuy) = estimateSell( reserveBaseBefore, reserveQuoteBefore, amountBaseSell ); return (reserveBase, reserveQuote, amountTokenBuy); } function estimate( Pool memory pBefore, uint256 liquidityRemove, uint256 amountBaseBuy ) public view returns (Pool memory pAfter, Wallet memory wAfter) { (Pool memory pAfterRemove, Wallet memory wAfterRemove) = estimateRemove( pBefore, liquidityRemove ); (Pool memory pAfterBuy, Wallet memory wAfterBuy, ) = estimateBuy( pAfterRemove, wAfterRemove, amountBaseBuy ); (Pool memory pAfterAdd, Wallet memory wAfterAdd) = estimateAdd( pAfterBuy, wAfterBuy ); pAfter = pAfterAdd; wAfter = wAfterAdd; } function estimateRemove(Pool memory pBefore, uint256 liquidityRemove) public view returns (Pool memory pAfter, Wallet memory wAfter) { pAfter = pBefore; uint256 reserveBase = pBefore.reserveBase; uint256 reserveQuote = pBefore.reserveQuote; uint256 totalSupply = pBefore.totalSupply; uint256 kLast = pBefore.kLast; totalSupply = mintFee(reserveBase, reserveQuote, totalSupply, kLast); uint256 amountBase = (liquidityRemove * reserveBase) / totalSupply; uint256 amountQuote = (liquidityRemove * reserveQuote) / totalSupply; pAfter.totalSupply = totalSupply - liquidityRemove; wAfter.amountBase = amountBase; wAfter.amountQuote = amountQuote; pAfter.reserveBase = reserveBase - amountBase; pAfter.reserveQuote = reserveQuote - amountQuote; pAfter.kLast = pAfter.reserveBase * pAfter.reserveQuote; } function estimateBuy( Pool memory pBefore, Wallet memory wBefore, uint256 amountBaseBuy ) public view returns ( Pool memory pAfter, Wallet memory wAfter, uint256 amountTokenSell ) { pAfter = pBefore; wAfter = wBefore; amountTokenSell = getAmountIn( amountBaseBuy, pBefore.reserveQuote, pBefore.reserveBase ); // console.log("swap base for token", amountBaseBuy, amountTokensell); wAfter.amountBase = wBefore.amountBase + amountBaseBuy; wAfter.amountQuote = wBefore.amountQuote - amountTokenSell; pAfter.reserveBase = pBefore.reserveBase - amountBaseBuy; pAfter.reserveQuote = pBefore.reserveQuote + amountTokenSell; // console.log("reserves after buy", pAfter.reserveBase, pAfter.reserveQuote); } function estimateAdd(Pool memory pBefore, Wallet memory wBefore) public view returns (Pool memory pAfter, Wallet memory wAfter) { pAfter = pBefore; wAfter = wBefore; uint256 reserveBase = pBefore.reserveBase; uint256 reserveQuote = pBefore.reserveQuote; uint256 totalSupply = pBefore.totalSupply; uint256 kLast = pBefore.kLast; uint256 amountQuoteAdd = wBefore.amountQuote; uint256 amountBaseAdd = quote( amountQuoteAdd, reserveQuote, reserveBase ); wAfter.amountBase = wBefore.amountBase - amountBaseAdd; wAfter.amountQuote = wBefore.amountQuote - amountQuoteAdd; totalSupply = mintFee(reserveBase, reserveQuote, totalSupply, kLast); uint256 liquidity = min( (amountBaseAdd * totalSupply) / reserveBase, (amountQuoteAdd * totalSupply) / reserveQuote ); wAfter.liquidity = liquidity; pAfter.totalSupply = totalSupply + liquidity; pAfter.reserveBase = reserveBase + amountBaseAdd; pAfter.reserveQuote = reserveQuote + amountQuoteAdd; pAfter.kLast = pAfter.reserveBase * pAfter.reserveQuote; } // **** PICK FUNCTIONS **** function pickBuyNow( IUniswapV2Pair pool, uint256 price, // 2 decimals uint256 start, uint256 end ) public view returns ( uint256, uint256, uint256 ) { IERC20 token = tokenFromPool(pool); (uint256 reserveBaseBefore, uint256 reserveQuoteBefore) = getReserves( pool, address(base), address(token) ); return pickBuy(reserveBaseBefore, reserveQuoteBefore, price, start, end); } function pickSellNow( IUniswapV2Pair pool, uint256 price, // 2 decimals uint256 start, uint256 end ) public view returns ( uint256, uint256, uint256 ) { IERC20 token = tokenFromPool(pool); (uint256 reserveBaseBefore, uint256 reserveQuoteBefore) = getReserves( pool, address(base), address(token) ); return pickSell(reserveBaseBefore, reserveQuoteBefore, price, start, end); } function pickBuy( uint256 reserveBaseBefore, uint256 reserveQuoteBefore, uint256 price, // 2 decimals uint256 start, uint256 end ) public view returns ( uint256, uint256, uint256 ) { uint256 ds = 100; if ((reserveQuoteBefore * ds) / reserveBaseBefore == price) { // console.log( // // "--", // reserveBaseBefore, // reserveQuoteBefore, // (reserveQuoteBefore * ds) / reserveBaseBefore, // 0 // ); return (reserveBaseBefore, reserveQuoteBefore, 0); } uint256 amountBaseBuy = (start + end) / 2; if (start > end) { return (reserveBaseBefore, reserveQuoteBefore, amountBaseBuy); } ( uint256 reserveBaseAfter, uint256 reserveQuoteAfter, uint256 amountQuoteSell ) = estimateBuy(reserveBaseBefore, reserveQuoteBefore, amountBaseBuy); if ((reserveQuoteAfter * ds) / reserveBaseAfter == price) { // console.log( // // "eq", // reserveBaseAfter, // reserveQuoteAfter, // (reserveQuoteAfter * ds) / reserveBaseAfter, // amountBaseBuy // ); return (reserveBaseAfter, reserveQuoteAfter, amountBaseBuy); } if ((reserveQuoteAfter * ds) / reserveBaseAfter < price) { // console.log( // // "lt", // reserveBaseAfter, // reserveQuoteAfter, // (reserveQuoteAfter * ds) / reserveBaseAfter, // amountBaseBuy // ); return pickBuy( reserveBaseBefore, reserveQuoteBefore, price, amountBaseBuy + 1, end ); } if ((reserveQuoteAfter * ds) / reserveBaseAfter > price) { // console.log( // // "gt", // reserveBaseAfter, // reserveQuoteAfter, // (reserveQuoteAfter * ds) / reserveBaseAfter, // amountBaseBuy // ); return pickBuy( reserveBaseBefore, reserveQuoteBefore, price, start, amountBaseBuy - 1 ); } } function pickSell( uint256 reserveBaseBefore, uint256 reserveQuoteBefore, uint256 price, // 2 decimals uint256 start, uint256 end ) public view returns ( uint256, uint256, uint256 ) { uint256 ds = 100; if ((reserveQuoteBefore * ds) / reserveBaseBefore == price) { // console.log( // // "--", // reserveBaseBefore, // reserveQuoteBefore, // (reserveQuoteBefore * ds) / reserveBaseBefore, // 0 // ); return (reserveBaseBefore, reserveQuoteBefore, 0); } uint256 amountBaseSell = (start + end) / 2; if (start > end) { return (reserveBaseBefore, reserveQuoteBefore, amountBaseSell); } ( uint256 reserveBaseAfter, uint256 reserveQuoteAfter, uint256 amountQuoteSell ) = estimateSell(reserveBaseBefore, reserveQuoteBefore, amountBaseSell); if ((reserveQuoteAfter * ds) / reserveBaseAfter == price) { // console.log( // // "eq", // reserveBaseAfter, // reserveQuoteAfter, // (reserveQuoteAfter * ds) / reserveBaseAfter, // amountBaseSell // ); return (reserveBaseAfter, reserveQuoteAfter, amountBaseSell); } if ((reserveQuoteAfter * ds) / reserveBaseAfter > price) { // console.log( // // "lt", // reserveBaseAfter, // reserveQuoteAfter, // (reserveQuoteAfter * ds) / reserveBaseAfter, // amountBaseSell // ); return pickSell( reserveBaseBefore, reserveQuoteBefore, price, amountBaseSell + 1, end ); } if ((reserveQuoteAfter * ds) / reserveBaseAfter < price) { // console.log( // // "gt", // reserveBaseAfter, // reserveQuoteAfter, // (reserveQuoteAfter * ds) / reserveBaseAfter, // amountBaseSell // ); return pickSell( reserveBaseBefore, reserveQuoteBefore, price, start, amountBaseSell - 1 ); } } // **** STEP FUNCTIONS **** function estimateRemove( uint256 reserveBaseBefore, uint256 reserveQuoteBefore, uint256 totalSupplyBefore, uint256 kLastBefore, uint256 liquidityRemove ) override public view returns ( uint256 reserveBaseAfter, uint256 reserveQuoteAfter, uint256 totalSupplyAfter, uint256 kLastAfter, uint256 amountBaseAfter, uint256 amountQuoteAfter ) { uint256 totalSupply = mintFee( reserveBaseBefore, reserveQuoteBefore, totalSupplyBefore, kLastBefore ); amountBaseAfter = (liquidityRemove * reserveBaseBefore) / totalSupply; amountQuoteAfter = (liquidityRemove * reserveQuoteBefore) / totalSupply; totalSupplyAfter = totalSupplyBefore - liquidityRemove; reserveBaseAfter = reserveBaseBefore - amountBaseAfter; reserveQuoteAfter = reserveQuoteBefore - amountQuoteAfter; kLastAfter = reserveBaseAfter * reserveQuoteAfter; } function estimateBuy( uint256 reserveBaseBefore, uint256 reserveQuoteBefore, uint256 amountBaseBuy ) override public view returns ( uint256 reserveBaseAfter, uint256 reserveQuoteAfter, uint256 amountQuoteSell ) { amountQuoteSell = getAmountIn( amountBaseBuy, reserveQuoteBefore, reserveBaseBefore ); reserveBaseAfter = reserveBaseBefore - amountBaseBuy; reserveQuoteAfter = reserveQuoteBefore + amountQuoteSell; } function estimateSell( uint256 reserveBaseBefore, uint256 reserveQuoteBefore, uint256 amountBaseSell ) override public view returns ( uint256 reserveBaseAfter, uint256 reserveQuoteAfter, uint256 amountQuoteBuy ) { amountQuoteBuy = getAmountOut( amountBaseSell, reserveBaseBefore, reserveQuoteBefore ); reserveBaseAfter = reserveBaseBefore + amountBaseSell; reserveQuoteAfter = reserveQuoteBefore - amountQuoteBuy; } function estimateAdd( uint256 reserveBaseBefore, uint256 reserveQuoteBefore, uint256 totalSupplyBefore, uint256 kLastBefore, uint256 amountQuoteAdd ) public view returns ( uint256 reserveBaseAfter, uint256 reserveQuoteAfter, uint256 totalSupplyAfter, uint256 kLastAfter, uint256 amountBaseAdd, uint256 liquidity ) { amountBaseAdd = quote( amountQuoteAdd, reserveQuoteBefore, reserveBaseBefore ); uint256 totalSupply = mintFee( reserveBaseBefore, reserveQuoteBefore, totalSupplyBefore, kLastBefore ); liquidity = min( (amountBaseAdd * totalSupplyAfter) / reserveBaseBefore, (amountQuoteAdd * totalSupplyAfter) / reserveQuoteBefore ); totalSupplyAfter = totalSupply + liquidity; reserveBaseAfter = reserveBaseBefore + amountBaseAdd; reserveQuoteAfter = reserveQuoteBefore + amountQuoteAdd; kLastAfter = reserveBaseAfter * reserveQuoteAfter; } // **** LIBRARY FUNCTIONS **** function sqrt(uint256 a) internal pure returns (uint256 b) { if (a > 3) { b = a; uint256 x = a / 2 + 1; while (x < b) { b = x; x = (a / x + x) / 2; } } else if (a != 0) { b = 1; } } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a <= b ? a : b; } function equal(string memory a, string memory b) public pure returns (bool) { return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b)); } /** * returns quote token */ function tokenFromPool(IUniswapV2Pair pool) override public view returns (IERC20 token) { address token0 = pool.token0(); address token1 = pool.token1(); token = token0 == address(base) ? IERC20(token1) : IERC20(token0); } // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "UniswapV2Library: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "UniswapV2Library: ZERO_ADDRESS"); } function getRouter() override public view returns (address rtr) { rtr = address(router); } // fetches and sorts the reserves for a pair // uses getPair instead of pairFor because init code hashes can be different for amms function getReserves( IUniswapV2Pair pool, address tokenA, address tokenB ) override public view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = pool.getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) public pure returns (uint256 amountB) { require(amountA > 0, "UniswapV2Library: INSUFFICIENT_AMOUNT"); require( reserveA > 0 && reserveB > 0, "UniswapV2Library: INSUFFICIENT_LIQUIDITY" ); amountB = (amountA * reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) override public view returns (uint256 amountOut) { // require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); // require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); if (equal(dex, "CAKE")) { uint256 amountInWithFee = amountIn * 9975; uint256 numerator = amountInWithFee * reserveOut; uint256 denominator = (reserveIn * 10000) + amountInWithFee; amountOut = numerator / denominator; } else if (equal(dex, "SPOOKY")) { uint256 amountInWithFee = amountIn * 998; uint256 numerator = amountInWithFee * reserveOut; uint256 denominator = (reserveIn * 1000) + amountInWithFee; amountOut = numerator / denominator; } else { uint256 amountInWithFee = amountIn * 997; uint256 numerator = amountInWithFee * reserveOut; uint256 denominator = (reserveIn * 1000) + amountInWithFee; amountOut = numerator / denominator; } } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) public view returns (uint256 amountIn) { // require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); // require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); if (equal(dex, "CAKE")) { uint256 numerator = reserveIn * amountOut * 10000; uint256 denominator = (reserveOut - amountOut) * 9975; amountIn = (numerator / denominator) + 1; } else if (equal(dex, "SPOOKY")) { uint256 numerator = reserveIn * amountOut * 1000; uint256 denominator = (reserveOut - amountOut) * 998; amountIn = (numerator / denominator) + 1; } else { uint256 numerator = reserveIn * amountOut * 1000; uint256 denominator = (reserveOut - amountOut) * 997; amountIn = (numerator / denominator) + 1; } } function mintFee( uint256 reserve0, uint256 reserve1, uint256 totalSupply, uint256 kLast ) internal view returns (uint256 totalSupplyNew) { if (equal(dex, "MDEX")) { if (kLast != 0) { uint256 rootK = sqrt(reserve0 * reserve1); uint256 rootKLast = sqrt(kLast); if (rootK > rootKLast) { uint256 numerator = totalSupply * (rootK - rootKLast); uint256 denominator = rootKLast; uint256 liquidityFee = numerator / denominator; if (liquidityFee > 0) { totalSupply += liquidityFee; } } } } else if (equal(dex, "CAKE")) { if (kLast != 0) { uint256 rootK = sqrt(reserve0 * reserve1); uint256 rootKLast = sqrt(kLast); if (rootK > rootKLast) { uint256 numerator = totalSupply * (rootK - rootKLast); uint256 denominator = (rootK * 17) + rootKLast; uint256 liquidityFee = numerator / denominator; if (liquidityFee > 0) { totalSupply += liquidityFee; } } } } else if (equal(dex, "SPOOKY")) { if (kLast != 0) { uint256 rootK = sqrt(reserve0 * reserve1); uint256 rootKLast = sqrt(kLast); if (rootK > rootKLast) { uint256 numerator = totalSupply * (rootK - rootKLast); uint256 denominator = (rootK * 3) + rootKLast; uint256 liquidityFee = numerator / denominator; if (liquidityFee > 0) { totalSupply += liquidityFee; } } } } else { if (kLast != 0) { uint256 rootK = sqrt(reserve0 * reserve1); uint256 rootKLast = sqrt(kLast); if (rootK > rootKLast) { uint256 numerator = totalSupply * (rootK - rootKLast); uint256 denominator = (rootK * 5) + rootKLast; uint256 liquidityFee = numerator / denominator; if (liquidityFee > 0) { totalSupply += liquidityFee; } } } } return totalSupply; } // **** RECLAIM FUNCTION **** function reclaimERC20(IERC20 token, uint256 amount) external { require(msg.sender == owner, "ACW"); token.transfer(msg.sender, amount); } function reclaimNative(uint256 amount) external { require(msg.sender == owner, "ACW"); payable(msg.sender).transfer(amount); } // **** LOG FUNCTION **** // function log(IUniswapV2Pair pool, string memory s) internal { // IERC20 token = tokenFromPool(pool); // console.log(s); // console.log( // "balances", // base.balanceOf(address(this)), // token.balanceOf(address(this)) // ); // console.log( // "reserves", // base.balanceOf(address(pool)), // token.balanceOf(address(pool)) // ); // address[] memory pathToQuote = new address[](2); // pathToQuote[0] = address(base); // pathToQuote[1] = address(token); // uint[] memory tokens = router.getAmountsOut(1e4, pathToQuote); // console.log("for 10000 base", tokens[1], "token"); // console.log(tokens[1], "/", tokens[0], tokens[1]/tokens[0]); // console.log(tokens[0], "/", tokens[1], tokens[1]==0 ? 0 : tokens[0]/tokens[1]); // console.log("====================================="); // } }
fetches and sorts the reserves for a pair uses getPair instead of pairFor because init code hashes can be different for amms
function getReserves( IUniswapV2Pair pool, address tokenA, address tokenB ) override public view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = pool.getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); }
6,451,473
/** *Submitted for verification at Etherscan.io on 2020-10-04 */ // SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.6.12; library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; require(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { require(b > 0); uint c = a / b; require(a == b * c + a % b); return c; } function sub(uint a, uint b) internal pure returns (uint) { require(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a); return c; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint a, uint b) internal pure returns (uint) { return a >= b ? a : b; } function min256(uint a, uint b) internal pure returns (uint) { return a < b ? a : b; } } interface ISupplyController { function mint(address token, address owner, uint amount) external; } interface IADXToken { function transfer(address to, uint256 amount) external returns (bool); function transferFrom(address from, address to, uint256 amount) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function balanceOf(address spender) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function supplyController() external view returns (ISupplyController); } contract ADXLoyaltyPoolToken { using SafeMath for uint; // ERC20 stuff // Constants string public constant name = "AdEx Loyalty"; uint8 public constant decimals = 18; string public symbol = "ADX-LOYALTY"; // Mutable variables uint public totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // EIP 2612 bytes32 public DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint) public nonces; // ERC20 events event Approval(address indexed owner, address indexed spender, uint amount); event Transfer(address indexed from, address indexed to, uint amount); function balanceOf(address owner) public view returns (uint balance) { //inject PUBLIC FUNC TO EXTERNAL return balances[owner]; } function transfer(address to, uint amount) public returns (bool success) { //inject PUBLIC FUNC TO EXTERNAL require(to != address(this), 'BAD_ADDRESS'); balances[msg.sender] = balances[msg.sender].sub(amount); balances[to] = balances[to].add(amount); emit Transfer(msg.sender, to, amount); return true; } function transferFrom(address from, address to, uint amount) public returns (bool success) { //inject PUBLIC FUNC TO EXTERNAL balances[from] = balances[from].sub(amount); allowed[from][msg.sender] = allowed[from][msg.sender].sub(amount); balances[to] = balances[to].add(amount); emit Transfer(from, to, amount); return true; } function approve(address spender, uint amount) public returns (bool success) { //inject PUBLIC FUNC TO EXTERNAL allowed[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function allowance(address owner, address spender) public view returns (uint remaining) { //inject PUBLIC FUNC TO EXTERNAL return allowed[owner][spender]; } // EIP 2612 function permit(address owner, address spender, uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) public { //inject PUBLIC FUNC TO EXTERNAL require(deadline >= block.timestamp, 'DEADLINE_EXPIRED'); bytes32 digest = keccak256(abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline)) )); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, 'INVALID_SIGNATURE'); allowed[owner][spender] = amount; emit Approval(owner, spender, amount); } // Inner function innerMint(address owner, uint amount) internal { totalSupply = totalSupply.add(amount); balances[owner] = balances[owner].add(amount); // Because of https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer-1 emit Transfer(address(0), owner, amount); } function innerBurn(address owner, uint amount) internal { totalSupply = totalSupply.sub(amount); balances[owner] = balances[owner].sub(amount); emit Transfer(owner, address(0), amount); } // Pool functionality event LogSetGovernance(address indexed addr, bool hasGovt, uint time); event LogSetIncentive(uint incentive, uint time); IADXToken public ADXToken; uint public incentivePerTokenPerAnnum; uint public lastMintTime; uint public maxTotalADX; mapping (address => bool) public governance; constructor(IADXToken token, uint incentive, uint cap) public { ADXToken = token; incentivePerTokenPerAnnum = incentive; maxTotalADX = cap; governance[msg.sender] = true; lastMintTime = block.timestamp; // EIP 2612 uint chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(name)), keccak256(bytes('1')), chainId, address(this) ) ); emit LogSetGovernance(msg.sender, true, block.timestamp); emit LogSetIncentive(incentive, block.timestamp); } // Governance functions function setGovernance(address addr, bool hasGovt) public { //inject PUBLIC FUNC TO EXTERNAL require(governance[msg.sender], 'NOT_GOVERNANCE'); governance[addr] = hasGovt; emit LogSetGovernance(addr, hasGovt, block.timestamp); } // This doesn't trigger a mint because otherwise we risk of being unable to setIncentive to 0 // if minting is impossible // It's the better tradeoff to make - and the issue of front-running mintIncnetive with setIncentive(0) can // be solved by timelocking the governance function setIncentive(uint newIncentive) public { //inject PUBLIC FUNC TO EXTERNAL require(governance[msg.sender], 'NOT_GOVERNANCE'); incentivePerTokenPerAnnum = newIncentive; lastMintTime = block.timestamp; emit LogSetIncentive(newIncentive, block.timestamp); } function setSymbol(string calldata newSymbol) external { require(governance[msg.sender], 'NOT_GOVERNANCE'); symbol = newSymbol; } function setMaxTotalADX(uint newMaxTotalADX) public { //inject PUBLIC FUNC TO EXTERNAL require(governance[msg.sender], 'NOT_GOVERNANCE'); maxTotalADX = newMaxTotalADX; } // Pool stuff // There are a few notable items in how minting works // 1) if ADX is sent to the LoyaltyPool in-between mints, it will calculate the incentive as if this amount // has been there the whole time since the last mint // 2) Compounding is happening when mint is called, so essentially when entities enter/leave/trigger it manually function toMint() public view returns (uint) { //inject PUBLIC FUNC TO EXTERNAL if (block.timestamp <= lastMintTime) return 0; uint totalADX = ADXToken.balanceOf(address(this)); return (block.timestamp - lastMintTime) .mul(totalADX) .mul(incentivePerTokenPerAnnum) .div(365 days * 10e17); } function shareValue() public view returns (uint) { //inject PUBLIC FUNC TO EXTERNAL if (totalSupply == 0) return 0; return ADXToken.balanceOf(address(this)) .add(this.toMint()) .mul(10e17) .div(totalSupply); } function mintIncentive() public { if (incentivePerTokenPerAnnum == 0) return; uint amountToMint = this.toMint(); if (amountToMint == 0) return; lastMintTime = block.timestamp; ADXToken.supplyController().mint(address(ADXToken), address(this), amountToMint); } function enter(uint256 amount) public { //inject PUBLIC FUNC TO EXTERNAL // Please note that minting has to be in the beginning so that we take it into account // when using ADXToken.balanceOf() // Minting makes an external call but it's to a trusted contract (ADXToken) mintIncentive(); uint totalADX = ADXToken.balanceOf(address(this)); require(totalADX.add(amount) <= maxTotalADX, 'REACHED_MAX_TOTAL_ADX'); // The totalADX == 0 check here should be redudnant; the only way to get totalSupply to a nonzero val is by adding ADX if (totalSupply == 0 || totalADX == 0) { innerMint(msg.sender, amount); } else { uint256 newShares = amount.mul(totalSupply).div(totalADX); innerMint(msg.sender, newShares); } require(ADXToken.transferFrom(msg.sender, address(this), amount)); } function leaveInner(uint256 shares) internal { uint256 totalADX = ADXToken.balanceOf(address(this)); uint256 adxAmount = shares.mul(totalADX).div(totalSupply); innerBurn(msg.sender, shares); require(ADXToken.transfer(msg.sender, adxAmount)); } function leave(uint256 shares) public { //inject PUBLIC FUNC TO EXTERNAL mintIncentive(); leaveInner(shares); } // Guarantees ADX can be taken out even if minting is failing function emergencyLeave(uint256 shares) public { //inject PUBLIC FUNC TO EXTERNAL leaveInner(shares); } }
inject PUBLIC FUNC TO EXTERNAL
function setGovernance(address addr, bool hasGovt) public {
2,519,496
./partial_match/1/0x1E6EB746EC5dbDe097223dD1bb3031310321e33B/sources/UreeqaCollectibleNFTv2.sol
Performs the resolution and then marks it as passed. No checks prevent it from performing the resolutions.
function _performResolution(uint256 resNum) internal { if (resolutions[resNum].resType == resTypeAddOwner) { _addOwner(resolutions[resNum].newAddress); _removeOwner(resolutions[resNum].oldAddress); _replaceOwner( resolutions[resNum].oldAddress, resolutions[resNum].newAddress ); _addOperator(resolutions[resNum].newAddress); _removeOperator(resolutions[resNum].oldAddress); _replaceOperator( resolutions[resNum].oldAddress, resolutions[resNum].newAddress ); } else if ( resolutions[resNum].resType == resTypeUpdateTransactionLimit ) { _updateTransactionLimit(uint160(resolutions[resNum].newAddress)); _updateThreshold(uint160(resolutions[resNum].newAddress)); _pause(); _unpause(); _customResolutions(resNum); return; } resolutions[resNum].passed = true; }
2,597,310
./full_match/1/0x2F53e033C55eB6C87CEa259123C0a68Ca3578426/sources/contracts/WorldsEscrow.sol
Claim all rewards from caller into a given address
function claim(address _to) external nonReentrant checkForUpgrade { _updateRewardsPerWeight(0, false); uint rewardAmount = _updateUserRewards(_msgSender(), 0, false); WorldsEscrowStorage.layout().rewards[_msgSender()].accumulated = 0; TransferHelper.safeTransfer(WorldsEscrowStorage.layout().rewardTokenAddress, _to, rewardAmount); emit RewardClaimed(_to, rewardAmount); }
17,079,643
./full_match/4/0x09d6b61953547fC17F16F0690c94c1d0d79Cae36/sources/contracts/mapping.sol
with this function the user sets their best fruit
function setBestFruit(string memory fruit) public { fruits[msg.sender] = fruit; }
13,353,389
./full_match/1/0xd446315C7e4fA5354d019970e1a4C6045bB133af/sources/contracts/Uniswap/UniswapAnchoredView.sol
Calculate the anchor price by fetching price data from the TWAP config TokenConfig return anchorPrice uint/
function calculateAnchorPriceFromEthPrice(TokenConfig memory config) internal view returns (uint256 anchorPrice) { require(config.priceSource == PriceSource.REPORTER, "Reporter only"); uint256 ethPrice = fetchEthPrice(); if (config.symbolHash == ETH_HASH) { anchorPrice = ethPrice; anchorPrice = fetchAnchorPrice(config, ethPrice); } }
3,182,764
./partial_match/1/0x5B17f168829968D9fb5F049b45b14b7601AFf85B/sources/ions/ERC721_Remote_Store.sol
Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is forwarded in {IERC721Receiver-onERC721Received} to contract recipients./
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "438"); }
11,032,361
// File: contracts/ERC721.sol // eterart-contract // contracts/ERC721.sol pragma solidity ^0.4.24; /** * @title ERC-721 contract interface. */ contract ERC721 { // ERC20 compatible functions. function name() public constant returns (string); function symbol() public constant returns (string); function totalSupply() public constant returns (uint256); function balanceOf(address _owner) public constant returns (uint); // Functions that define ownership. function ownerOf(uint256 _tokenId) public constant returns (address); function approve(address _to, uint256 _tokenId) public; function takeOwnership(uint256 _tokenId) public; function transfer(address _to, uint256 _tokenId) public; function tokenOfOwnerByIndex(address _owner, uint256 _index) public constant returns (uint); // Token metadata. function tokenMetadata(uint256 _tokenId) public constant returns (string); // Events. event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); } // File: contracts/EterArt.sol // eterart-contract // contracts/EterArt.sol pragma solidity ^0.4.24; /** * @title EterArt contract. */ contract EterArt is ERC721 { // Art structure for tokens ownership registry. struct Art { uint256 price; address owner; address newOwner; } struct Token { uint256[] items; mapping(uint256 => uint) lookup; } // Mapping from token ID to owner. mapping (address => Token) internal ownedTokens; // All minted tokens number (ERC-20 compatibility). uint256 public totalTokenSupply; // Token issuer address address public _issuer; // Tokens ownership registry. mapping (uint => Art) public registry; // Token metadata base URL. string public baseInfoUrl = "https://www.eterart.com/art/"; // Fee in percents uint public feePercent = 5; // Change price event event ChangePrice(uint indexed token, uint indexed price); /** * @dev Constructor sets the `issuer` of the contract to the sender * account. */ constructor() public { _issuer = msg.sender; } /** * @return the address of the issuer. */ function issuer() public view returns(address) { return _issuer; } /** * @dev Reject all Ether from being sent here. (Hopefully, we can prevent user accidents.) */ function() external payable { require(msg.sender == address(this)); } /** * @dev Gets token name (ERC-20 compatibility). * @return string token name. */ function name() public constant returns (string) { return "EterArt"; } /** * @dev Gets token symbol (ERC-20 compatibility). * @return string token symbol. */ function symbol() public constant returns (string) { return "WAW"; } /** * @dev Gets token URL. * @param _tokenId uint256 ID of the token to get URL of. * @return string token URL. */ function tokenMetadata(uint256 _tokenId) public constant returns (string) { return strConcat(baseInfoUrl, strConcat("0x", uint2hexstr(_tokenId))); } /** * @dev Gets contract all minted tokens number. * @return uint256 contract all minted tokens number. */ function totalSupply() public constant returns (uint256) { return totalTokenSupply; } /** * @dev Gets tokens number of specified address. * @param _owner address to query tokens number of. * @return uint256 number of tokens owned by the specified address. */ function balanceOf(address _owner) public constant returns (uint balance) { balance = ownedTokens[_owner].items.length; } /** * @dev Gets token by index of specified address. * @param _owner address to query tokens number of. * @param _index uint256 index of the token to get. * @return uint256 token ID from specified address tokens list by specified index. */ function tokenOfOwnerByIndex(address _owner, uint256 _index) public constant returns (uint tokenId) { tokenId = ownedTokens[_owner].items[_index]; } /** * @dev Approve token ownership transfer to another address. * @param _to address to change token ownership to. * @param _tokenId uint256 token ID to change ownership of. */ function approve(address _to, uint256 _tokenId) public { require(_to != msg.sender); require(registry[_tokenId].owner == msg.sender); registry[_tokenId].newOwner = _to; emit Approval(registry[_tokenId].owner, _to, _tokenId); } /** * @dev Internal method that transfer token to another address. * Run some checks and internal contract data manipulations. * @param _to address new token owner address. * @param _tokenId uint256 token ID to transfer to specified address. */ function _transfer(address _to, uint256 _tokenId) internal { if (registry[_tokenId].owner != address(0)) { require(registry[_tokenId].owner != _to); removeByValue(registry[_tokenId].owner, _tokenId); } else { totalTokenSupply = totalTokenSupply + 1; } require(_to != address(0)); push(_to, _tokenId); emit Transfer(registry[_tokenId].owner, _to, _tokenId); registry[_tokenId].owner = _to; registry[_tokenId].newOwner = address(0); registry[_tokenId].price = 0; } /** * @dev Take ownership of specified token. * Only if current token owner approve that. * @param _tokenId uint256 token ID to take ownership of. */ function takeOwnership(uint256 _tokenId) public { require(registry[_tokenId].newOwner == msg.sender); _transfer(msg.sender, _tokenId); } /** * @dev Change baseInfoUrl contract property value. * @param url string new baseInfoUrl value. */ function changeBaseInfoUrl(string url) public { require(msg.sender == _issuer); baseInfoUrl = url; } /** * @dev Change issuer contract address. * @param _to address of new contract issuer. */ function changeIssuer(address _to) public { require(msg.sender == _issuer); _issuer = _to; } /** * @dev Withdraw all contract balance value to contract issuer. */ function withdraw() public { require(msg.sender == _issuer); withdraw(_issuer, address(this).balance); } /** * @dev Withdraw all contract balance value to specified address. * @param _to address to transfer value. */ function withdraw(address _to) public { require(msg.sender == _issuer); withdraw(_to, address(this).balance); } /** * @dev Withdraw specified wei number to address. * @param _to address to transfer value. * @param _value uint wei amount value. */ function withdraw(address _to, uint _value) public { require(msg.sender == _issuer); require(_value <= address(this).balance); _to.transfer(address(this).balance); } /** * @dev Gets specified token owner address. * @param token uint256 token ID. * @return address specified token owner address. */ function ownerOf(uint256 token) public constant returns (address owner) { owner = registry[token].owner; } /** * @dev Gets specified token price. * @param token uint256 token ID. * @return uint specified token price. */ function getPrice(uint token) public view returns (uint) { return registry[token].price; } /** * @dev Direct transfer specified token to another address. * @param _to address new token owner address. * @param _tokenId uint256 token ID to transfer to specified address. */ function transfer(address _to, uint256 _tokenId) public { require(registry[_tokenId].owner == msg.sender); _transfer(_to, _tokenId); } /** * @dev Change specified token price. * Used for: change token price, * withdraw token from sale (set token price to 0 (zero)) * and for put up token for sale (set token price > 0) * @param token uint token ID to change price of. * @param price uint new token price. */ function changePrice(uint token, uint price) public { require(registry[token].owner == msg.sender); registry[token].price = price; emit ChangePrice(token, price); } /** * @dev Buy specified token if it's marked as for sale (token price > 0). * Run some checks, calculate fee and transfer token to msg.sender. * @param _tokenId uint token ID to buy. */ function buy(uint _tokenId) public payable { require(registry[_tokenId].price > 0); uint fee = ((registry[_tokenId].price / 100) * feePercent); uint value = msg.value - fee; require(registry[_tokenId].price <= value); registry[_tokenId].owner.transfer(value); _transfer(msg.sender, _tokenId); } /** * @dev Mint token. */ function mint(uint _tokenId, address _to) public { require(msg.sender == _issuer); require(registry[_tokenId].owner == 0x0); _transfer(_to, _tokenId); } /** * @dev Mint token. */ function mint( string length, uint _tokenId, uint price, uint8 v, bytes32 r, bytes32 s ) public payable { string memory m_price = uint2hexstr(price); string memory m_token = uint2hexstr(_tokenId); require(msg.value >= price); require(ecrecover(keccak256("\x19Ethereum Signed Message:\n", length, m_token, m_price), v, r, s) == _issuer); require(registry[_tokenId].owner == 0x0); _transfer(msg.sender, _tokenId); } /** * UTILS */ /** * @dev Add token to specified address tokens list. * @param owner address address of token owner to add token to. * @param value uint token ID to add. */ function push(address owner, uint value) private { if (ownedTokens[owner].lookup[value] > 0) { return; } ownedTokens[owner].lookup[value] = ownedTokens[owner].items.push(value); } /** * @dev Remove token by ID from specified address tokens list. * @param owner address address of token owner to remove token from. * @param value uint token ID to remove. */ function removeByValue(address owner, uint value) private { uint index = ownedTokens[owner].lookup[value]; if (index == 0) { return; } if (index < ownedTokens[owner].items.length) { uint256 lastItem = ownedTokens[owner].items[ownedTokens[owner].items.length - 1]; ownedTokens[owner].items[index - 1] = lastItem; ownedTokens[owner].lookup[lastItem] = index; } ownedTokens[owner].items.length -= 1; delete ownedTokens[owner].lookup[value]; } /** * @dev String concatenation. * @param _a string first string. * @param _b string second string. * @return string result of string concatenation. */ function strConcat(string _a, string _b) internal pure returns (string){ bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); string memory abcde = new string(_ba.length + _bb.length); bytes memory babcde = bytes(abcde); uint k = 0; for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i]; for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i]; return string(babcde); } /** * @dev Convert long to hex string. * @param i uint value to convert. * @return string specified value converted to hex string. */ function uint2hexstr(uint i) internal pure returns (string) { if (i == 0) return "0"; uint j = i; uint length; while (j != 0) { length++; j = j >> 4; } uint mask = 15; bytes memory bstr = new bytes(length); uint k = length - 1; while (i != 0) { uint curr = (i & mask); bstr[k--] = curr > 9 ? byte(55 + curr) : byte(48 + curr); // 55 = 65 - 10 i = i >> 4; } return string(bstr); } }
Direct transfer specified token to another address. _to address new token owner address. _tokenId uint256 token ID to transfer to specified address./
function transfer(address _to, uint256 _tokenId) public { require(registry[_tokenId].owner == msg.sender); _transfer(_to, _tokenId); }
14,042,380
./full_match/43113/0xbd87Cf35D0fCd510b91b22fee7cc5790edA7b60a/sources/apps/avai/src/contracts/Stablecoin.sol
No need for SafeMath in solidity ^0.8.0, built in overflow checking using SafeMath for uint256; The vaults that users can use
{ bytes32 public constant BURNER_ROLE = keccak256('BURNER_ROLE'); bytes32 public constant MINTER_ROLE = keccak256('MINTER_ROLE'); address[] public vaults; event CreateVaultType(uint256 vaultID, address vault); pragma solidity ^0.8.0; function initialize(string memory name, address vault_) public initializer { __Context_init_unchained(); __ERC20_init_unchained(name, name); __EIP712_init_unchained(name, '1'); __ERC20Permit_init_unchained(name); __ERC165_init_unchained(); __AccessControl_init_unchained(); __UpgradeableBeacon__init(vault_); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } function vaultCount() external view returns (uint256) { return vaults.length; } function burn(address from, uint256 amount) external onlyRole(BURNER_ROLE) { _burn(from, amount); } function mint(address account, uint256 amount) external onlyRole(MINTER_ROLE) { _mint(account, amount); } function addVault( uint256 minimumCollateralPercentage_, address priceSource_, string calldata name_, string calldata symbol_, address token_ ) external onlyRole(DEFAULT_ADMIN_ROLE) returns (address) { address proxy = address(new BeaconProxy(address(this), '')); BaseVault(proxy).initialize( minimumCollateralPercentage_, priceSource_, name_, symbol_, token_, msg.sender ); vaults.push(proxy); _setupRole(BURNER_ROLE, proxy); _setupRole(MINTER_ROLE, proxy); return proxy; } }
13,146,384
./full_match/11297108109/0x19D4F9A260AF1d7E0E99A32DBe418956af875c25/sources/contracts/NFTCollection/NFTCollectionBase.sol
xref:ROOT:erc1155.adocbatch-operations[Batched] version of {_burn}. Requirements: - `ids` and `amounts` must have the same length./
function _burnBatch( address account, uint256[] memory ids, uint256[] memory amounts ) internal virtual { _checkNotZeroAddress(account); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][account] = _balances[ids[i]][account].sub( amounts[i], "Insufficient balance" ); } emit TransferBatch(_msgSender(), account, address(0), ids, amounts); }
13,236,849
./partial_match/1/0x1473F3e4d236CBBe3412b9f65B4c210756BE2C0E/sources/src/abstracts/EthUsdChainlinkOracleWithMaxDelay.sol
The ```getEthUsdChainlinkPrice``` function is called to get the eth/usd price from Chainlink return _isBadData If the data is stale return _updatedAt The timestamp of the last update return _usdPerEth The eth/usd price
function getEthUsdChainlinkPrice() external view virtual returns (bool _isBadData, uint256 _updatedAt, uint256 _usdPerEth) { (_isBadData, _updatedAt, _usdPerEth) = _getEthUsdChainlinkPrice(); }
4,389,266
./full_match/7700/0x9B2a63F27661A468E2da22226b64A4914144f195/sources/contracts/mixins/TickCensus.sol
Splits out the lobby bits and the mezzanine bits from the 24-bit price tick index associated with the type of border tick used in seekMezzSpill() call / Because pinTermMezz returns a border on the previous bitmap, we need to decrement by one to get the seek starting point.
function rootsForBorder (int24 borderTick, bool isUpper) private pure returns (uint8 lobbyBit, uint8 mezzBit) { int24 pinTick = isUpper ? borderTick : (borderTick - 1); lobbyBit = pinTick.lobbyBit(); mezzBit = pinTick.mezzBit(); }
4,651,084